1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Shared application/kernel submission and completion ring pairs, for 4 * supporting fast/efficient IO. 5 * 6 * A note on the read/write ordering memory barriers that are matched between 7 * the application and kernel side. 8 * 9 * After the application reads the CQ ring tail, it must use an 10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses 11 * before writing the tail (using smp_load_acquire to read the tail will 12 * do). It also needs a smp_mb() before updating CQ head (ordering the 13 * entry load(s) with the head store), pairing with an implicit barrier 14 * through a control-dependency in io_get_cqe (smp_store_release to 15 * store head will do). Failure to do so could lead to reading invalid 16 * CQ entries. 17 * 18 * Likewise, the application must use an appropriate smp_wmb() before 19 * writing the SQ tail (ordering SQ entry stores with the tail store), 20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release 21 * to store the tail will do). And it needs a barrier ordering the SQ 22 * head load before writing new SQ entries (smp_load_acquire to read 23 * head will do). 24 * 25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application 26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after* 27 * updating the SQ tail; a full memory barrier smp_mb() is needed 28 * between. 29 * 30 * Also see the examples in the liburing library: 31 * 32 * git://git.kernel.dk/liburing 33 * 34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens 35 * from data shared between the kernel and application. This is done both 36 * for ordering purposes, but also to ensure that once a value is loaded from 37 * data that the application could potentially modify, it remains stable. 38 * 39 * Copyright (C) 2018-2019 Jens Axboe 40 * Copyright (c) 2018-2019 Christoph Hellwig 41 */ 42 #include <linux/kernel.h> 43 #include <linux/init.h> 44 #include <linux/errno.h> 45 #include <linux/syscalls.h> 46 #include <net/compat.h> 47 #include <linux/refcount.h> 48 #include <linux/uio.h> 49 #include <linux/bits.h> 50 51 #include <linux/sched/signal.h> 52 #include <linux/fs.h> 53 #include <linux/file.h> 54 #include <linux/fdtable.h> 55 #include <linux/mm.h> 56 #include <linux/mman.h> 57 #include <linux/percpu.h> 58 #include <linux/slab.h> 59 #include <linux/bvec.h> 60 #include <linux/net.h> 61 #include <net/sock.h> 62 #include <net/af_unix.h> 63 #include <linux/anon_inodes.h> 64 #include <linux/sched/mm.h> 65 #include <linux/uaccess.h> 66 #include <linux/nospec.h> 67 #include <linux/highmem.h> 68 #include <linux/fsnotify.h> 69 #include <linux/fadvise.h> 70 #include <linux/task_work.h> 71 #include <linux/io_uring.h> 72 #include <linux/audit.h> 73 #include <linux/security.h> 74 #include <asm/shmparam.h> 75 76 #define CREATE_TRACE_POINTS 77 #include <trace/events/io_uring.h> 78 79 #include <uapi/linux/io_uring.h> 80 81 #include "io-wq.h" 82 83 #include "io_uring.h" 84 #include "opdef.h" 85 #include "refs.h" 86 #include "tctx.h" 87 #include "sqpoll.h" 88 #include "fdinfo.h" 89 #include "kbuf.h" 90 #include "rsrc.h" 91 #include "cancel.h" 92 #include "net.h" 93 #include "notif.h" 94 95 #include "timeout.h" 96 #include "poll.h" 97 #include "rw.h" 98 #include "alloc_cache.h" 99 100 #define IORING_MAX_ENTRIES 32768 101 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES) 102 103 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \ 104 IORING_REGISTER_LAST + IORING_OP_LAST) 105 106 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \ 107 IOSQE_IO_HARDLINK | IOSQE_ASYNC) 108 109 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \ 110 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS) 111 112 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \ 113 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \ 114 REQ_F_ASYNC_DATA) 115 116 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\ 117 IO_REQ_CLEAN_FLAGS) 118 119 #define IO_TCTX_REFS_CACHE_NR (1U << 10) 120 121 #define IO_COMPL_BATCH 32 122 #define IO_REQ_ALLOC_BATCH 8 123 124 enum { 125 IO_CHECK_CQ_OVERFLOW_BIT, 126 IO_CHECK_CQ_DROPPED_BIT, 127 }; 128 129 enum { 130 IO_EVENTFD_OP_SIGNAL_BIT, 131 IO_EVENTFD_OP_FREE_BIT, 132 }; 133 134 struct io_defer_entry { 135 struct list_head list; 136 struct io_kiocb *req; 137 u32 seq; 138 }; 139 140 /* requests with any of those set should undergo io_disarm_next() */ 141 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL) 142 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK) 143 144 static bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx, 145 struct task_struct *task, 146 bool cancel_all); 147 148 static void io_queue_sqe(struct io_kiocb *req); 149 150 struct kmem_cache *req_cachep; 151 static struct workqueue_struct *iou_wq __ro_after_init; 152 153 static int __read_mostly sysctl_io_uring_disabled; 154 static int __read_mostly sysctl_io_uring_group = -1; 155 156 #ifdef CONFIG_SYSCTL 157 static struct ctl_table kernel_io_uring_disabled_table[] = { 158 { 159 .procname = "io_uring_disabled", 160 .data = &sysctl_io_uring_disabled, 161 .maxlen = sizeof(sysctl_io_uring_disabled), 162 .mode = 0644, 163 .proc_handler = proc_dointvec_minmax, 164 .extra1 = SYSCTL_ZERO, 165 .extra2 = SYSCTL_TWO, 166 }, 167 { 168 .procname = "io_uring_group", 169 .data = &sysctl_io_uring_group, 170 .maxlen = sizeof(gid_t), 171 .mode = 0644, 172 .proc_handler = proc_dointvec, 173 }, 174 {}, 175 }; 176 #endif 177 io_submit_flush_completions(struct io_ring_ctx * ctx)178 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx) 179 { 180 if (!wq_list_empty(&ctx->submit_state.compl_reqs) || 181 ctx->submit_state.cqes_count) 182 __io_submit_flush_completions(ctx); 183 } 184 __io_cqring_events(struct io_ring_ctx * ctx)185 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx) 186 { 187 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head); 188 } 189 __io_cqring_events_user(struct io_ring_ctx * ctx)190 static inline unsigned int __io_cqring_events_user(struct io_ring_ctx *ctx) 191 { 192 return READ_ONCE(ctx->rings->cq.tail) - READ_ONCE(ctx->rings->cq.head); 193 } 194 io_match_linked(struct io_kiocb * head)195 static bool io_match_linked(struct io_kiocb *head) 196 { 197 struct io_kiocb *req; 198 199 io_for_each_link(req, head) { 200 if (req->flags & REQ_F_INFLIGHT) 201 return true; 202 } 203 return false; 204 } 205 206 /* 207 * As io_match_task() but protected against racing with linked timeouts. 208 * User must not hold timeout_lock. 209 */ io_match_task_safe(struct io_kiocb * head,struct task_struct * task,bool cancel_all)210 bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task, 211 bool cancel_all) 212 { 213 bool matched; 214 215 if (task && head->task != task) 216 return false; 217 if (cancel_all) 218 return true; 219 220 if (head->flags & REQ_F_LINK_TIMEOUT) { 221 struct io_ring_ctx *ctx = head->ctx; 222 223 /* protect against races with linked timeouts */ 224 spin_lock_irq(&ctx->timeout_lock); 225 matched = io_match_linked(head); 226 spin_unlock_irq(&ctx->timeout_lock); 227 } else { 228 matched = io_match_linked(head); 229 } 230 return matched; 231 } 232 req_fail_link_node(struct io_kiocb * req,int res)233 static inline void req_fail_link_node(struct io_kiocb *req, int res) 234 { 235 req_set_fail(req); 236 io_req_set_res(req, res, 0); 237 } 238 io_req_add_to_cache(struct io_kiocb * req,struct io_ring_ctx * ctx)239 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx) 240 { 241 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list); 242 } 243 io_ring_ctx_ref_free(struct percpu_ref * ref)244 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref) 245 { 246 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs); 247 248 complete(&ctx->ref_comp); 249 } 250 io_fallback_req_func(struct work_struct * work)251 static __cold void io_fallback_req_func(struct work_struct *work) 252 { 253 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, 254 fallback_work.work); 255 struct llist_node *node = llist_del_all(&ctx->fallback_llist); 256 struct io_kiocb *req, *tmp; 257 struct io_tw_state ts = { .locked = true, }; 258 259 percpu_ref_get(&ctx->refs); 260 mutex_lock(&ctx->uring_lock); 261 llist_for_each_entry_safe(req, tmp, node, io_task_work.node) 262 req->io_task_work.func(req, &ts); 263 if (WARN_ON_ONCE(!ts.locked)) 264 return; 265 io_submit_flush_completions(ctx); 266 mutex_unlock(&ctx->uring_lock); 267 percpu_ref_put(&ctx->refs); 268 } 269 io_alloc_hash_table(struct io_hash_table * table,unsigned bits)270 static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits) 271 { 272 unsigned hash_buckets = 1U << bits; 273 size_t hash_size = hash_buckets * sizeof(table->hbs[0]); 274 275 table->hbs = kmalloc(hash_size, GFP_KERNEL); 276 if (!table->hbs) 277 return -ENOMEM; 278 279 table->hash_bits = bits; 280 init_hash_table(table, hash_buckets); 281 return 0; 282 } 283 io_ring_ctx_alloc(struct io_uring_params * p)284 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p) 285 { 286 struct io_ring_ctx *ctx; 287 int hash_bits; 288 289 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); 290 if (!ctx) 291 return NULL; 292 293 xa_init(&ctx->io_bl_xa); 294 295 /* 296 * Use 5 bits less than the max cq entries, that should give us around 297 * 32 entries per hash list if totally full and uniformly spread, but 298 * don't keep too many buckets to not overconsume memory. 299 */ 300 hash_bits = ilog2(p->cq_entries) - 5; 301 hash_bits = clamp(hash_bits, 1, 8); 302 if (io_alloc_hash_table(&ctx->cancel_table, hash_bits)) 303 goto err; 304 if (io_alloc_hash_table(&ctx->cancel_table_locked, hash_bits)) 305 goto err; 306 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free, 307 0, GFP_KERNEL)) 308 goto err; 309 310 ctx->flags = p->flags; 311 init_waitqueue_head(&ctx->sqo_sq_wait); 312 INIT_LIST_HEAD(&ctx->sqd_list); 313 INIT_LIST_HEAD(&ctx->cq_overflow_list); 314 INIT_LIST_HEAD(&ctx->io_buffers_cache); 315 INIT_HLIST_HEAD(&ctx->io_buf_list); 316 io_alloc_cache_init(&ctx->rsrc_node_cache, IO_NODE_ALLOC_CACHE_MAX, 317 sizeof(struct io_rsrc_node)); 318 io_alloc_cache_init(&ctx->apoll_cache, IO_ALLOC_CACHE_MAX, 319 sizeof(struct async_poll)); 320 io_alloc_cache_init(&ctx->netmsg_cache, IO_ALLOC_CACHE_MAX, 321 sizeof(struct io_async_msghdr)); 322 init_completion(&ctx->ref_comp); 323 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1); 324 mutex_init(&ctx->uring_lock); 325 init_waitqueue_head(&ctx->cq_wait); 326 init_waitqueue_head(&ctx->poll_wq); 327 init_waitqueue_head(&ctx->rsrc_quiesce_wq); 328 spin_lock_init(&ctx->completion_lock); 329 spin_lock_init(&ctx->timeout_lock); 330 INIT_WQ_LIST(&ctx->iopoll_list); 331 INIT_LIST_HEAD(&ctx->io_buffers_pages); 332 INIT_LIST_HEAD(&ctx->io_buffers_comp); 333 INIT_LIST_HEAD(&ctx->defer_list); 334 INIT_LIST_HEAD(&ctx->timeout_list); 335 INIT_LIST_HEAD(&ctx->ltimeout_list); 336 INIT_LIST_HEAD(&ctx->rsrc_ref_list); 337 init_llist_head(&ctx->work_llist); 338 INIT_LIST_HEAD(&ctx->tctx_list); 339 ctx->submit_state.free_list.next = NULL; 340 INIT_WQ_LIST(&ctx->locked_free_list); 341 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func); 342 INIT_WQ_LIST(&ctx->submit_state.compl_reqs); 343 return ctx; 344 err: 345 kfree(ctx->cancel_table.hbs); 346 kfree(ctx->cancel_table_locked.hbs); 347 xa_destroy(&ctx->io_bl_xa); 348 kfree(ctx); 349 return NULL; 350 } 351 io_account_cq_overflow(struct io_ring_ctx * ctx)352 static void io_account_cq_overflow(struct io_ring_ctx *ctx) 353 { 354 struct io_rings *r = ctx->rings; 355 356 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1); 357 ctx->cq_extra--; 358 } 359 req_need_defer(struct io_kiocb * req,u32 seq)360 static bool req_need_defer(struct io_kiocb *req, u32 seq) 361 { 362 if (unlikely(req->flags & REQ_F_IO_DRAIN)) { 363 struct io_ring_ctx *ctx = req->ctx; 364 365 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail; 366 } 367 368 return false; 369 } 370 io_clean_op(struct io_kiocb * req)371 static void io_clean_op(struct io_kiocb *req) 372 { 373 if (req->flags & REQ_F_BUFFER_SELECTED) { 374 spin_lock(&req->ctx->completion_lock); 375 io_put_kbuf_comp(req); 376 spin_unlock(&req->ctx->completion_lock); 377 } 378 379 if (req->flags & REQ_F_NEED_CLEANUP) { 380 const struct io_cold_def *def = &io_cold_defs[req->opcode]; 381 382 if (def->cleanup) 383 def->cleanup(req); 384 } 385 if ((req->flags & REQ_F_POLLED) && req->apoll) { 386 kfree(req->apoll->double_poll); 387 kfree(req->apoll); 388 req->apoll = NULL; 389 } 390 if (req->flags & REQ_F_INFLIGHT) { 391 struct io_uring_task *tctx = req->task->io_uring; 392 393 atomic_dec(&tctx->inflight_tracked); 394 } 395 if (req->flags & REQ_F_CREDS) 396 put_cred(req->creds); 397 if (req->flags & REQ_F_ASYNC_DATA) { 398 kfree(req->async_data); 399 req->async_data = NULL; 400 } 401 req->flags &= ~IO_REQ_CLEAN_FLAGS; 402 } 403 io_req_track_inflight(struct io_kiocb * req)404 static inline void io_req_track_inflight(struct io_kiocb *req) 405 { 406 if (!(req->flags & REQ_F_INFLIGHT)) { 407 req->flags |= REQ_F_INFLIGHT; 408 atomic_inc(&req->task->io_uring->inflight_tracked); 409 } 410 } 411 __io_prep_linked_timeout(struct io_kiocb * req)412 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req) 413 { 414 if (WARN_ON_ONCE(!req->link)) 415 return NULL; 416 417 req->flags &= ~REQ_F_ARM_LTIMEOUT; 418 req->flags |= REQ_F_LINK_TIMEOUT; 419 420 /* linked timeouts should have two refs once prep'ed */ 421 io_req_set_refcount(req); 422 __io_req_set_refcount(req->link, 2); 423 return req->link; 424 } 425 io_prep_linked_timeout(struct io_kiocb * req)426 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req) 427 { 428 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT))) 429 return NULL; 430 return __io_prep_linked_timeout(req); 431 } 432 __io_arm_ltimeout(struct io_kiocb * req)433 static noinline void __io_arm_ltimeout(struct io_kiocb *req) 434 { 435 io_queue_linked_timeout(__io_prep_linked_timeout(req)); 436 } 437 io_arm_ltimeout(struct io_kiocb * req)438 static inline void io_arm_ltimeout(struct io_kiocb *req) 439 { 440 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT)) 441 __io_arm_ltimeout(req); 442 } 443 io_prep_async_work(struct io_kiocb * req)444 static void io_prep_async_work(struct io_kiocb *req) 445 { 446 const struct io_issue_def *def = &io_issue_defs[req->opcode]; 447 struct io_ring_ctx *ctx = req->ctx; 448 449 if (!(req->flags & REQ_F_CREDS)) { 450 req->flags |= REQ_F_CREDS; 451 req->creds = get_current_cred(); 452 } 453 454 req->work.list.next = NULL; 455 req->work.flags = 0; 456 req->work.cancel_seq = atomic_read(&ctx->cancel_seq); 457 if (req->flags & REQ_F_FORCE_ASYNC) 458 req->work.flags |= IO_WQ_WORK_CONCURRENT; 459 460 if (req->file && !(req->flags & REQ_F_FIXED_FILE)) 461 req->flags |= io_file_get_flags(req->file); 462 463 if (req->file && (req->flags & REQ_F_ISREG)) { 464 bool should_hash = def->hash_reg_file; 465 466 /* don't serialize this request if the fs doesn't need it */ 467 if (should_hash && (req->file->f_flags & O_DIRECT) && 468 (req->file->f_mode & FMODE_DIO_PARALLEL_WRITE)) 469 should_hash = false; 470 if (should_hash || (ctx->flags & IORING_SETUP_IOPOLL)) 471 io_wq_hash_work(&req->work, file_inode(req->file)); 472 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) { 473 if (def->unbound_nonreg_file) 474 req->work.flags |= IO_WQ_WORK_UNBOUND; 475 } 476 } 477 io_prep_async_link(struct io_kiocb * req)478 static void io_prep_async_link(struct io_kiocb *req) 479 { 480 struct io_kiocb *cur; 481 482 if (req->flags & REQ_F_LINK_TIMEOUT) { 483 struct io_ring_ctx *ctx = req->ctx; 484 485 spin_lock_irq(&ctx->timeout_lock); 486 io_for_each_link(cur, req) 487 io_prep_async_work(cur); 488 spin_unlock_irq(&ctx->timeout_lock); 489 } else { 490 io_for_each_link(cur, req) 491 io_prep_async_work(cur); 492 } 493 } 494 io_queue_iowq(struct io_kiocb * req)495 static void io_queue_iowq(struct io_kiocb *req) 496 { 497 struct io_kiocb *link = io_prep_linked_timeout(req); 498 struct io_uring_task *tctx = req->task->io_uring; 499 500 BUG_ON(!tctx); 501 502 if ((current->flags & PF_KTHREAD) || !tctx->io_wq) { 503 io_req_task_queue_fail(req, -ECANCELED); 504 return; 505 } 506 507 /* init ->work of the whole link before punting */ 508 io_prep_async_link(req); 509 510 /* 511 * Not expected to happen, but if we do have a bug where this _can_ 512 * happen, catch it here and ensure the request is marked as 513 * canceled. That will make io-wq go through the usual work cancel 514 * procedure rather than attempt to run this request (or create a new 515 * worker for it). 516 */ 517 if (WARN_ON_ONCE(!same_thread_group(req->task, current))) 518 req->work.flags |= IO_WQ_WORK_CANCEL; 519 520 trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work)); 521 io_wq_enqueue(tctx->io_wq, &req->work); 522 if (link) 523 io_queue_linked_timeout(link); 524 } 525 io_queue_deferred(struct io_ring_ctx * ctx)526 static __cold void io_queue_deferred(struct io_ring_ctx *ctx) 527 { 528 while (!list_empty(&ctx->defer_list)) { 529 struct io_defer_entry *de = list_first_entry(&ctx->defer_list, 530 struct io_defer_entry, list); 531 532 if (req_need_defer(de->req, de->seq)) 533 break; 534 list_del_init(&de->list); 535 io_req_task_queue(de->req); 536 kfree(de); 537 } 538 } 539 io_eventfd_free(struct rcu_head * rcu)540 static void io_eventfd_free(struct rcu_head *rcu) 541 { 542 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu); 543 544 eventfd_ctx_put(ev_fd->cq_ev_fd); 545 kfree(ev_fd); 546 } 547 io_eventfd_ops(struct rcu_head * rcu)548 static void io_eventfd_ops(struct rcu_head *rcu) 549 { 550 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu); 551 int ops = atomic_xchg(&ev_fd->ops, 0); 552 553 if (ops & BIT(IO_EVENTFD_OP_SIGNAL_BIT)) 554 eventfd_signal_mask(ev_fd->cq_ev_fd, 1, EPOLL_URING_WAKE); 555 556 /* IO_EVENTFD_OP_FREE_BIT may not be set here depending on callback 557 * ordering in a race but if references are 0 we know we have to free 558 * it regardless. 559 */ 560 if (atomic_dec_and_test(&ev_fd->refs)) 561 call_rcu(&ev_fd->rcu, io_eventfd_free); 562 } 563 io_eventfd_signal(struct io_ring_ctx * ctx)564 static void io_eventfd_signal(struct io_ring_ctx *ctx) 565 { 566 struct io_ev_fd *ev_fd = NULL; 567 568 rcu_read_lock(); 569 /* 570 * rcu_dereference ctx->io_ev_fd once and use it for both for checking 571 * and eventfd_signal 572 */ 573 ev_fd = rcu_dereference(ctx->io_ev_fd); 574 575 /* 576 * Check again if ev_fd exists incase an io_eventfd_unregister call 577 * completed between the NULL check of ctx->io_ev_fd at the start of 578 * the function and rcu_read_lock. 579 */ 580 if (unlikely(!ev_fd)) 581 goto out; 582 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED) 583 goto out; 584 if (ev_fd->eventfd_async && !io_wq_current_is_worker()) 585 goto out; 586 587 if (likely(eventfd_signal_allowed())) { 588 eventfd_signal_mask(ev_fd->cq_ev_fd, 1, EPOLL_URING_WAKE); 589 } else { 590 atomic_inc(&ev_fd->refs); 591 if (!atomic_fetch_or(BIT(IO_EVENTFD_OP_SIGNAL_BIT), &ev_fd->ops)) 592 call_rcu_hurry(&ev_fd->rcu, io_eventfd_ops); 593 else 594 atomic_dec(&ev_fd->refs); 595 } 596 597 out: 598 rcu_read_unlock(); 599 } 600 io_eventfd_flush_signal(struct io_ring_ctx * ctx)601 static void io_eventfd_flush_signal(struct io_ring_ctx *ctx) 602 { 603 bool skip; 604 605 spin_lock(&ctx->completion_lock); 606 607 /* 608 * Eventfd should only get triggered when at least one event has been 609 * posted. Some applications rely on the eventfd notification count 610 * only changing IFF a new CQE has been added to the CQ ring. There's 611 * no depedency on 1:1 relationship between how many times this 612 * function is called (and hence the eventfd count) and number of CQEs 613 * posted to the CQ ring. 614 */ 615 skip = ctx->cached_cq_tail == ctx->evfd_last_cq_tail; 616 ctx->evfd_last_cq_tail = ctx->cached_cq_tail; 617 spin_unlock(&ctx->completion_lock); 618 if (skip) 619 return; 620 621 io_eventfd_signal(ctx); 622 } 623 __io_commit_cqring_flush(struct io_ring_ctx * ctx)624 void __io_commit_cqring_flush(struct io_ring_ctx *ctx) 625 { 626 if (ctx->poll_activated) 627 io_poll_wq_wake(ctx); 628 if (ctx->off_timeout_used) 629 io_flush_timeouts(ctx); 630 if (ctx->drain_active) { 631 spin_lock(&ctx->completion_lock); 632 io_queue_deferred(ctx); 633 spin_unlock(&ctx->completion_lock); 634 } 635 if (ctx->has_evfd) 636 io_eventfd_flush_signal(ctx); 637 } 638 __io_cq_lock(struct io_ring_ctx * ctx)639 static inline void __io_cq_lock(struct io_ring_ctx *ctx) 640 { 641 if (!ctx->lockless_cq) 642 spin_lock(&ctx->completion_lock); 643 } 644 io_cq_lock(struct io_ring_ctx * ctx)645 static inline void io_cq_lock(struct io_ring_ctx *ctx) 646 __acquires(ctx->completion_lock) 647 { 648 spin_lock(&ctx->completion_lock); 649 } 650 __io_cq_unlock_post(struct io_ring_ctx * ctx)651 static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx) 652 { 653 io_commit_cqring(ctx); 654 if (!ctx->task_complete) { 655 if (!ctx->lockless_cq) 656 spin_unlock(&ctx->completion_lock); 657 /* IOPOLL rings only need to wake up if it's also SQPOLL */ 658 if (!ctx->syscall_iopoll) 659 io_cqring_wake(ctx); 660 } 661 io_commit_cqring_flush(ctx); 662 } 663 io_cq_unlock_post(struct io_ring_ctx * ctx)664 static void io_cq_unlock_post(struct io_ring_ctx *ctx) 665 __releases(ctx->completion_lock) 666 { 667 io_commit_cqring(ctx); 668 spin_unlock(&ctx->completion_lock); 669 io_cqring_wake(ctx); 670 io_commit_cqring_flush(ctx); 671 } 672 673 /* Returns true if there are no backlogged entries after the flush */ io_cqring_overflow_kill(struct io_ring_ctx * ctx)674 static void io_cqring_overflow_kill(struct io_ring_ctx *ctx) 675 { 676 struct io_overflow_cqe *ocqe; 677 LIST_HEAD(list); 678 679 lockdep_assert_held(&ctx->uring_lock); 680 681 spin_lock(&ctx->completion_lock); 682 list_splice_init(&ctx->cq_overflow_list, &list); 683 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq); 684 spin_unlock(&ctx->completion_lock); 685 686 while (!list_empty(&list)) { 687 ocqe = list_first_entry(&list, struct io_overflow_cqe, list); 688 list_del(&ocqe->list); 689 kfree(ocqe); 690 } 691 } 692 __io_cqring_overflow_flush(struct io_ring_ctx * ctx)693 static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx) 694 { 695 size_t cqe_size = sizeof(struct io_uring_cqe); 696 697 lockdep_assert_held(&ctx->uring_lock); 698 699 if (__io_cqring_events(ctx) == ctx->cq_entries) 700 return; 701 702 if (ctx->flags & IORING_SETUP_CQE32) 703 cqe_size <<= 1; 704 705 io_cq_lock(ctx); 706 while (!list_empty(&ctx->cq_overflow_list)) { 707 struct io_uring_cqe *cqe; 708 struct io_overflow_cqe *ocqe; 709 710 if (!io_get_cqe_overflow(ctx, &cqe, true)) 711 break; 712 ocqe = list_first_entry(&ctx->cq_overflow_list, 713 struct io_overflow_cqe, list); 714 memcpy(cqe, &ocqe->cqe, cqe_size); 715 list_del(&ocqe->list); 716 kfree(ocqe); 717 718 /* 719 * For silly syzbot cases that deliberately overflow by huge 720 * amounts, check if we need to resched and drop and 721 * reacquire the locks if so. Nothing real would ever hit this. 722 * Ideally we'd have a non-posting unlock for this, but hard 723 * to care for a non-real case. 724 */ 725 if (need_resched()) { 726 io_cq_unlock_post(ctx); 727 mutex_unlock(&ctx->uring_lock); 728 cond_resched(); 729 mutex_lock(&ctx->uring_lock); 730 io_cq_lock(ctx); 731 } 732 } 733 734 if (list_empty(&ctx->cq_overflow_list)) { 735 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq); 736 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags); 737 } 738 io_cq_unlock_post(ctx); 739 } 740 io_cqring_do_overflow_flush(struct io_ring_ctx * ctx)741 static void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx) 742 { 743 mutex_lock(&ctx->uring_lock); 744 __io_cqring_overflow_flush(ctx); 745 mutex_unlock(&ctx->uring_lock); 746 } 747 io_cqring_overflow_flush(struct io_ring_ctx * ctx)748 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx) 749 { 750 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) 751 io_cqring_do_overflow_flush(ctx); 752 } 753 754 /* can be called by any task */ io_put_task_remote(struct task_struct * task)755 static void io_put_task_remote(struct task_struct *task) 756 { 757 struct io_uring_task *tctx = task->io_uring; 758 759 percpu_counter_sub(&tctx->inflight, 1); 760 if (unlikely(atomic_read(&tctx->in_cancel))) 761 wake_up(&tctx->wait); 762 put_task_struct(task); 763 } 764 765 /* used by a task to put its own references */ io_put_task_local(struct task_struct * task)766 static void io_put_task_local(struct task_struct *task) 767 { 768 task->io_uring->cached_refs++; 769 } 770 771 /* must to be called somewhat shortly after putting a request */ io_put_task(struct task_struct * task)772 static inline void io_put_task(struct task_struct *task) 773 { 774 if (likely(task == current)) 775 io_put_task_local(task); 776 else 777 io_put_task_remote(task); 778 } 779 io_task_refs_refill(struct io_uring_task * tctx)780 void io_task_refs_refill(struct io_uring_task *tctx) 781 { 782 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR; 783 784 percpu_counter_add(&tctx->inflight, refill); 785 refcount_add(refill, ¤t->usage); 786 tctx->cached_refs += refill; 787 } 788 io_uring_drop_tctx_refs(struct task_struct * task)789 static __cold void io_uring_drop_tctx_refs(struct task_struct *task) 790 { 791 struct io_uring_task *tctx = task->io_uring; 792 unsigned int refs = tctx->cached_refs; 793 794 if (refs) { 795 tctx->cached_refs = 0; 796 percpu_counter_sub(&tctx->inflight, refs); 797 put_task_struct_many(task, refs); 798 } 799 } 800 io_cqring_event_overflow(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags,u64 extra1,u64 extra2)801 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data, 802 s32 res, u32 cflags, u64 extra1, u64 extra2) 803 { 804 struct io_overflow_cqe *ocqe; 805 size_t ocq_size = sizeof(struct io_overflow_cqe); 806 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32); 807 808 lockdep_assert_held(&ctx->completion_lock); 809 810 if (is_cqe32) 811 ocq_size += sizeof(struct io_uring_cqe); 812 813 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT); 814 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe); 815 if (!ocqe) { 816 /* 817 * If we're in ring overflow flush mode, or in task cancel mode, 818 * or cannot allocate an overflow entry, then we need to drop it 819 * on the floor. 820 */ 821 io_account_cq_overflow(ctx); 822 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq); 823 return false; 824 } 825 if (list_empty(&ctx->cq_overflow_list)) { 826 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq); 827 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags); 828 829 } 830 ocqe->cqe.user_data = user_data; 831 ocqe->cqe.res = res; 832 ocqe->cqe.flags = cflags; 833 if (is_cqe32) { 834 ocqe->cqe.big_cqe[0] = extra1; 835 ocqe->cqe.big_cqe[1] = extra2; 836 } 837 list_add_tail(&ocqe->list, &ctx->cq_overflow_list); 838 return true; 839 } 840 io_req_cqe_overflow(struct io_kiocb * req)841 void io_req_cqe_overflow(struct io_kiocb *req) 842 { 843 io_cqring_event_overflow(req->ctx, req->cqe.user_data, 844 req->cqe.res, req->cqe.flags, 845 req->big_cqe.extra1, req->big_cqe.extra2); 846 memset(&req->big_cqe, 0, sizeof(req->big_cqe)); 847 } 848 849 /* 850 * writes to the cq entry need to come after reading head; the 851 * control dependency is enough as we're using WRITE_ONCE to 852 * fill the cq entry 853 */ io_cqe_cache_refill(struct io_ring_ctx * ctx,bool overflow)854 bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow) 855 { 856 struct io_rings *rings = ctx->rings; 857 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1); 858 unsigned int free, queued, len; 859 860 /* 861 * Posting into the CQ when there are pending overflowed CQEs may break 862 * ordering guarantees, which will affect links, F_MORE users and more. 863 * Force overflow the completion. 864 */ 865 if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))) 866 return false; 867 868 /* userspace may cheat modifying the tail, be safe and do min */ 869 queued = min(__io_cqring_events(ctx), ctx->cq_entries); 870 free = ctx->cq_entries - queued; 871 /* we need a contiguous range, limit based on the current array offset */ 872 len = min(free, ctx->cq_entries - off); 873 if (!len) 874 return false; 875 876 if (ctx->flags & IORING_SETUP_CQE32) { 877 off <<= 1; 878 len <<= 1; 879 } 880 881 ctx->cqe_cached = &rings->cqes[off]; 882 ctx->cqe_sentinel = ctx->cqe_cached + len; 883 return true; 884 } 885 io_fill_cqe_aux(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags)886 static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res, 887 u32 cflags) 888 { 889 struct io_uring_cqe *cqe; 890 891 ctx->cq_extra++; 892 893 /* 894 * If we can't get a cq entry, userspace overflowed the 895 * submission (by quite a lot). Increment the overflow count in 896 * the ring. 897 */ 898 if (likely(io_get_cqe(ctx, &cqe))) { 899 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0); 900 901 WRITE_ONCE(cqe->user_data, user_data); 902 WRITE_ONCE(cqe->res, res); 903 WRITE_ONCE(cqe->flags, cflags); 904 905 if (ctx->flags & IORING_SETUP_CQE32) { 906 WRITE_ONCE(cqe->big_cqe[0], 0); 907 WRITE_ONCE(cqe->big_cqe[1], 0); 908 } 909 return true; 910 } 911 return false; 912 } 913 __io_flush_post_cqes(struct io_ring_ctx * ctx)914 static void __io_flush_post_cqes(struct io_ring_ctx *ctx) 915 __must_hold(&ctx->uring_lock) 916 { 917 struct io_submit_state *state = &ctx->submit_state; 918 unsigned int i; 919 920 lockdep_assert_held(&ctx->uring_lock); 921 for (i = 0; i < state->cqes_count; i++) { 922 struct io_uring_cqe *cqe = &ctx->completion_cqes[i]; 923 924 if (!io_fill_cqe_aux(ctx, cqe->user_data, cqe->res, cqe->flags)) { 925 if (ctx->lockless_cq) { 926 spin_lock(&ctx->completion_lock); 927 io_cqring_event_overflow(ctx, cqe->user_data, 928 cqe->res, cqe->flags, 0, 0); 929 spin_unlock(&ctx->completion_lock); 930 } else { 931 io_cqring_event_overflow(ctx, cqe->user_data, 932 cqe->res, cqe->flags, 0, 0); 933 } 934 } 935 } 936 state->cqes_count = 0; 937 } 938 __io_post_aux_cqe(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags,bool allow_overflow)939 static bool __io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags, 940 bool allow_overflow) 941 { 942 bool filled; 943 944 io_cq_lock(ctx); 945 filled = io_fill_cqe_aux(ctx, user_data, res, cflags); 946 if (!filled && allow_overflow) 947 filled = io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0); 948 949 io_cq_unlock_post(ctx); 950 return filled; 951 } 952 io_post_aux_cqe(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags)953 bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags) 954 { 955 return __io_post_aux_cqe(ctx, user_data, res, cflags, true); 956 } 957 958 /* 959 * A helper for multishot requests posting additional CQEs. 960 * Should only be used from a task_work including IO_URING_F_MULTISHOT. 961 */ io_fill_cqe_req_aux(struct io_kiocb * req,bool defer,s32 res,u32 cflags)962 bool io_fill_cqe_req_aux(struct io_kiocb *req, bool defer, s32 res, u32 cflags) 963 { 964 struct io_ring_ctx *ctx = req->ctx; 965 u64 user_data = req->cqe.user_data; 966 struct io_uring_cqe *cqe; 967 968 if (!defer) 969 return __io_post_aux_cqe(ctx, user_data, res, cflags, false); 970 971 lockdep_assert_held(&ctx->uring_lock); 972 973 if (ctx->submit_state.cqes_count == ARRAY_SIZE(ctx->completion_cqes)) { 974 __io_cq_lock(ctx); 975 __io_flush_post_cqes(ctx); 976 /* no need to flush - flush is deferred */ 977 __io_cq_unlock_post(ctx); 978 } 979 980 /* For defered completions this is not as strict as it is otherwise, 981 * however it's main job is to prevent unbounded posted completions, 982 * and in that it works just as well. 983 */ 984 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) 985 return false; 986 987 cqe = &ctx->completion_cqes[ctx->submit_state.cqes_count++]; 988 cqe->user_data = user_data; 989 cqe->res = res; 990 cqe->flags = cflags; 991 return true; 992 } 993 __io_req_complete_post(struct io_kiocb * req,unsigned issue_flags)994 static void __io_req_complete_post(struct io_kiocb *req, unsigned issue_flags) 995 { 996 struct io_ring_ctx *ctx = req->ctx; 997 struct io_rsrc_node *rsrc_node = NULL; 998 999 io_cq_lock(ctx); 1000 if (!(req->flags & REQ_F_CQE_SKIP)) { 1001 if (!io_fill_cqe_req(ctx, req)) 1002 io_req_cqe_overflow(req); 1003 } 1004 1005 /* 1006 * If we're the last reference to this request, add to our locked 1007 * free_list cache. 1008 */ 1009 if (req_ref_put_and_test(req)) { 1010 if (req->flags & IO_REQ_LINK_FLAGS) { 1011 if (req->flags & IO_DISARM_MASK) 1012 io_disarm_next(req); 1013 if (req->link) { 1014 io_req_task_queue(req->link); 1015 req->link = NULL; 1016 } 1017 } 1018 io_put_kbuf_comp(req); 1019 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS)) 1020 io_clean_op(req); 1021 io_put_file(req); 1022 1023 rsrc_node = req->rsrc_node; 1024 /* 1025 * Selected buffer deallocation in io_clean_op() assumes that 1026 * we don't hold ->completion_lock. Clean them here to avoid 1027 * deadlocks. 1028 */ 1029 io_put_task_remote(req->task); 1030 wq_list_add_head(&req->comp_list, &ctx->locked_free_list); 1031 ctx->locked_free_nr++; 1032 } 1033 io_cq_unlock_post(ctx); 1034 1035 if (rsrc_node) { 1036 io_ring_submit_lock(ctx, issue_flags); 1037 io_put_rsrc_node(ctx, rsrc_node); 1038 io_ring_submit_unlock(ctx, issue_flags); 1039 } 1040 } 1041 io_req_complete_post(struct io_kiocb * req,unsigned issue_flags)1042 void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags) 1043 { 1044 if (req->ctx->task_complete && req->ctx->submitter_task != current) { 1045 req->io_task_work.func = io_req_task_complete; 1046 io_req_task_work_add(req); 1047 } else if (!(issue_flags & IO_URING_F_UNLOCKED) || 1048 !(req->ctx->flags & IORING_SETUP_IOPOLL)) { 1049 __io_req_complete_post(req, issue_flags); 1050 } else { 1051 struct io_ring_ctx *ctx = req->ctx; 1052 1053 mutex_lock(&ctx->uring_lock); 1054 __io_req_complete_post(req, issue_flags & ~IO_URING_F_UNLOCKED); 1055 mutex_unlock(&ctx->uring_lock); 1056 } 1057 } 1058 io_req_defer_failed(struct io_kiocb * req,s32 res)1059 void io_req_defer_failed(struct io_kiocb *req, s32 res) 1060 __must_hold(&ctx->uring_lock) 1061 { 1062 const struct io_cold_def *def = &io_cold_defs[req->opcode]; 1063 1064 lockdep_assert_held(&req->ctx->uring_lock); 1065 1066 req_set_fail(req); 1067 io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED)); 1068 if (def->fail) 1069 def->fail(req); 1070 io_req_complete_defer(req); 1071 } 1072 1073 /* 1074 * Don't initialise the fields below on every allocation, but do that in 1075 * advance and keep them valid across allocations. 1076 */ io_preinit_req(struct io_kiocb * req,struct io_ring_ctx * ctx)1077 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx) 1078 { 1079 req->ctx = ctx; 1080 req->link = NULL; 1081 req->async_data = NULL; 1082 /* not necessary, but safer to zero */ 1083 memset(&req->cqe, 0, sizeof(req->cqe)); 1084 memset(&req->big_cqe, 0, sizeof(req->big_cqe)); 1085 } 1086 io_flush_cached_locked_reqs(struct io_ring_ctx * ctx,struct io_submit_state * state)1087 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx, 1088 struct io_submit_state *state) 1089 { 1090 spin_lock(&ctx->completion_lock); 1091 wq_list_splice(&ctx->locked_free_list, &state->free_list); 1092 ctx->locked_free_nr = 0; 1093 spin_unlock(&ctx->completion_lock); 1094 } 1095 1096 /* 1097 * A request might get retired back into the request caches even before opcode 1098 * handlers and io_issue_sqe() are done with it, e.g. inline completion path. 1099 * Because of that, io_alloc_req() should be called only under ->uring_lock 1100 * and with extra caution to not get a request that is still worked on. 1101 */ __io_alloc_req_refill(struct io_ring_ctx * ctx)1102 __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx) 1103 __must_hold(&ctx->uring_lock) 1104 { 1105 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN; 1106 void *reqs[IO_REQ_ALLOC_BATCH]; 1107 int ret, i; 1108 1109 /* 1110 * If we have more than a batch's worth of requests in our IRQ side 1111 * locked cache, grab the lock and move them over to our submission 1112 * side cache. 1113 */ 1114 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) { 1115 io_flush_cached_locked_reqs(ctx, &ctx->submit_state); 1116 if (!io_req_cache_empty(ctx)) 1117 return true; 1118 } 1119 1120 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs); 1121 1122 /* 1123 * Bulk alloc is all-or-nothing. If we fail to get a batch, 1124 * retry single alloc to be on the safe side. 1125 */ 1126 if (unlikely(ret <= 0)) { 1127 reqs[0] = kmem_cache_alloc(req_cachep, gfp); 1128 if (!reqs[0]) 1129 return false; 1130 ret = 1; 1131 } 1132 1133 percpu_ref_get_many(&ctx->refs, ret); 1134 for (i = 0; i < ret; i++) { 1135 struct io_kiocb *req = reqs[i]; 1136 1137 io_preinit_req(req, ctx); 1138 io_req_add_to_cache(req, ctx); 1139 } 1140 return true; 1141 } 1142 io_free_req(struct io_kiocb * req)1143 __cold void io_free_req(struct io_kiocb *req) 1144 { 1145 /* refs were already put, restore them for io_req_task_complete() */ 1146 req->flags &= ~REQ_F_REFCOUNT; 1147 /* we only want to free it, don't post CQEs */ 1148 req->flags |= REQ_F_CQE_SKIP; 1149 req->io_task_work.func = io_req_task_complete; 1150 io_req_task_work_add(req); 1151 } 1152 __io_req_find_next_prep(struct io_kiocb * req)1153 static void __io_req_find_next_prep(struct io_kiocb *req) 1154 { 1155 struct io_ring_ctx *ctx = req->ctx; 1156 1157 spin_lock(&ctx->completion_lock); 1158 io_disarm_next(req); 1159 spin_unlock(&ctx->completion_lock); 1160 } 1161 io_req_find_next(struct io_kiocb * req)1162 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req) 1163 { 1164 struct io_kiocb *nxt; 1165 1166 /* 1167 * If LINK is set, we have dependent requests in this chain. If we 1168 * didn't fail this request, queue the first one up, moving any other 1169 * dependencies to the next request. In case of failure, fail the rest 1170 * of the chain. 1171 */ 1172 if (unlikely(req->flags & IO_DISARM_MASK)) 1173 __io_req_find_next_prep(req); 1174 nxt = req->link; 1175 req->link = NULL; 1176 return nxt; 1177 } 1178 ctx_flush_and_put(struct io_ring_ctx * ctx,struct io_tw_state * ts)1179 static void ctx_flush_and_put(struct io_ring_ctx *ctx, struct io_tw_state *ts) 1180 { 1181 if (!ctx) 1182 return; 1183 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG) 1184 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags); 1185 if (ts->locked) { 1186 io_submit_flush_completions(ctx); 1187 mutex_unlock(&ctx->uring_lock); 1188 ts->locked = false; 1189 } 1190 percpu_ref_put(&ctx->refs); 1191 } 1192 handle_tw_list(struct llist_node * node,struct io_ring_ctx ** ctx,struct io_tw_state * ts)1193 static unsigned int handle_tw_list(struct llist_node *node, 1194 struct io_ring_ctx **ctx, 1195 struct io_tw_state *ts) 1196 { 1197 unsigned int count = 0; 1198 1199 do { 1200 struct llist_node *next = node->next; 1201 struct io_kiocb *req = container_of(node, struct io_kiocb, 1202 io_task_work.node); 1203 1204 prefetch(container_of(next, struct io_kiocb, io_task_work.node)); 1205 1206 if (req->ctx != *ctx) { 1207 ctx_flush_and_put(*ctx, ts); 1208 *ctx = req->ctx; 1209 /* if not contended, grab and improve batching */ 1210 ts->locked = mutex_trylock(&(*ctx)->uring_lock); 1211 percpu_ref_get(&(*ctx)->refs); 1212 } 1213 INDIRECT_CALL_2(req->io_task_work.func, 1214 io_poll_task_func, io_req_rw_complete, 1215 req, ts); 1216 node = next; 1217 count++; 1218 if (unlikely(need_resched())) { 1219 ctx_flush_and_put(*ctx, ts); 1220 *ctx = NULL; 1221 cond_resched(); 1222 } 1223 } while (node); 1224 1225 return count; 1226 } 1227 1228 /** 1229 * io_llist_xchg - swap all entries in a lock-less list 1230 * @head: the head of lock-less list to delete all entries 1231 * @new: new entry as the head of the list 1232 * 1233 * If list is empty, return NULL, otherwise, return the pointer to the first entry. 1234 * The order of entries returned is from the newest to the oldest added one. 1235 */ io_llist_xchg(struct llist_head * head,struct llist_node * new)1236 static inline struct llist_node *io_llist_xchg(struct llist_head *head, 1237 struct llist_node *new) 1238 { 1239 return xchg(&head->first, new); 1240 } 1241 io_fallback_tw(struct io_uring_task * tctx,bool sync)1242 static __cold void io_fallback_tw(struct io_uring_task *tctx, bool sync) 1243 { 1244 struct llist_node *node = llist_del_all(&tctx->task_list); 1245 struct io_ring_ctx *last_ctx = NULL; 1246 struct io_kiocb *req; 1247 1248 while (node) { 1249 req = container_of(node, struct io_kiocb, io_task_work.node); 1250 node = node->next; 1251 if (sync && last_ctx != req->ctx) { 1252 if (last_ctx) { 1253 flush_delayed_work(&last_ctx->fallback_work); 1254 percpu_ref_put(&last_ctx->refs); 1255 } 1256 last_ctx = req->ctx; 1257 percpu_ref_get(&last_ctx->refs); 1258 } 1259 if (llist_add(&req->io_task_work.node, 1260 &req->ctx->fallback_llist)) 1261 schedule_delayed_work(&req->ctx->fallback_work, 1); 1262 } 1263 1264 if (last_ctx) { 1265 flush_delayed_work(&last_ctx->fallback_work); 1266 percpu_ref_put(&last_ctx->refs); 1267 } 1268 } 1269 tctx_task_work(struct callback_head * cb)1270 void tctx_task_work(struct callback_head *cb) 1271 { 1272 struct io_tw_state ts = {}; 1273 struct io_ring_ctx *ctx = NULL; 1274 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, 1275 task_work); 1276 struct llist_node *node; 1277 unsigned int count = 0; 1278 1279 if (unlikely(current->flags & PF_EXITING)) { 1280 io_fallback_tw(tctx, true); 1281 return; 1282 } 1283 1284 node = llist_del_all(&tctx->task_list); 1285 if (node) 1286 count = handle_tw_list(node, &ctx, &ts); 1287 1288 ctx_flush_and_put(ctx, &ts); 1289 1290 /* relaxed read is enough as only the task itself sets ->in_cancel */ 1291 if (unlikely(atomic_read(&tctx->in_cancel))) 1292 io_uring_drop_tctx_refs(current); 1293 1294 trace_io_uring_task_work_run(tctx, count, 1); 1295 } 1296 io_req_local_work_add(struct io_kiocb * req,unsigned flags)1297 static inline void io_req_local_work_add(struct io_kiocb *req, unsigned flags) 1298 { 1299 struct io_ring_ctx *ctx = req->ctx; 1300 unsigned nr_wait, nr_tw, nr_tw_prev; 1301 struct llist_node *first; 1302 1303 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) 1304 flags &= ~IOU_F_TWQ_LAZY_WAKE; 1305 1306 first = READ_ONCE(ctx->work_llist.first); 1307 do { 1308 nr_tw_prev = 0; 1309 if (first) { 1310 struct io_kiocb *first_req = container_of(first, 1311 struct io_kiocb, 1312 io_task_work.node); 1313 /* 1314 * Might be executed at any moment, rely on 1315 * SLAB_TYPESAFE_BY_RCU to keep it alive. 1316 */ 1317 nr_tw_prev = READ_ONCE(first_req->nr_tw); 1318 } 1319 nr_tw = nr_tw_prev + 1; 1320 /* Large enough to fail the nr_wait comparison below */ 1321 if (!(flags & IOU_F_TWQ_LAZY_WAKE)) 1322 nr_tw = INT_MAX; 1323 1324 req->nr_tw = nr_tw; 1325 req->io_task_work.node.next = first; 1326 } while (!try_cmpxchg(&ctx->work_llist.first, &first, 1327 &req->io_task_work.node)); 1328 1329 if (!first) { 1330 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG) 1331 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags); 1332 if (ctx->has_evfd) 1333 io_eventfd_signal(ctx); 1334 } 1335 1336 nr_wait = atomic_read(&ctx->cq_wait_nr); 1337 /* no one is waiting */ 1338 if (!nr_wait) 1339 return; 1340 /* either not enough or the previous add has already woken it up */ 1341 if (nr_wait > nr_tw || nr_tw_prev >= nr_wait) 1342 return; 1343 /* pairs with set_current_state() in io_cqring_wait() */ 1344 smp_mb__after_atomic(); 1345 wake_up_state(ctx->submitter_task, TASK_INTERRUPTIBLE); 1346 } 1347 io_req_normal_work_add(struct io_kiocb * req)1348 static void io_req_normal_work_add(struct io_kiocb *req) 1349 { 1350 struct io_uring_task *tctx = req->task->io_uring; 1351 struct io_ring_ctx *ctx = req->ctx; 1352 1353 /* task_work already pending, we're done */ 1354 if (!llist_add(&req->io_task_work.node, &tctx->task_list)) 1355 return; 1356 1357 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG) 1358 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags); 1359 1360 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method))) 1361 return; 1362 1363 io_fallback_tw(tctx, false); 1364 } 1365 __io_req_task_work_add(struct io_kiocb * req,unsigned flags)1366 void __io_req_task_work_add(struct io_kiocb *req, unsigned flags) 1367 { 1368 if (req->ctx->flags & IORING_SETUP_DEFER_TASKRUN) { 1369 rcu_read_lock(); 1370 io_req_local_work_add(req, flags); 1371 rcu_read_unlock(); 1372 } else { 1373 io_req_normal_work_add(req); 1374 } 1375 } 1376 io_move_task_work_from_local(struct io_ring_ctx * ctx)1377 static void __cold io_move_task_work_from_local(struct io_ring_ctx *ctx) 1378 { 1379 struct llist_node *node; 1380 1381 node = llist_del_all(&ctx->work_llist); 1382 while (node) { 1383 struct io_kiocb *req = container_of(node, struct io_kiocb, 1384 io_task_work.node); 1385 1386 node = node->next; 1387 io_req_normal_work_add(req); 1388 } 1389 } 1390 io_run_local_work_continue(struct io_ring_ctx * ctx,int events,int min_events)1391 static bool io_run_local_work_continue(struct io_ring_ctx *ctx, int events, 1392 int min_events) 1393 { 1394 if (llist_empty(&ctx->work_llist)) 1395 return false; 1396 if (events < min_events) 1397 return true; 1398 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG) 1399 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags); 1400 return false; 1401 } 1402 __io_run_local_work(struct io_ring_ctx * ctx,struct io_tw_state * ts,int min_events)1403 static int __io_run_local_work(struct io_ring_ctx *ctx, struct io_tw_state *ts, 1404 int min_events) 1405 { 1406 struct llist_node *node; 1407 unsigned int loops = 0; 1408 int ret = 0; 1409 1410 if (WARN_ON_ONCE(ctx->submitter_task != current)) 1411 return -EEXIST; 1412 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG) 1413 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags); 1414 again: 1415 /* 1416 * llists are in reverse order, flip it back the right way before 1417 * running the pending items. 1418 */ 1419 node = llist_reverse_order(io_llist_xchg(&ctx->work_llist, NULL)); 1420 while (node) { 1421 struct llist_node *next = node->next; 1422 struct io_kiocb *req = container_of(node, struct io_kiocb, 1423 io_task_work.node); 1424 prefetch(container_of(next, struct io_kiocb, io_task_work.node)); 1425 INDIRECT_CALL_2(req->io_task_work.func, 1426 io_poll_task_func, io_req_rw_complete, 1427 req, ts); 1428 ret++; 1429 node = next; 1430 } 1431 loops++; 1432 1433 if (io_run_local_work_continue(ctx, ret, min_events)) 1434 goto again; 1435 if (ts->locked) { 1436 io_submit_flush_completions(ctx); 1437 if (io_run_local_work_continue(ctx, ret, min_events)) 1438 goto again; 1439 } 1440 1441 trace_io_uring_local_work_run(ctx, ret, loops); 1442 return ret; 1443 } 1444 io_run_local_work_locked(struct io_ring_ctx * ctx,int min_events)1445 static inline int io_run_local_work_locked(struct io_ring_ctx *ctx, 1446 int min_events) 1447 { 1448 struct io_tw_state ts = { .locked = true, }; 1449 int ret; 1450 1451 if (llist_empty(&ctx->work_llist)) 1452 return 0; 1453 1454 ret = __io_run_local_work(ctx, &ts, min_events); 1455 /* shouldn't happen! */ 1456 if (WARN_ON_ONCE(!ts.locked)) 1457 mutex_lock(&ctx->uring_lock); 1458 return ret; 1459 } 1460 io_run_local_work(struct io_ring_ctx * ctx,int min_events)1461 static int io_run_local_work(struct io_ring_ctx *ctx, int min_events) 1462 { 1463 struct io_tw_state ts = {}; 1464 int ret; 1465 1466 ts.locked = mutex_trylock(&ctx->uring_lock); 1467 ret = __io_run_local_work(ctx, &ts, min_events); 1468 if (ts.locked) 1469 mutex_unlock(&ctx->uring_lock); 1470 1471 return ret; 1472 } 1473 io_req_task_cancel(struct io_kiocb * req,struct io_tw_state * ts)1474 static void io_req_task_cancel(struct io_kiocb *req, struct io_tw_state *ts) 1475 { 1476 io_tw_lock(req->ctx, ts); 1477 io_req_defer_failed(req, req->cqe.res); 1478 } 1479 io_req_task_submit(struct io_kiocb * req,struct io_tw_state * ts)1480 void io_req_task_submit(struct io_kiocb *req, struct io_tw_state *ts) 1481 { 1482 io_tw_lock(req->ctx, ts); 1483 /* req->task == current here, checking PF_EXITING is safe */ 1484 if (unlikely(req->task->flags & PF_EXITING)) 1485 io_req_defer_failed(req, -EFAULT); 1486 else if (req->flags & REQ_F_FORCE_ASYNC) 1487 io_queue_iowq(req); 1488 else 1489 io_queue_sqe(req); 1490 } 1491 io_req_task_queue_fail(struct io_kiocb * req,int ret)1492 void io_req_task_queue_fail(struct io_kiocb *req, int ret) 1493 { 1494 io_req_set_res(req, ret, 0); 1495 req->io_task_work.func = io_req_task_cancel; 1496 io_req_task_work_add(req); 1497 } 1498 io_req_task_queue(struct io_kiocb * req)1499 void io_req_task_queue(struct io_kiocb *req) 1500 { 1501 req->io_task_work.func = io_req_task_submit; 1502 io_req_task_work_add(req); 1503 } 1504 io_queue_next(struct io_kiocb * req)1505 void io_queue_next(struct io_kiocb *req) 1506 { 1507 struct io_kiocb *nxt = io_req_find_next(req); 1508 1509 if (nxt) 1510 io_req_task_queue(nxt); 1511 } 1512 io_free_batch_list(struct io_ring_ctx * ctx,struct io_wq_work_node * node)1513 static void io_free_batch_list(struct io_ring_ctx *ctx, 1514 struct io_wq_work_node *node) 1515 __must_hold(&ctx->uring_lock) 1516 { 1517 do { 1518 struct io_kiocb *req = container_of(node, struct io_kiocb, 1519 comp_list); 1520 1521 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) { 1522 if (req->flags & REQ_F_REFCOUNT) { 1523 node = req->comp_list.next; 1524 if (!req_ref_put_and_test(req)) 1525 continue; 1526 } 1527 if ((req->flags & REQ_F_POLLED) && req->apoll) { 1528 struct async_poll *apoll = req->apoll; 1529 1530 if (apoll->double_poll) 1531 kfree(apoll->double_poll); 1532 if (!io_alloc_cache_put(&ctx->apoll_cache, &apoll->cache)) 1533 kfree(apoll); 1534 req->flags &= ~REQ_F_POLLED; 1535 } 1536 if (req->flags & IO_REQ_LINK_FLAGS) 1537 io_queue_next(req); 1538 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS)) 1539 io_clean_op(req); 1540 } 1541 io_put_file(req); 1542 1543 io_req_put_rsrc_locked(req, ctx); 1544 1545 io_put_task(req->task); 1546 node = req->comp_list.next; 1547 io_req_add_to_cache(req, ctx); 1548 } while (node); 1549 } 1550 __io_submit_flush_completions(struct io_ring_ctx * ctx)1551 void __io_submit_flush_completions(struct io_ring_ctx *ctx) 1552 __must_hold(&ctx->uring_lock) 1553 { 1554 struct io_submit_state *state = &ctx->submit_state; 1555 struct io_wq_work_node *node; 1556 1557 __io_cq_lock(ctx); 1558 /* must come first to preserve CQE ordering in failure cases */ 1559 if (state->cqes_count) 1560 __io_flush_post_cqes(ctx); 1561 __wq_list_for_each(node, &state->compl_reqs) { 1562 struct io_kiocb *req = container_of(node, struct io_kiocb, 1563 comp_list); 1564 1565 if (!(req->flags & REQ_F_CQE_SKIP) && 1566 unlikely(!io_fill_cqe_req(ctx, req))) { 1567 if (ctx->lockless_cq) { 1568 spin_lock(&ctx->completion_lock); 1569 io_req_cqe_overflow(req); 1570 spin_unlock(&ctx->completion_lock); 1571 } else { 1572 io_req_cqe_overflow(req); 1573 } 1574 } 1575 } 1576 __io_cq_unlock_post(ctx); 1577 1578 if (!wq_list_empty(&ctx->submit_state.compl_reqs)) { 1579 io_free_batch_list(ctx, state->compl_reqs.first); 1580 INIT_WQ_LIST(&state->compl_reqs); 1581 } 1582 } 1583 io_cqring_events(struct io_ring_ctx * ctx)1584 static unsigned io_cqring_events(struct io_ring_ctx *ctx) 1585 { 1586 /* See comment at the top of this file */ 1587 smp_rmb(); 1588 return __io_cqring_events(ctx); 1589 } 1590 1591 /* 1592 * We can't just wait for polled events to come to us, we have to actively 1593 * find and complete them. 1594 */ io_iopoll_try_reap_events(struct io_ring_ctx * ctx)1595 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx) 1596 { 1597 if (!(ctx->flags & IORING_SETUP_IOPOLL)) 1598 return; 1599 1600 mutex_lock(&ctx->uring_lock); 1601 while (!wq_list_empty(&ctx->iopoll_list)) { 1602 /* let it sleep and repeat later if can't complete a request */ 1603 if (io_do_iopoll(ctx, true) == 0) 1604 break; 1605 /* 1606 * Ensure we allow local-to-the-cpu processing to take place, 1607 * in this case we need to ensure that we reap all events. 1608 * Also let task_work, etc. to progress by releasing the mutex 1609 */ 1610 if (need_resched()) { 1611 mutex_unlock(&ctx->uring_lock); 1612 cond_resched(); 1613 mutex_lock(&ctx->uring_lock); 1614 } 1615 } 1616 mutex_unlock(&ctx->uring_lock); 1617 } 1618 io_iopoll_check(struct io_ring_ctx * ctx,long min)1619 static int io_iopoll_check(struct io_ring_ctx *ctx, long min) 1620 { 1621 unsigned int nr_events = 0; 1622 unsigned long check_cq; 1623 1624 lockdep_assert_held(&ctx->uring_lock); 1625 1626 if (!io_allowed_run_tw(ctx)) 1627 return -EEXIST; 1628 1629 check_cq = READ_ONCE(ctx->check_cq); 1630 if (unlikely(check_cq)) { 1631 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)) 1632 __io_cqring_overflow_flush(ctx); 1633 /* 1634 * Similarly do not spin if we have not informed the user of any 1635 * dropped CQE. 1636 */ 1637 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)) 1638 return -EBADR; 1639 } 1640 /* 1641 * Don't enter poll loop if we already have events pending. 1642 * If we do, we can potentially be spinning for commands that 1643 * already triggered a CQE (eg in error). 1644 */ 1645 if (io_cqring_events(ctx)) 1646 return 0; 1647 1648 do { 1649 int ret = 0; 1650 1651 /* 1652 * If a submit got punted to a workqueue, we can have the 1653 * application entering polling for a command before it gets 1654 * issued. That app will hold the uring_lock for the duration 1655 * of the poll right here, so we need to take a breather every 1656 * now and then to ensure that the issue has a chance to add 1657 * the poll to the issued list. Otherwise we can spin here 1658 * forever, while the workqueue is stuck trying to acquire the 1659 * very same mutex. 1660 */ 1661 if (wq_list_empty(&ctx->iopoll_list) || 1662 io_task_work_pending(ctx)) { 1663 u32 tail = ctx->cached_cq_tail; 1664 1665 (void) io_run_local_work_locked(ctx, min); 1666 1667 if (task_work_pending(current) || 1668 wq_list_empty(&ctx->iopoll_list)) { 1669 mutex_unlock(&ctx->uring_lock); 1670 io_run_task_work(); 1671 mutex_lock(&ctx->uring_lock); 1672 } 1673 /* some requests don't go through iopoll_list */ 1674 if (tail != ctx->cached_cq_tail || 1675 wq_list_empty(&ctx->iopoll_list)) 1676 break; 1677 } 1678 ret = io_do_iopoll(ctx, !min); 1679 if (unlikely(ret < 0)) 1680 return ret; 1681 1682 if (task_sigpending(current)) 1683 return -EINTR; 1684 if (need_resched()) 1685 break; 1686 1687 nr_events += ret; 1688 } while (nr_events < min); 1689 1690 return 0; 1691 } 1692 io_req_task_complete(struct io_kiocb * req,struct io_tw_state * ts)1693 void io_req_task_complete(struct io_kiocb *req, struct io_tw_state *ts) 1694 { 1695 if (ts->locked) 1696 io_req_complete_defer(req); 1697 else 1698 io_req_complete_post(req, IO_URING_F_UNLOCKED); 1699 } 1700 1701 /* 1702 * After the iocb has been issued, it's safe to be found on the poll list. 1703 * Adding the kiocb to the list AFTER submission ensures that we don't 1704 * find it from a io_do_iopoll() thread before the issuer is done 1705 * accessing the kiocb cookie. 1706 */ io_iopoll_req_issued(struct io_kiocb * req,unsigned int issue_flags)1707 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags) 1708 { 1709 struct io_ring_ctx *ctx = req->ctx; 1710 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED; 1711 1712 /* workqueue context doesn't hold uring_lock, grab it now */ 1713 if (unlikely(needs_lock)) 1714 mutex_lock(&ctx->uring_lock); 1715 1716 /* 1717 * Track whether we have multiple files in our lists. This will impact 1718 * how we do polling eventually, not spinning if we're on potentially 1719 * different devices. 1720 */ 1721 if (wq_list_empty(&ctx->iopoll_list)) { 1722 ctx->poll_multi_queue = false; 1723 } else if (!ctx->poll_multi_queue) { 1724 struct io_kiocb *list_req; 1725 1726 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb, 1727 comp_list); 1728 if (list_req->file != req->file) 1729 ctx->poll_multi_queue = true; 1730 } 1731 1732 /* 1733 * For fast devices, IO may have already completed. If it has, add 1734 * it to the front so we find it first. 1735 */ 1736 if (READ_ONCE(req->iopoll_completed)) 1737 wq_list_add_head(&req->comp_list, &ctx->iopoll_list); 1738 else 1739 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list); 1740 1741 if (unlikely(needs_lock)) { 1742 /* 1743 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle 1744 * in sq thread task context or in io worker task context. If 1745 * current task context is sq thread, we don't need to check 1746 * whether should wake up sq thread. 1747 */ 1748 if ((ctx->flags & IORING_SETUP_SQPOLL) && 1749 wq_has_sleeper(&ctx->sq_data->wait)) 1750 wake_up(&ctx->sq_data->wait); 1751 1752 mutex_unlock(&ctx->uring_lock); 1753 } 1754 } 1755 io_file_get_flags(struct file * file)1756 unsigned int io_file_get_flags(struct file *file) 1757 { 1758 unsigned int res = 0; 1759 1760 if (S_ISREG(file_inode(file)->i_mode)) 1761 res |= REQ_F_ISREG; 1762 if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT)) 1763 res |= REQ_F_SUPPORT_NOWAIT; 1764 return res; 1765 } 1766 io_alloc_async_data(struct io_kiocb * req)1767 bool io_alloc_async_data(struct io_kiocb *req) 1768 { 1769 WARN_ON_ONCE(!io_cold_defs[req->opcode].async_size); 1770 req->async_data = kmalloc(io_cold_defs[req->opcode].async_size, GFP_KERNEL); 1771 if (req->async_data) { 1772 req->flags |= REQ_F_ASYNC_DATA; 1773 return false; 1774 } 1775 return true; 1776 } 1777 io_req_prep_async(struct io_kiocb * req)1778 int io_req_prep_async(struct io_kiocb *req) 1779 { 1780 const struct io_cold_def *cdef = &io_cold_defs[req->opcode]; 1781 const struct io_issue_def *def = &io_issue_defs[req->opcode]; 1782 int ret; 1783 1784 /* assign early for deferred execution for non-fixed file */ 1785 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE) && !req->file) 1786 req->file = io_file_get_normal(req, req->cqe.fd); 1787 if (!cdef->prep_async) 1788 return 0; 1789 if (WARN_ON_ONCE(req_has_async_data(req))) 1790 return -EFAULT; 1791 if (!def->manual_alloc) { 1792 if (io_alloc_async_data(req)) 1793 return -EAGAIN; 1794 } 1795 ret = cdef->prep_async(req); 1796 io_kbuf_recycle(req, 0); 1797 return ret; 1798 } 1799 io_get_sequence(struct io_kiocb * req)1800 static u32 io_get_sequence(struct io_kiocb *req) 1801 { 1802 u32 seq = req->ctx->cached_sq_head; 1803 struct io_kiocb *cur; 1804 1805 /* need original cached_sq_head, but it was increased for each req */ 1806 io_for_each_link(cur, req) 1807 seq--; 1808 return seq; 1809 } 1810 io_drain_req(struct io_kiocb * req)1811 static __cold void io_drain_req(struct io_kiocb *req) 1812 __must_hold(&ctx->uring_lock) 1813 { 1814 struct io_ring_ctx *ctx = req->ctx; 1815 struct io_defer_entry *de; 1816 int ret; 1817 u32 seq = io_get_sequence(req); 1818 1819 /* Still need defer if there is pending req in defer list. */ 1820 spin_lock(&ctx->completion_lock); 1821 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) { 1822 spin_unlock(&ctx->completion_lock); 1823 queue: 1824 ctx->drain_active = false; 1825 io_req_task_queue(req); 1826 return; 1827 } 1828 spin_unlock(&ctx->completion_lock); 1829 1830 io_prep_async_link(req); 1831 de = kmalloc(sizeof(*de), GFP_KERNEL); 1832 if (!de) { 1833 ret = -ENOMEM; 1834 io_req_defer_failed(req, ret); 1835 return; 1836 } 1837 1838 spin_lock(&ctx->completion_lock); 1839 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) { 1840 spin_unlock(&ctx->completion_lock); 1841 kfree(de); 1842 goto queue; 1843 } 1844 1845 trace_io_uring_defer(req); 1846 de->req = req; 1847 de->seq = seq; 1848 list_add_tail(&de->list, &ctx->defer_list); 1849 spin_unlock(&ctx->completion_lock); 1850 } 1851 io_assign_file(struct io_kiocb * req,const struct io_issue_def * def,unsigned int issue_flags)1852 static bool io_assign_file(struct io_kiocb *req, const struct io_issue_def *def, 1853 unsigned int issue_flags) 1854 { 1855 if (req->file || !def->needs_file) 1856 return true; 1857 1858 if (req->flags & REQ_F_FIXED_FILE) 1859 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags); 1860 else 1861 req->file = io_file_get_normal(req, req->cqe.fd); 1862 1863 return !!req->file; 1864 } 1865 io_issue_sqe(struct io_kiocb * req,unsigned int issue_flags)1866 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags) 1867 { 1868 const struct io_issue_def *def = &io_issue_defs[req->opcode]; 1869 const struct cred *creds = NULL; 1870 int ret; 1871 1872 if (unlikely(!io_assign_file(req, def, issue_flags))) 1873 return -EBADF; 1874 1875 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred())) 1876 creds = override_creds(req->creds); 1877 1878 if (!def->audit_skip) 1879 audit_uring_entry(req->opcode); 1880 1881 ret = def->issue(req, issue_flags); 1882 1883 if (!def->audit_skip) 1884 audit_uring_exit(!ret, ret); 1885 1886 if (creds) 1887 revert_creds(creds); 1888 1889 if (ret == IOU_OK) { 1890 if (issue_flags & IO_URING_F_COMPLETE_DEFER) 1891 io_req_complete_defer(req); 1892 else 1893 io_req_complete_post(req, issue_flags); 1894 1895 return 0; 1896 } 1897 1898 if (ret != IOU_ISSUE_SKIP_COMPLETE) 1899 return ret; 1900 1901 /* If the op doesn't have a file, we're not polling for it */ 1902 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && def->iopoll_queue) 1903 io_iopoll_req_issued(req, issue_flags); 1904 1905 return 0; 1906 } 1907 io_poll_issue(struct io_kiocb * req,struct io_tw_state * ts)1908 int io_poll_issue(struct io_kiocb *req, struct io_tw_state *ts) 1909 { 1910 io_tw_lock(req->ctx, ts); 1911 return io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_MULTISHOT| 1912 IO_URING_F_COMPLETE_DEFER); 1913 } 1914 io_wq_free_work(struct io_wq_work * work)1915 struct io_wq_work *io_wq_free_work(struct io_wq_work *work) 1916 { 1917 struct io_kiocb *req = container_of(work, struct io_kiocb, work); 1918 struct io_kiocb *nxt = NULL; 1919 1920 if (req_ref_put_and_test(req)) { 1921 if (req->flags & IO_REQ_LINK_FLAGS) 1922 nxt = io_req_find_next(req); 1923 io_free_req(req); 1924 } 1925 return nxt ? &nxt->work : NULL; 1926 } 1927 io_wq_submit_work(struct io_wq_work * work)1928 void io_wq_submit_work(struct io_wq_work *work) 1929 { 1930 struct io_kiocb *req = container_of(work, struct io_kiocb, work); 1931 const struct io_issue_def *def = &io_issue_defs[req->opcode]; 1932 unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ; 1933 bool needs_poll = false; 1934 int ret = 0, err = -ECANCELED; 1935 1936 /* one will be dropped by ->io_wq_free_work() after returning to io-wq */ 1937 if (!(req->flags & REQ_F_REFCOUNT)) 1938 __io_req_set_refcount(req, 2); 1939 else 1940 req_ref_get(req); 1941 1942 io_arm_ltimeout(req); 1943 1944 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */ 1945 if (work->flags & IO_WQ_WORK_CANCEL) { 1946 fail: 1947 io_req_task_queue_fail(req, err); 1948 return; 1949 } 1950 if (!io_assign_file(req, def, issue_flags)) { 1951 err = -EBADF; 1952 work->flags |= IO_WQ_WORK_CANCEL; 1953 goto fail; 1954 } 1955 1956 if (req->flags & REQ_F_FORCE_ASYNC) { 1957 bool opcode_poll = def->pollin || def->pollout; 1958 1959 if (opcode_poll && file_can_poll(req->file)) { 1960 needs_poll = true; 1961 issue_flags |= IO_URING_F_NONBLOCK; 1962 } 1963 } 1964 1965 do { 1966 ret = io_issue_sqe(req, issue_flags); 1967 if (ret != -EAGAIN) 1968 break; 1969 1970 /* 1971 * If REQ_F_NOWAIT is set, then don't wait or retry with 1972 * poll. -EAGAIN is final for that case. 1973 */ 1974 if (req->flags & REQ_F_NOWAIT) 1975 break; 1976 1977 /* 1978 * We can get EAGAIN for iopolled IO even though we're 1979 * forcing a sync submission from here, since we can't 1980 * wait for request slots on the block side. 1981 */ 1982 if (!needs_poll) { 1983 if (!(req->ctx->flags & IORING_SETUP_IOPOLL)) 1984 break; 1985 if (io_wq_worker_stopped()) 1986 break; 1987 cond_resched(); 1988 continue; 1989 } 1990 1991 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK) 1992 return; 1993 /* aborted or ready, in either case retry blocking */ 1994 needs_poll = false; 1995 issue_flags &= ~IO_URING_F_NONBLOCK; 1996 } while (1); 1997 1998 /* avoid locking problems by failing it from a clean context */ 1999 if (ret < 0) 2000 io_req_task_queue_fail(req, ret); 2001 } 2002 io_file_get_fixed(struct io_kiocb * req,int fd,unsigned int issue_flags)2003 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd, 2004 unsigned int issue_flags) 2005 { 2006 struct io_ring_ctx *ctx = req->ctx; 2007 struct io_fixed_file *slot; 2008 struct file *file = NULL; 2009 2010 io_ring_submit_lock(ctx, issue_flags); 2011 2012 if (unlikely((unsigned int)fd >= ctx->nr_user_files)) 2013 goto out; 2014 fd = array_index_nospec(fd, ctx->nr_user_files); 2015 slot = io_fixed_file_slot(&ctx->file_table, fd); 2016 file = io_slot_file(slot); 2017 req->flags |= io_slot_flags(slot); 2018 io_req_set_rsrc_node(req, ctx, 0); 2019 out: 2020 io_ring_submit_unlock(ctx, issue_flags); 2021 return file; 2022 } 2023 io_file_get_normal(struct io_kiocb * req,int fd)2024 struct file *io_file_get_normal(struct io_kiocb *req, int fd) 2025 { 2026 struct file *file = fget(fd); 2027 2028 trace_io_uring_file_get(req, fd); 2029 2030 /* we don't allow fixed io_uring files */ 2031 if (file && io_is_uring_fops(file)) 2032 io_req_track_inflight(req); 2033 return file; 2034 } 2035 io_queue_async(struct io_kiocb * req,int ret)2036 static void io_queue_async(struct io_kiocb *req, int ret) 2037 __must_hold(&req->ctx->uring_lock) 2038 { 2039 struct io_kiocb *linked_timeout; 2040 2041 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) { 2042 io_req_defer_failed(req, ret); 2043 return; 2044 } 2045 2046 linked_timeout = io_prep_linked_timeout(req); 2047 2048 switch (io_arm_poll_handler(req, 0)) { 2049 case IO_APOLL_READY: 2050 io_kbuf_recycle(req, 0); 2051 io_req_task_queue(req); 2052 break; 2053 case IO_APOLL_ABORTED: 2054 io_kbuf_recycle(req, 0); 2055 io_queue_iowq(req); 2056 break; 2057 case IO_APOLL_OK: 2058 break; 2059 } 2060 2061 if (linked_timeout) 2062 io_queue_linked_timeout(linked_timeout); 2063 } 2064 io_queue_sqe(struct io_kiocb * req)2065 static inline void io_queue_sqe(struct io_kiocb *req) 2066 __must_hold(&req->ctx->uring_lock) 2067 { 2068 int ret; 2069 2070 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER); 2071 2072 /* 2073 * We async punt it if the file wasn't marked NOWAIT, or if the file 2074 * doesn't support non-blocking read/write attempts 2075 */ 2076 if (likely(!ret)) 2077 io_arm_ltimeout(req); 2078 else 2079 io_queue_async(req, ret); 2080 } 2081 io_queue_sqe_fallback(struct io_kiocb * req)2082 static void io_queue_sqe_fallback(struct io_kiocb *req) 2083 __must_hold(&req->ctx->uring_lock) 2084 { 2085 if (unlikely(req->flags & REQ_F_FAIL)) { 2086 /* 2087 * We don't submit, fail them all, for that replace hardlinks 2088 * with normal links. Extra REQ_F_LINK is tolerated. 2089 */ 2090 req->flags &= ~REQ_F_HARDLINK; 2091 req->flags |= REQ_F_LINK; 2092 io_req_defer_failed(req, req->cqe.res); 2093 } else { 2094 int ret = io_req_prep_async(req); 2095 2096 if (unlikely(ret)) { 2097 io_req_defer_failed(req, ret); 2098 return; 2099 } 2100 2101 if (unlikely(req->ctx->drain_active)) 2102 io_drain_req(req); 2103 else 2104 io_queue_iowq(req); 2105 } 2106 } 2107 2108 /* 2109 * Check SQE restrictions (opcode and flags). 2110 * 2111 * Returns 'true' if SQE is allowed, 'false' otherwise. 2112 */ io_check_restriction(struct io_ring_ctx * ctx,struct io_kiocb * req,unsigned int sqe_flags)2113 static inline bool io_check_restriction(struct io_ring_ctx *ctx, 2114 struct io_kiocb *req, 2115 unsigned int sqe_flags) 2116 { 2117 if (!test_bit(req->opcode, ctx->restrictions.sqe_op)) 2118 return false; 2119 2120 if ((sqe_flags & ctx->restrictions.sqe_flags_required) != 2121 ctx->restrictions.sqe_flags_required) 2122 return false; 2123 2124 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed | 2125 ctx->restrictions.sqe_flags_required)) 2126 return false; 2127 2128 return true; 2129 } 2130 io_init_req_drain(struct io_kiocb * req)2131 static void io_init_req_drain(struct io_kiocb *req) 2132 { 2133 struct io_ring_ctx *ctx = req->ctx; 2134 struct io_kiocb *head = ctx->submit_state.link.head; 2135 2136 ctx->drain_active = true; 2137 if (head) { 2138 /* 2139 * If we need to drain a request in the middle of a link, drain 2140 * the head request and the next request/link after the current 2141 * link. Considering sequential execution of links, 2142 * REQ_F_IO_DRAIN will be maintained for every request of our 2143 * link. 2144 */ 2145 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC; 2146 ctx->drain_next = true; 2147 } 2148 } 2149 io_init_fail_req(struct io_kiocb * req,int err)2150 static __cold int io_init_fail_req(struct io_kiocb *req, int err) 2151 { 2152 /* ensure per-opcode data is cleared if we fail before prep */ 2153 memset(&req->cmd.data, 0, sizeof(req->cmd.data)); 2154 return err; 2155 } 2156 io_init_req(struct io_ring_ctx * ctx,struct io_kiocb * req,const struct io_uring_sqe * sqe)2157 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req, 2158 const struct io_uring_sqe *sqe) 2159 __must_hold(&ctx->uring_lock) 2160 { 2161 const struct io_issue_def *def; 2162 unsigned int sqe_flags; 2163 int personality; 2164 u8 opcode; 2165 2166 /* req is partially pre-initialised, see io_preinit_req() */ 2167 req->opcode = opcode = READ_ONCE(sqe->opcode); 2168 /* same numerical values with corresponding REQ_F_*, safe to copy */ 2169 req->flags = sqe_flags = READ_ONCE(sqe->flags); 2170 req->cqe.user_data = READ_ONCE(sqe->user_data); 2171 req->file = NULL; 2172 req->rsrc_node = NULL; 2173 req->task = current; 2174 2175 if (unlikely(opcode >= IORING_OP_LAST)) { 2176 req->opcode = 0; 2177 return io_init_fail_req(req, -EINVAL); 2178 } 2179 opcode = array_index_nospec(opcode, IORING_OP_LAST); 2180 2181 def = &io_issue_defs[opcode]; 2182 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) { 2183 /* enforce forwards compatibility on users */ 2184 if (sqe_flags & ~SQE_VALID_FLAGS) 2185 return io_init_fail_req(req, -EINVAL); 2186 if (sqe_flags & IOSQE_BUFFER_SELECT) { 2187 if (!def->buffer_select) 2188 return io_init_fail_req(req, -EOPNOTSUPP); 2189 req->buf_index = READ_ONCE(sqe->buf_group); 2190 } 2191 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS) 2192 ctx->drain_disabled = true; 2193 if (sqe_flags & IOSQE_IO_DRAIN) { 2194 if (ctx->drain_disabled) 2195 return io_init_fail_req(req, -EOPNOTSUPP); 2196 io_init_req_drain(req); 2197 } 2198 } 2199 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) { 2200 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags)) 2201 return io_init_fail_req(req, -EACCES); 2202 /* knock it to the slow queue path, will be drained there */ 2203 if (ctx->drain_active) 2204 req->flags |= REQ_F_FORCE_ASYNC; 2205 /* if there is no link, we're at "next" request and need to drain */ 2206 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) { 2207 ctx->drain_next = false; 2208 ctx->drain_active = true; 2209 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC; 2210 } 2211 } 2212 2213 if (!def->ioprio && sqe->ioprio) 2214 return io_init_fail_req(req, -EINVAL); 2215 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL)) 2216 return io_init_fail_req(req, -EINVAL); 2217 2218 if (def->needs_file) { 2219 struct io_submit_state *state = &ctx->submit_state; 2220 2221 req->cqe.fd = READ_ONCE(sqe->fd); 2222 2223 /* 2224 * Plug now if we have more than 2 IO left after this, and the 2225 * target is potentially a read/write to block based storage. 2226 */ 2227 if (state->need_plug && def->plug) { 2228 state->plug_started = true; 2229 state->need_plug = false; 2230 blk_start_plug_nr_ios(&state->plug, state->submit_nr); 2231 } 2232 } 2233 2234 personality = READ_ONCE(sqe->personality); 2235 if (personality) { 2236 int ret; 2237 2238 req->creds = xa_load(&ctx->personalities, personality); 2239 if (!req->creds) 2240 return io_init_fail_req(req, -EINVAL); 2241 get_cred(req->creds); 2242 ret = security_uring_override_creds(req->creds); 2243 if (ret) { 2244 put_cred(req->creds); 2245 return io_init_fail_req(req, ret); 2246 } 2247 req->flags |= REQ_F_CREDS; 2248 } 2249 2250 return def->prep(req, sqe); 2251 } 2252 io_submit_fail_init(const struct io_uring_sqe * sqe,struct io_kiocb * req,int ret)2253 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe, 2254 struct io_kiocb *req, int ret) 2255 { 2256 struct io_ring_ctx *ctx = req->ctx; 2257 struct io_submit_link *link = &ctx->submit_state.link; 2258 struct io_kiocb *head = link->head; 2259 2260 trace_io_uring_req_failed(sqe, req, ret); 2261 2262 /* 2263 * Avoid breaking links in the middle as it renders links with SQPOLL 2264 * unusable. Instead of failing eagerly, continue assembling the link if 2265 * applicable and mark the head with REQ_F_FAIL. The link flushing code 2266 * should find the flag and handle the rest. 2267 */ 2268 req_fail_link_node(req, ret); 2269 if (head && !(head->flags & REQ_F_FAIL)) 2270 req_fail_link_node(head, -ECANCELED); 2271 2272 if (!(req->flags & IO_REQ_LINK_FLAGS)) { 2273 if (head) { 2274 link->last->link = req; 2275 link->head = NULL; 2276 req = head; 2277 } 2278 io_queue_sqe_fallback(req); 2279 return ret; 2280 } 2281 2282 if (head) 2283 link->last->link = req; 2284 else 2285 link->head = req; 2286 link->last = req; 2287 return 0; 2288 } 2289 io_submit_sqe(struct io_ring_ctx * ctx,struct io_kiocb * req,const struct io_uring_sqe * sqe)2290 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req, 2291 const struct io_uring_sqe *sqe) 2292 __must_hold(&ctx->uring_lock) 2293 { 2294 struct io_submit_link *link = &ctx->submit_state.link; 2295 int ret; 2296 2297 ret = io_init_req(ctx, req, sqe); 2298 if (unlikely(ret)) 2299 return io_submit_fail_init(sqe, req, ret); 2300 2301 trace_io_uring_submit_req(req); 2302 2303 /* 2304 * If we already have a head request, queue this one for async 2305 * submittal once the head completes. If we don't have a head but 2306 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be 2307 * submitted sync once the chain is complete. If none of those 2308 * conditions are true (normal request), then just queue it. 2309 */ 2310 if (unlikely(link->head)) { 2311 ret = io_req_prep_async(req); 2312 if (unlikely(ret)) 2313 return io_submit_fail_init(sqe, req, ret); 2314 2315 trace_io_uring_link(req, link->head); 2316 link->last->link = req; 2317 link->last = req; 2318 2319 if (req->flags & IO_REQ_LINK_FLAGS) 2320 return 0; 2321 /* last request of the link, flush it */ 2322 req = link->head; 2323 link->head = NULL; 2324 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)) 2325 goto fallback; 2326 2327 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS | 2328 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) { 2329 if (req->flags & IO_REQ_LINK_FLAGS) { 2330 link->head = req; 2331 link->last = req; 2332 } else { 2333 fallback: 2334 io_queue_sqe_fallback(req); 2335 } 2336 return 0; 2337 } 2338 2339 io_queue_sqe(req); 2340 return 0; 2341 } 2342 2343 /* 2344 * Batched submission is done, ensure local IO is flushed out. 2345 */ io_submit_state_end(struct io_ring_ctx * ctx)2346 static void io_submit_state_end(struct io_ring_ctx *ctx) 2347 { 2348 struct io_submit_state *state = &ctx->submit_state; 2349 2350 if (unlikely(state->link.head)) 2351 io_queue_sqe_fallback(state->link.head); 2352 /* flush only after queuing links as they can generate completions */ 2353 io_submit_flush_completions(ctx); 2354 if (state->plug_started) 2355 blk_finish_plug(&state->plug); 2356 } 2357 2358 /* 2359 * Start submission side cache. 2360 */ io_submit_state_start(struct io_submit_state * state,unsigned int max_ios)2361 static void io_submit_state_start(struct io_submit_state *state, 2362 unsigned int max_ios) 2363 { 2364 state->plug_started = false; 2365 state->need_plug = max_ios > 2; 2366 state->submit_nr = max_ios; 2367 /* set only head, no need to init link_last in advance */ 2368 state->link.head = NULL; 2369 } 2370 io_commit_sqring(struct io_ring_ctx * ctx)2371 static void io_commit_sqring(struct io_ring_ctx *ctx) 2372 { 2373 struct io_rings *rings = ctx->rings; 2374 2375 /* 2376 * Ensure any loads from the SQEs are done at this point, 2377 * since once we write the new head, the application could 2378 * write new data to them. 2379 */ 2380 smp_store_release(&rings->sq.head, ctx->cached_sq_head); 2381 } 2382 2383 /* 2384 * Fetch an sqe, if one is available. Note this returns a pointer to memory 2385 * that is mapped by userspace. This means that care needs to be taken to 2386 * ensure that reads are stable, as we cannot rely on userspace always 2387 * being a good citizen. If members of the sqe are validated and then later 2388 * used, it's important that those reads are done through READ_ONCE() to 2389 * prevent a re-load down the line. 2390 */ io_get_sqe(struct io_ring_ctx * ctx,const struct io_uring_sqe ** sqe)2391 static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe) 2392 { 2393 unsigned mask = ctx->sq_entries - 1; 2394 unsigned head = ctx->cached_sq_head++ & mask; 2395 2396 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY)) { 2397 head = READ_ONCE(ctx->sq_array[head]); 2398 if (unlikely(head >= ctx->sq_entries)) { 2399 /* drop invalid entries */ 2400 spin_lock(&ctx->completion_lock); 2401 ctx->cq_extra--; 2402 spin_unlock(&ctx->completion_lock); 2403 WRITE_ONCE(ctx->rings->sq_dropped, 2404 READ_ONCE(ctx->rings->sq_dropped) + 1); 2405 return false; 2406 } 2407 } 2408 2409 /* 2410 * The cached sq head (or cq tail) serves two purposes: 2411 * 2412 * 1) allows us to batch the cost of updating the user visible 2413 * head updates. 2414 * 2) allows the kernel side to track the head on its own, even 2415 * though the application is the one updating it. 2416 */ 2417 2418 /* double index for 128-byte SQEs, twice as long */ 2419 if (ctx->flags & IORING_SETUP_SQE128) 2420 head <<= 1; 2421 *sqe = &ctx->sq_sqes[head]; 2422 return true; 2423 } 2424 io_submit_sqes(struct io_ring_ctx * ctx,unsigned int nr)2425 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr) 2426 __must_hold(&ctx->uring_lock) 2427 { 2428 unsigned int entries = io_sqring_entries(ctx); 2429 unsigned int left; 2430 int ret; 2431 2432 if (unlikely(!entries)) 2433 return 0; 2434 /* make sure SQ entry isn't read before tail */ 2435 ret = left = min(nr, entries); 2436 io_get_task_refs(left); 2437 io_submit_state_start(&ctx->submit_state, left); 2438 2439 do { 2440 const struct io_uring_sqe *sqe; 2441 struct io_kiocb *req; 2442 2443 if (unlikely(!io_alloc_req(ctx, &req))) 2444 break; 2445 if (unlikely(!io_get_sqe(ctx, &sqe))) { 2446 io_req_add_to_cache(req, ctx); 2447 break; 2448 } 2449 2450 /* 2451 * Continue submitting even for sqe failure if the 2452 * ring was setup with IORING_SETUP_SUBMIT_ALL 2453 */ 2454 if (unlikely(io_submit_sqe(ctx, req, sqe)) && 2455 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) { 2456 left--; 2457 break; 2458 } 2459 } while (--left); 2460 2461 if (unlikely(left)) { 2462 ret -= left; 2463 /* try again if it submitted nothing and can't allocate a req */ 2464 if (!ret && io_req_cache_empty(ctx)) 2465 ret = -EAGAIN; 2466 current->io_uring->cached_refs += left; 2467 } 2468 2469 io_submit_state_end(ctx); 2470 /* Commit SQ ring head once we've consumed and submitted all SQEs */ 2471 io_commit_sqring(ctx); 2472 return ret; 2473 } 2474 2475 struct io_wait_queue { 2476 struct wait_queue_entry wq; 2477 struct io_ring_ctx *ctx; 2478 unsigned cq_tail; 2479 unsigned nr_timeouts; 2480 ktime_t timeout; 2481 }; 2482 io_has_work(struct io_ring_ctx * ctx)2483 static inline bool io_has_work(struct io_ring_ctx *ctx) 2484 { 2485 return test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq) || 2486 !llist_empty(&ctx->work_llist); 2487 } 2488 io_should_wake(struct io_wait_queue * iowq)2489 static inline bool io_should_wake(struct io_wait_queue *iowq) 2490 { 2491 struct io_ring_ctx *ctx = iowq->ctx; 2492 int dist = READ_ONCE(ctx->rings->cq.tail) - (int) iowq->cq_tail; 2493 2494 /* 2495 * Wake up if we have enough events, or if a timeout occurred since we 2496 * started waiting. For timeouts, we always want to return to userspace, 2497 * regardless of event count. 2498 */ 2499 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts; 2500 } 2501 io_wake_function(struct wait_queue_entry * curr,unsigned int mode,int wake_flags,void * key)2502 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode, 2503 int wake_flags, void *key) 2504 { 2505 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue, wq); 2506 2507 /* 2508 * Cannot safely flush overflowed CQEs from here, ensure we wake up 2509 * the task, and the next invocation will do it. 2510 */ 2511 if (io_should_wake(iowq) || io_has_work(iowq->ctx)) 2512 return autoremove_wake_function(curr, mode, wake_flags, key); 2513 return -1; 2514 } 2515 io_run_task_work_sig(struct io_ring_ctx * ctx)2516 int io_run_task_work_sig(struct io_ring_ctx *ctx) 2517 { 2518 if (!llist_empty(&ctx->work_llist)) { 2519 __set_current_state(TASK_RUNNING); 2520 if (io_run_local_work(ctx, INT_MAX) > 0) 2521 return 0; 2522 } 2523 if (io_run_task_work() > 0) 2524 return 0; 2525 if (task_sigpending(current)) 2526 return -EINTR; 2527 return 0; 2528 } 2529 current_pending_io(void)2530 static bool current_pending_io(void) 2531 { 2532 struct io_uring_task *tctx = current->io_uring; 2533 2534 if (!tctx) 2535 return false; 2536 return percpu_counter_read_positive(&tctx->inflight); 2537 } 2538 2539 /* when returns >0, the caller should retry */ io_cqring_wait_schedule(struct io_ring_ctx * ctx,struct io_wait_queue * iowq)2540 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx, 2541 struct io_wait_queue *iowq) 2542 { 2543 int ret; 2544 2545 if (unlikely(READ_ONCE(ctx->check_cq))) 2546 return 1; 2547 if (unlikely(!llist_empty(&ctx->work_llist))) 2548 return 1; 2549 if (unlikely(task_work_pending(current))) 2550 return 1; 2551 if (unlikely(task_sigpending(current))) 2552 return -EINTR; 2553 if (unlikely(io_should_wake(iowq))) 2554 return 0; 2555 2556 /* 2557 * Mark us as being in io_wait if we have pending requests, so cpufreq 2558 * can take into account that the task is waiting for IO - turns out 2559 * to be important for low QD IO. 2560 */ 2561 if (current_pending_io()) 2562 current->in_iowait = 1; 2563 ret = 0; 2564 if (iowq->timeout == KTIME_MAX) 2565 schedule(); 2566 else if (!schedule_hrtimeout(&iowq->timeout, HRTIMER_MODE_ABS)) 2567 ret = -ETIME; 2568 current->in_iowait = 0; 2569 return ret; 2570 } 2571 2572 /* 2573 * Wait until events become available, if we don't already have some. The 2574 * application must reap them itself, as they reside on the shared cq ring. 2575 */ io_cqring_wait(struct io_ring_ctx * ctx,int min_events,const sigset_t __user * sig,size_t sigsz,struct __kernel_timespec __user * uts)2576 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events, 2577 const sigset_t __user *sig, size_t sigsz, 2578 struct __kernel_timespec __user *uts) 2579 { 2580 struct io_wait_queue iowq; 2581 struct io_rings *rings = ctx->rings; 2582 int ret; 2583 2584 if (!io_allowed_run_tw(ctx)) 2585 return -EEXIST; 2586 if (!llist_empty(&ctx->work_llist)) 2587 io_run_local_work(ctx, min_events); 2588 io_run_task_work(); 2589 io_cqring_overflow_flush(ctx); 2590 /* if user messes with these they will just get an early return */ 2591 if (__io_cqring_events_user(ctx) >= min_events) 2592 return 0; 2593 2594 init_waitqueue_func_entry(&iowq.wq, io_wake_function); 2595 iowq.wq.private = current; 2596 INIT_LIST_HEAD(&iowq.wq.entry); 2597 iowq.ctx = ctx; 2598 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts); 2599 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events; 2600 iowq.timeout = KTIME_MAX; 2601 2602 if (uts) { 2603 struct timespec64 ts; 2604 2605 if (get_timespec64(&ts, uts)) 2606 return -EFAULT; 2607 iowq.timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns()); 2608 } 2609 2610 if (sig) { 2611 #ifdef CONFIG_COMPAT 2612 if (in_compat_syscall()) 2613 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig, 2614 sigsz); 2615 else 2616 #endif 2617 ret = set_user_sigmask(sig, sigsz); 2618 2619 if (ret) 2620 return ret; 2621 } 2622 2623 trace_io_uring_cqring_wait(ctx, min_events); 2624 do { 2625 int nr_wait = (int) iowq.cq_tail - READ_ONCE(ctx->rings->cq.tail); 2626 unsigned long check_cq; 2627 2628 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) { 2629 atomic_set(&ctx->cq_wait_nr, nr_wait); 2630 set_current_state(TASK_INTERRUPTIBLE); 2631 } else { 2632 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq, 2633 TASK_INTERRUPTIBLE); 2634 } 2635 2636 ret = io_cqring_wait_schedule(ctx, &iowq); 2637 __set_current_state(TASK_RUNNING); 2638 atomic_set(&ctx->cq_wait_nr, 0); 2639 2640 /* 2641 * Run task_work after scheduling and before io_should_wake(). 2642 * If we got woken because of task_work being processed, run it 2643 * now rather than let the caller do another wait loop. 2644 */ 2645 if (!llist_empty(&ctx->work_llist)) 2646 io_run_local_work(ctx, nr_wait); 2647 io_run_task_work(); 2648 2649 /* 2650 * Non-local task_work will be run on exit to userspace, but 2651 * if we're using DEFER_TASKRUN, then we could have waited 2652 * with a timeout for a number of requests. If the timeout 2653 * hits, we could have some requests ready to process. Ensure 2654 * this break is _after_ we have run task_work, to avoid 2655 * deferring running potentially pending requests until the 2656 * next time we wait for events. 2657 */ 2658 if (ret < 0) 2659 break; 2660 2661 check_cq = READ_ONCE(ctx->check_cq); 2662 if (unlikely(check_cq)) { 2663 /* let the caller flush overflows, retry */ 2664 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)) 2665 io_cqring_do_overflow_flush(ctx); 2666 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)) { 2667 ret = -EBADR; 2668 break; 2669 } 2670 } 2671 2672 if (io_should_wake(&iowq)) { 2673 ret = 0; 2674 break; 2675 } 2676 cond_resched(); 2677 } while (1); 2678 2679 if (!(ctx->flags & IORING_SETUP_DEFER_TASKRUN)) 2680 finish_wait(&ctx->cq_wait, &iowq.wq); 2681 restore_saved_sigmask_unless(ret == -EINTR); 2682 2683 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0; 2684 } 2685 io_mem_free(void * ptr)2686 void io_mem_free(void *ptr) 2687 { 2688 if (!ptr) 2689 return; 2690 2691 folio_put(virt_to_folio(ptr)); 2692 } 2693 io_pages_free(struct page *** pages,int npages)2694 static void io_pages_free(struct page ***pages, int npages) 2695 { 2696 struct page **page_array; 2697 int i; 2698 2699 if (!pages) 2700 return; 2701 2702 page_array = *pages; 2703 if (!page_array) 2704 return; 2705 2706 for (i = 0; i < npages; i++) 2707 unpin_user_page(page_array[i]); 2708 kvfree(page_array); 2709 *pages = NULL; 2710 } 2711 __io_uaddr_map(struct page *** pages,unsigned short * npages,unsigned long uaddr,size_t size)2712 static void *__io_uaddr_map(struct page ***pages, unsigned short *npages, 2713 unsigned long uaddr, size_t size) 2714 { 2715 struct page **page_array; 2716 unsigned int nr_pages; 2717 void *page_addr; 2718 int ret, i, pinned; 2719 2720 *npages = 0; 2721 2722 if (uaddr & (PAGE_SIZE - 1) || !size) 2723 return ERR_PTR(-EINVAL); 2724 2725 nr_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT; 2726 if (nr_pages > USHRT_MAX) 2727 return ERR_PTR(-EINVAL); 2728 page_array = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL); 2729 if (!page_array) 2730 return ERR_PTR(-ENOMEM); 2731 2732 2733 pinned = pin_user_pages_fast(uaddr, nr_pages, FOLL_WRITE | FOLL_LONGTERM, 2734 page_array); 2735 if (pinned != nr_pages) { 2736 ret = (pinned < 0) ? pinned : -EFAULT; 2737 goto free_pages; 2738 } 2739 2740 page_addr = page_address(page_array[0]); 2741 for (i = 0; i < nr_pages; i++) { 2742 ret = -EINVAL; 2743 2744 /* 2745 * Can't support mapping user allocated ring memory on 32-bit 2746 * archs where it could potentially reside in highmem. Just 2747 * fail those with -EINVAL, just like we did on kernels that 2748 * didn't support this feature. 2749 */ 2750 if (PageHighMem(page_array[i])) 2751 goto free_pages; 2752 2753 /* 2754 * No support for discontig pages for now, should either be a 2755 * single normal page, or a huge page. Later on we can add 2756 * support for remapping discontig pages, for now we will 2757 * just fail them with EINVAL. 2758 */ 2759 if (page_address(page_array[i]) != page_addr) 2760 goto free_pages; 2761 page_addr += PAGE_SIZE; 2762 } 2763 2764 *pages = page_array; 2765 *npages = nr_pages; 2766 return page_to_virt(page_array[0]); 2767 2768 free_pages: 2769 io_pages_free(&page_array, pinned > 0 ? pinned : 0); 2770 return ERR_PTR(ret); 2771 } 2772 io_rings_map(struct io_ring_ctx * ctx,unsigned long uaddr,size_t size)2773 static void *io_rings_map(struct io_ring_ctx *ctx, unsigned long uaddr, 2774 size_t size) 2775 { 2776 return __io_uaddr_map(&ctx->ring_pages, &ctx->n_ring_pages, uaddr, 2777 size); 2778 } 2779 io_sqes_map(struct io_ring_ctx * ctx,unsigned long uaddr,size_t size)2780 static void *io_sqes_map(struct io_ring_ctx *ctx, unsigned long uaddr, 2781 size_t size) 2782 { 2783 return __io_uaddr_map(&ctx->sqe_pages, &ctx->n_sqe_pages, uaddr, 2784 size); 2785 } 2786 io_rings_free(struct io_ring_ctx * ctx)2787 static void io_rings_free(struct io_ring_ctx *ctx) 2788 { 2789 if (!(ctx->flags & IORING_SETUP_NO_MMAP)) { 2790 io_mem_free(ctx->rings); 2791 io_mem_free(ctx->sq_sqes); 2792 } else { 2793 io_pages_free(&ctx->ring_pages, ctx->n_ring_pages); 2794 ctx->n_ring_pages = 0; 2795 io_pages_free(&ctx->sqe_pages, ctx->n_sqe_pages); 2796 ctx->n_sqe_pages = 0; 2797 } 2798 2799 ctx->rings = NULL; 2800 ctx->sq_sqes = NULL; 2801 } 2802 io_mem_alloc(size_t size)2803 void *io_mem_alloc(size_t size) 2804 { 2805 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP; 2806 void *ret; 2807 2808 ret = (void *) __get_free_pages(gfp, get_order(size)); 2809 if (ret) 2810 return ret; 2811 return ERR_PTR(-ENOMEM); 2812 } 2813 rings_size(struct io_ring_ctx * ctx,unsigned int sq_entries,unsigned int cq_entries,size_t * sq_offset)2814 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries, 2815 unsigned int cq_entries, size_t *sq_offset) 2816 { 2817 struct io_rings *rings; 2818 size_t off, sq_array_size; 2819 2820 off = struct_size(rings, cqes, cq_entries); 2821 if (off == SIZE_MAX) 2822 return SIZE_MAX; 2823 if (ctx->flags & IORING_SETUP_CQE32) { 2824 if (check_shl_overflow(off, 1, &off)) 2825 return SIZE_MAX; 2826 } 2827 2828 #ifdef CONFIG_SMP 2829 off = ALIGN(off, SMP_CACHE_BYTES); 2830 if (off == 0) 2831 return SIZE_MAX; 2832 #endif 2833 2834 if (ctx->flags & IORING_SETUP_NO_SQARRAY) { 2835 if (sq_offset) 2836 *sq_offset = SIZE_MAX; 2837 return off; 2838 } 2839 2840 if (sq_offset) 2841 *sq_offset = off; 2842 2843 sq_array_size = array_size(sizeof(u32), sq_entries); 2844 if (sq_array_size == SIZE_MAX) 2845 return SIZE_MAX; 2846 2847 if (check_add_overflow(off, sq_array_size, &off)) 2848 return SIZE_MAX; 2849 2850 return off; 2851 } 2852 io_eventfd_register(struct io_ring_ctx * ctx,void __user * arg,unsigned int eventfd_async)2853 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg, 2854 unsigned int eventfd_async) 2855 { 2856 struct io_ev_fd *ev_fd; 2857 __s32 __user *fds = arg; 2858 int fd; 2859 2860 ev_fd = rcu_dereference_protected(ctx->io_ev_fd, 2861 lockdep_is_held(&ctx->uring_lock)); 2862 if (ev_fd) 2863 return -EBUSY; 2864 2865 if (copy_from_user(&fd, fds, sizeof(*fds))) 2866 return -EFAULT; 2867 2868 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL); 2869 if (!ev_fd) 2870 return -ENOMEM; 2871 2872 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd); 2873 if (IS_ERR(ev_fd->cq_ev_fd)) { 2874 int ret = PTR_ERR(ev_fd->cq_ev_fd); 2875 kfree(ev_fd); 2876 return ret; 2877 } 2878 2879 spin_lock(&ctx->completion_lock); 2880 ctx->evfd_last_cq_tail = ctx->cached_cq_tail; 2881 spin_unlock(&ctx->completion_lock); 2882 2883 ev_fd->eventfd_async = eventfd_async; 2884 ctx->has_evfd = true; 2885 rcu_assign_pointer(ctx->io_ev_fd, ev_fd); 2886 atomic_set(&ev_fd->refs, 1); 2887 atomic_set(&ev_fd->ops, 0); 2888 return 0; 2889 } 2890 io_eventfd_unregister(struct io_ring_ctx * ctx)2891 static int io_eventfd_unregister(struct io_ring_ctx *ctx) 2892 { 2893 struct io_ev_fd *ev_fd; 2894 2895 ev_fd = rcu_dereference_protected(ctx->io_ev_fd, 2896 lockdep_is_held(&ctx->uring_lock)); 2897 if (ev_fd) { 2898 ctx->has_evfd = false; 2899 rcu_assign_pointer(ctx->io_ev_fd, NULL); 2900 if (!atomic_fetch_or(BIT(IO_EVENTFD_OP_FREE_BIT), &ev_fd->ops)) 2901 call_rcu(&ev_fd->rcu, io_eventfd_ops); 2902 return 0; 2903 } 2904 2905 return -ENXIO; 2906 } 2907 io_req_caches_free(struct io_ring_ctx * ctx)2908 static void io_req_caches_free(struct io_ring_ctx *ctx) 2909 { 2910 struct io_kiocb *req; 2911 int nr = 0; 2912 2913 mutex_lock(&ctx->uring_lock); 2914 io_flush_cached_locked_reqs(ctx, &ctx->submit_state); 2915 2916 while (!io_req_cache_empty(ctx)) { 2917 req = io_extract_req(ctx); 2918 kmem_cache_free(req_cachep, req); 2919 nr++; 2920 } 2921 if (nr) 2922 percpu_ref_put_many(&ctx->refs, nr); 2923 mutex_unlock(&ctx->uring_lock); 2924 } 2925 io_rsrc_node_cache_free(struct io_cache_entry * entry)2926 static void io_rsrc_node_cache_free(struct io_cache_entry *entry) 2927 { 2928 kfree(container_of(entry, struct io_rsrc_node, cache)); 2929 } 2930 io_ring_ctx_free(struct io_ring_ctx * ctx)2931 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx) 2932 { 2933 io_sq_thread_finish(ctx); 2934 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */ 2935 if (WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list))) 2936 return; 2937 2938 mutex_lock(&ctx->uring_lock); 2939 if (ctx->buf_data) 2940 __io_sqe_buffers_unregister(ctx); 2941 if (ctx->file_data) 2942 __io_sqe_files_unregister(ctx); 2943 io_cqring_overflow_kill(ctx); 2944 io_eventfd_unregister(ctx); 2945 io_alloc_cache_free(&ctx->apoll_cache, io_apoll_cache_free); 2946 io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free); 2947 io_destroy_buffers(ctx); 2948 mutex_unlock(&ctx->uring_lock); 2949 if (ctx->sq_creds) 2950 put_cred(ctx->sq_creds); 2951 if (ctx->submitter_task) 2952 put_task_struct(ctx->submitter_task); 2953 2954 /* there are no registered resources left, nobody uses it */ 2955 if (ctx->rsrc_node) 2956 io_rsrc_node_destroy(ctx, ctx->rsrc_node); 2957 2958 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list)); 2959 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list)); 2960 2961 io_alloc_cache_free(&ctx->rsrc_node_cache, io_rsrc_node_cache_free); 2962 if (ctx->mm_account) { 2963 mmdrop(ctx->mm_account); 2964 ctx->mm_account = NULL; 2965 } 2966 io_rings_free(ctx); 2967 io_kbuf_mmap_list_free(ctx); 2968 2969 percpu_ref_exit(&ctx->refs); 2970 free_uid(ctx->user); 2971 io_req_caches_free(ctx); 2972 if (ctx->hash_map) 2973 io_wq_put_hash(ctx->hash_map); 2974 kfree(ctx->cancel_table.hbs); 2975 kfree(ctx->cancel_table_locked.hbs); 2976 xa_destroy(&ctx->io_bl_xa); 2977 kfree(ctx); 2978 } 2979 io_activate_pollwq_cb(struct callback_head * cb)2980 static __cold void io_activate_pollwq_cb(struct callback_head *cb) 2981 { 2982 struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx, 2983 poll_wq_task_work); 2984 2985 mutex_lock(&ctx->uring_lock); 2986 ctx->poll_activated = true; 2987 mutex_unlock(&ctx->uring_lock); 2988 2989 /* 2990 * Wake ups for some events between start of polling and activation 2991 * might've been lost due to loose synchronisation. 2992 */ 2993 wake_up_all(&ctx->poll_wq); 2994 percpu_ref_put(&ctx->refs); 2995 } 2996 io_activate_pollwq(struct io_ring_ctx * ctx)2997 static __cold void io_activate_pollwq(struct io_ring_ctx *ctx) 2998 { 2999 spin_lock(&ctx->completion_lock); 3000 /* already activated or in progress */ 3001 if (ctx->poll_activated || ctx->poll_wq_task_work.func) 3002 goto out; 3003 if (WARN_ON_ONCE(!ctx->task_complete)) 3004 goto out; 3005 if (!ctx->submitter_task) 3006 goto out; 3007 /* 3008 * with ->submitter_task only the submitter task completes requests, we 3009 * only need to sync with it, which is done by injecting a tw 3010 */ 3011 init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb); 3012 percpu_ref_get(&ctx->refs); 3013 if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL)) 3014 percpu_ref_put(&ctx->refs); 3015 out: 3016 spin_unlock(&ctx->completion_lock); 3017 } 3018 io_uring_poll(struct file * file,poll_table * wait)3019 static __poll_t io_uring_poll(struct file *file, poll_table *wait) 3020 { 3021 struct io_ring_ctx *ctx = file->private_data; 3022 __poll_t mask = 0; 3023 3024 if (unlikely(!ctx->poll_activated)) 3025 io_activate_pollwq(ctx); 3026 3027 poll_wait(file, &ctx->poll_wq, wait); 3028 /* 3029 * synchronizes with barrier from wq_has_sleeper call in 3030 * io_commit_cqring 3031 */ 3032 smp_rmb(); 3033 if (!io_sqring_full(ctx)) 3034 mask |= EPOLLOUT | EPOLLWRNORM; 3035 3036 /* 3037 * Don't flush cqring overflow list here, just do a simple check. 3038 * Otherwise there could possible be ABBA deadlock: 3039 * CPU0 CPU1 3040 * ---- ---- 3041 * lock(&ctx->uring_lock); 3042 * lock(&ep->mtx); 3043 * lock(&ctx->uring_lock); 3044 * lock(&ep->mtx); 3045 * 3046 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this 3047 * pushes them to do the flush. 3048 */ 3049 3050 if (__io_cqring_events_user(ctx) || io_has_work(ctx)) 3051 mask |= EPOLLIN | EPOLLRDNORM; 3052 3053 return mask; 3054 } 3055 io_unregister_personality(struct io_ring_ctx * ctx,unsigned id)3056 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id) 3057 { 3058 const struct cred *creds; 3059 3060 creds = xa_erase(&ctx->personalities, id); 3061 if (creds) { 3062 put_cred(creds); 3063 return 0; 3064 } 3065 3066 return -EINVAL; 3067 } 3068 3069 struct io_tctx_exit { 3070 struct callback_head task_work; 3071 struct completion completion; 3072 struct io_ring_ctx *ctx; 3073 }; 3074 io_tctx_exit_cb(struct callback_head * cb)3075 static __cold void io_tctx_exit_cb(struct callback_head *cb) 3076 { 3077 struct io_uring_task *tctx = current->io_uring; 3078 struct io_tctx_exit *work; 3079 3080 work = container_of(cb, struct io_tctx_exit, task_work); 3081 /* 3082 * When @in_cancel, we're in cancellation and it's racy to remove the 3083 * node. It'll be removed by the end of cancellation, just ignore it. 3084 * tctx can be NULL if the queueing of this task_work raced with 3085 * work cancelation off the exec path. 3086 */ 3087 if (tctx && !atomic_read(&tctx->in_cancel)) 3088 io_uring_del_tctx_node((unsigned long)work->ctx); 3089 complete(&work->completion); 3090 } 3091 io_cancel_ctx_cb(struct io_wq_work * work,void * data)3092 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data) 3093 { 3094 struct io_kiocb *req = container_of(work, struct io_kiocb, work); 3095 3096 return req->ctx == data; 3097 } 3098 io_ring_exit_work(struct work_struct * work)3099 static __cold void io_ring_exit_work(struct work_struct *work) 3100 { 3101 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work); 3102 unsigned long timeout = jiffies + HZ * 60 * 5; 3103 unsigned long interval = HZ / 20; 3104 struct io_tctx_exit exit; 3105 struct io_tctx_node *node; 3106 int ret; 3107 3108 /* 3109 * If we're doing polled IO and end up having requests being 3110 * submitted async (out-of-line), then completions can come in while 3111 * we're waiting for refs to drop. We need to reap these manually, 3112 * as nobody else will be looking for them. 3113 */ 3114 do { 3115 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) { 3116 mutex_lock(&ctx->uring_lock); 3117 io_cqring_overflow_kill(ctx); 3118 mutex_unlock(&ctx->uring_lock); 3119 } 3120 3121 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) 3122 io_move_task_work_from_local(ctx); 3123 3124 while (io_uring_try_cancel_requests(ctx, NULL, true)) 3125 cond_resched(); 3126 3127 if (ctx->sq_data) { 3128 struct io_sq_data *sqd = ctx->sq_data; 3129 struct task_struct *tsk; 3130 3131 io_sq_thread_park(sqd); 3132 tsk = sqd->thread; 3133 if (tsk && tsk->io_uring && tsk->io_uring->io_wq) 3134 io_wq_cancel_cb(tsk->io_uring->io_wq, 3135 io_cancel_ctx_cb, ctx, true); 3136 io_sq_thread_unpark(sqd); 3137 } 3138 3139 io_req_caches_free(ctx); 3140 3141 if (WARN_ON_ONCE(time_after(jiffies, timeout))) { 3142 /* there is little hope left, don't run it too often */ 3143 interval = HZ * 60; 3144 } 3145 /* 3146 * This is really an uninterruptible wait, as it has to be 3147 * complete. But it's also run from a kworker, which doesn't 3148 * take signals, so it's fine to make it interruptible. This 3149 * avoids scenarios where we knowingly can wait much longer 3150 * on completions, for example if someone does a SIGSTOP on 3151 * a task that needs to finish task_work to make this loop 3152 * complete. That's a synthetic situation that should not 3153 * cause a stuck task backtrace, and hence a potential panic 3154 * on stuck tasks if that is enabled. 3155 */ 3156 } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval)); 3157 3158 init_completion(&exit.completion); 3159 init_task_work(&exit.task_work, io_tctx_exit_cb); 3160 exit.ctx = ctx; 3161 3162 mutex_lock(&ctx->uring_lock); 3163 while (!list_empty(&ctx->tctx_list)) { 3164 WARN_ON_ONCE(time_after(jiffies, timeout)); 3165 3166 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node, 3167 ctx_node); 3168 /* don't spin on a single task if cancellation failed */ 3169 list_rotate_left(&ctx->tctx_list); 3170 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL); 3171 if (WARN_ON_ONCE(ret)) 3172 continue; 3173 3174 mutex_unlock(&ctx->uring_lock); 3175 /* 3176 * See comment above for 3177 * wait_for_completion_interruptible_timeout() on why this 3178 * wait is marked as interruptible. 3179 */ 3180 wait_for_completion_interruptible(&exit.completion); 3181 mutex_lock(&ctx->uring_lock); 3182 } 3183 mutex_unlock(&ctx->uring_lock); 3184 spin_lock(&ctx->completion_lock); 3185 spin_unlock(&ctx->completion_lock); 3186 3187 /* pairs with RCU read section in io_req_local_work_add() */ 3188 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) 3189 synchronize_rcu(); 3190 3191 io_ring_ctx_free(ctx); 3192 } 3193 io_ring_ctx_wait_and_kill(struct io_ring_ctx * ctx)3194 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx) 3195 { 3196 unsigned long index; 3197 struct creds *creds; 3198 3199 mutex_lock(&ctx->uring_lock); 3200 percpu_ref_kill(&ctx->refs); 3201 xa_for_each(&ctx->personalities, index, creds) 3202 io_unregister_personality(ctx, index); 3203 if (ctx->rings) 3204 io_poll_remove_all(ctx, NULL, true); 3205 mutex_unlock(&ctx->uring_lock); 3206 3207 /* 3208 * If we failed setting up the ctx, we might not have any rings 3209 * and therefore did not submit any requests 3210 */ 3211 if (ctx->rings) 3212 io_kill_timeouts(ctx, NULL, true); 3213 3214 flush_delayed_work(&ctx->fallback_work); 3215 3216 INIT_WORK(&ctx->exit_work, io_ring_exit_work); 3217 /* 3218 * Use system_unbound_wq to avoid spawning tons of event kworkers 3219 * if we're exiting a ton of rings at the same time. It just adds 3220 * noise and overhead, there's no discernable change in runtime 3221 * over using system_wq. 3222 */ 3223 queue_work(iou_wq, &ctx->exit_work); 3224 } 3225 io_uring_release(struct inode * inode,struct file * file)3226 static int io_uring_release(struct inode *inode, struct file *file) 3227 { 3228 struct io_ring_ctx *ctx = file->private_data; 3229 3230 file->private_data = NULL; 3231 io_ring_ctx_wait_and_kill(ctx); 3232 return 0; 3233 } 3234 3235 struct io_task_cancel { 3236 struct task_struct *task; 3237 bool all; 3238 }; 3239 io_cancel_task_cb(struct io_wq_work * work,void * data)3240 static bool io_cancel_task_cb(struct io_wq_work *work, void *data) 3241 { 3242 struct io_kiocb *req = container_of(work, struct io_kiocb, work); 3243 struct io_task_cancel *cancel = data; 3244 3245 return io_match_task_safe(req, cancel->task, cancel->all); 3246 } 3247 io_cancel_defer_files(struct io_ring_ctx * ctx,struct task_struct * task,bool cancel_all)3248 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx, 3249 struct task_struct *task, 3250 bool cancel_all) 3251 { 3252 struct io_defer_entry *de; 3253 LIST_HEAD(list); 3254 3255 spin_lock(&ctx->completion_lock); 3256 list_for_each_entry_reverse(de, &ctx->defer_list, list) { 3257 if (io_match_task_safe(de->req, task, cancel_all)) { 3258 list_cut_position(&list, &ctx->defer_list, &de->list); 3259 break; 3260 } 3261 } 3262 spin_unlock(&ctx->completion_lock); 3263 if (list_empty(&list)) 3264 return false; 3265 3266 while (!list_empty(&list)) { 3267 de = list_first_entry(&list, struct io_defer_entry, list); 3268 list_del_init(&de->list); 3269 io_req_task_queue_fail(de->req, -ECANCELED); 3270 kfree(de); 3271 } 3272 return true; 3273 } 3274 io_uring_try_cancel_iowq(struct io_ring_ctx * ctx)3275 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx) 3276 { 3277 struct io_tctx_node *node; 3278 enum io_wq_cancel cret; 3279 bool ret = false; 3280 3281 mutex_lock(&ctx->uring_lock); 3282 list_for_each_entry(node, &ctx->tctx_list, ctx_node) { 3283 struct io_uring_task *tctx = node->task->io_uring; 3284 3285 /* 3286 * io_wq will stay alive while we hold uring_lock, because it's 3287 * killed after ctx nodes, which requires to take the lock. 3288 */ 3289 if (!tctx || !tctx->io_wq) 3290 continue; 3291 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true); 3292 ret |= (cret != IO_WQ_CANCEL_NOTFOUND); 3293 } 3294 mutex_unlock(&ctx->uring_lock); 3295 3296 return ret; 3297 } 3298 io_uring_try_cancel_requests(struct io_ring_ctx * ctx,struct task_struct * task,bool cancel_all)3299 static __cold bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx, 3300 struct task_struct *task, 3301 bool cancel_all) 3302 { 3303 struct io_task_cancel cancel = { .task = task, .all = cancel_all, }; 3304 struct io_uring_task *tctx = task ? task->io_uring : NULL; 3305 enum io_wq_cancel cret; 3306 bool ret = false; 3307 3308 /* set it so io_req_local_work_add() would wake us up */ 3309 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) { 3310 atomic_set(&ctx->cq_wait_nr, 1); 3311 smp_mb(); 3312 } 3313 3314 /* failed during ring init, it couldn't have issued any requests */ 3315 if (!ctx->rings) 3316 return false; 3317 3318 if (!task) { 3319 ret |= io_uring_try_cancel_iowq(ctx); 3320 } else if (tctx && tctx->io_wq) { 3321 /* 3322 * Cancels requests of all rings, not only @ctx, but 3323 * it's fine as the task is in exit/exec. 3324 */ 3325 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb, 3326 &cancel, true); 3327 ret |= (cret != IO_WQ_CANCEL_NOTFOUND); 3328 } 3329 3330 /* SQPOLL thread does its own polling */ 3331 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) || 3332 (ctx->sq_data && ctx->sq_data->thread == current)) { 3333 while (!wq_list_empty(&ctx->iopoll_list)) { 3334 io_iopoll_try_reap_events(ctx); 3335 ret = true; 3336 cond_resched(); 3337 } 3338 } 3339 3340 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) && 3341 io_allowed_defer_tw_run(ctx)) 3342 ret |= io_run_local_work(ctx, INT_MAX) > 0; 3343 ret |= io_cancel_defer_files(ctx, task, cancel_all); 3344 mutex_lock(&ctx->uring_lock); 3345 ret |= io_poll_remove_all(ctx, task, cancel_all); 3346 mutex_unlock(&ctx->uring_lock); 3347 ret |= io_kill_timeouts(ctx, task, cancel_all); 3348 if (task) 3349 ret |= io_run_task_work() > 0; 3350 return ret; 3351 } 3352 tctx_inflight(struct io_uring_task * tctx,bool tracked)3353 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked) 3354 { 3355 if (tracked) 3356 return atomic_read(&tctx->inflight_tracked); 3357 return percpu_counter_sum(&tctx->inflight); 3358 } 3359 3360 /* 3361 * Find any io_uring ctx that this task has registered or done IO on, and cancel 3362 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation. 3363 */ io_uring_cancel_generic(bool cancel_all,struct io_sq_data * sqd)3364 __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd) 3365 { 3366 struct io_uring_task *tctx = current->io_uring; 3367 struct io_ring_ctx *ctx; 3368 struct io_tctx_node *node; 3369 unsigned long index; 3370 s64 inflight; 3371 DEFINE_WAIT(wait); 3372 3373 WARN_ON_ONCE(sqd && sqd->thread != current); 3374 3375 if (!current->io_uring) 3376 return; 3377 if (tctx->io_wq) 3378 io_wq_exit_start(tctx->io_wq); 3379 3380 atomic_inc(&tctx->in_cancel); 3381 do { 3382 bool loop = false; 3383 3384 io_uring_drop_tctx_refs(current); 3385 if (!tctx_inflight(tctx, !cancel_all)) 3386 break; 3387 3388 /* read completions before cancelations */ 3389 inflight = tctx_inflight(tctx, false); 3390 if (!inflight) 3391 break; 3392 3393 if (!sqd) { 3394 xa_for_each(&tctx->xa, index, node) { 3395 /* sqpoll task will cancel all its requests */ 3396 if (node->ctx->sq_data) 3397 continue; 3398 loop |= io_uring_try_cancel_requests(node->ctx, 3399 current, cancel_all); 3400 } 3401 } else { 3402 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) 3403 loop |= io_uring_try_cancel_requests(ctx, 3404 current, 3405 cancel_all); 3406 } 3407 3408 if (loop) { 3409 cond_resched(); 3410 continue; 3411 } 3412 3413 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE); 3414 io_run_task_work(); 3415 io_uring_drop_tctx_refs(current); 3416 xa_for_each(&tctx->xa, index, node) { 3417 if (!llist_empty(&node->ctx->work_llist)) { 3418 WARN_ON_ONCE(node->ctx->submitter_task && 3419 node->ctx->submitter_task != current); 3420 goto end_wait; 3421 } 3422 } 3423 /* 3424 * If we've seen completions, retry without waiting. This 3425 * avoids a race where a completion comes in before we did 3426 * prepare_to_wait(). 3427 */ 3428 if (inflight == tctx_inflight(tctx, !cancel_all)) 3429 schedule(); 3430 end_wait: 3431 finish_wait(&tctx->wait, &wait); 3432 } while (1); 3433 3434 io_uring_clean_tctx(tctx); 3435 if (cancel_all) { 3436 /* 3437 * We shouldn't run task_works after cancel, so just leave 3438 * ->in_cancel set for normal exit. 3439 */ 3440 atomic_dec(&tctx->in_cancel); 3441 /* for exec all current's requests should be gone, kill tctx */ 3442 __io_uring_free(current); 3443 } 3444 } 3445 __io_uring_cancel(bool cancel_all)3446 void __io_uring_cancel(bool cancel_all) 3447 { 3448 io_uring_unreg_ringfd(); 3449 io_uring_cancel_generic(cancel_all, NULL); 3450 } 3451 io_uring_validate_mmap_request(struct file * file,loff_t pgoff,size_t sz)3452 static void *io_uring_validate_mmap_request(struct file *file, 3453 loff_t pgoff, size_t sz) 3454 { 3455 struct io_ring_ctx *ctx = file->private_data; 3456 loff_t offset = pgoff << PAGE_SHIFT; 3457 struct page *page; 3458 void *ptr; 3459 3460 switch (offset & IORING_OFF_MMAP_MASK) { 3461 case IORING_OFF_SQ_RING: 3462 case IORING_OFF_CQ_RING: 3463 /* Don't allow mmap if the ring was setup without it */ 3464 if (ctx->flags & IORING_SETUP_NO_MMAP) 3465 return ERR_PTR(-EINVAL); 3466 ptr = ctx->rings; 3467 break; 3468 case IORING_OFF_SQES: 3469 /* Don't allow mmap if the ring was setup without it */ 3470 if (ctx->flags & IORING_SETUP_NO_MMAP) 3471 return ERR_PTR(-EINVAL); 3472 ptr = ctx->sq_sqes; 3473 break; 3474 case IORING_OFF_PBUF_RING: { 3475 struct io_buffer_list *bl; 3476 unsigned int bgid; 3477 3478 bgid = (offset & ~IORING_OFF_MMAP_MASK) >> IORING_OFF_PBUF_SHIFT; 3479 bl = io_pbuf_get_bl(ctx, bgid); 3480 if (IS_ERR(bl)) 3481 return bl; 3482 ptr = bl->buf_ring; 3483 io_put_bl(ctx, bl); 3484 break; 3485 } 3486 default: 3487 return ERR_PTR(-EINVAL); 3488 } 3489 3490 page = virt_to_head_page(ptr); 3491 if (sz > page_size(page)) 3492 return ERR_PTR(-EINVAL); 3493 3494 return ptr; 3495 } 3496 3497 #ifdef CONFIG_MMU 3498 io_uring_mmap(struct file * file,struct vm_area_struct * vma)3499 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma) 3500 { 3501 size_t sz = vma->vm_end - vma->vm_start; 3502 unsigned long pfn; 3503 void *ptr; 3504 3505 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz); 3506 if (IS_ERR(ptr)) 3507 return PTR_ERR(ptr); 3508 3509 pfn = virt_to_phys(ptr) >> PAGE_SHIFT; 3510 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot); 3511 } 3512 io_uring_mmu_get_unmapped_area(struct file * filp,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)3513 static unsigned long io_uring_mmu_get_unmapped_area(struct file *filp, 3514 unsigned long addr, unsigned long len, 3515 unsigned long pgoff, unsigned long flags) 3516 { 3517 void *ptr; 3518 3519 /* 3520 * Do not allow to map to user-provided address to avoid breaking the 3521 * aliasing rules. Userspace is not able to guess the offset address of 3522 * kernel kmalloc()ed memory area. 3523 */ 3524 if (addr) 3525 return -EINVAL; 3526 3527 ptr = io_uring_validate_mmap_request(filp, pgoff, len); 3528 if (IS_ERR(ptr)) 3529 return -ENOMEM; 3530 3531 /* 3532 * Some architectures have strong cache aliasing requirements. 3533 * For such architectures we need a coherent mapping which aliases 3534 * kernel memory *and* userspace memory. To achieve that: 3535 * - use a NULL file pointer to reference physical memory, and 3536 * - use the kernel virtual address of the shared io_uring context 3537 * (instead of the userspace-provided address, which has to be 0UL 3538 * anyway). 3539 * - use the same pgoff which the get_unmapped_area() uses to 3540 * calculate the page colouring. 3541 * For architectures without such aliasing requirements, the 3542 * architecture will return any suitable mapping because addr is 0. 3543 */ 3544 filp = NULL; 3545 flags |= MAP_SHARED; 3546 pgoff = 0; /* has been translated to ptr above */ 3547 #ifdef SHM_COLOUR 3548 addr = (uintptr_t) ptr; 3549 pgoff = addr >> PAGE_SHIFT; 3550 #else 3551 addr = 0UL; 3552 #endif 3553 return current->mm->get_unmapped_area(filp, addr, len, pgoff, flags); 3554 } 3555 3556 #else /* !CONFIG_MMU */ 3557 io_uring_mmap(struct file * file,struct vm_area_struct * vma)3558 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma) 3559 { 3560 return is_nommu_shared_mapping(vma->vm_flags) ? 0 : -EINVAL; 3561 } 3562 io_uring_nommu_mmap_capabilities(struct file * file)3563 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file) 3564 { 3565 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE; 3566 } 3567 io_uring_nommu_get_unmapped_area(struct file * file,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)3568 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file, 3569 unsigned long addr, unsigned long len, 3570 unsigned long pgoff, unsigned long flags) 3571 { 3572 void *ptr; 3573 3574 ptr = io_uring_validate_mmap_request(file, pgoff, len); 3575 if (IS_ERR(ptr)) 3576 return PTR_ERR(ptr); 3577 3578 return (unsigned long) ptr; 3579 } 3580 3581 #endif /* !CONFIG_MMU */ 3582 io_validate_ext_arg(unsigned flags,const void __user * argp,size_t argsz)3583 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz) 3584 { 3585 if (flags & IORING_ENTER_EXT_ARG) { 3586 struct io_uring_getevents_arg arg; 3587 3588 if (argsz != sizeof(arg)) 3589 return -EINVAL; 3590 if (copy_from_user(&arg, argp, sizeof(arg))) 3591 return -EFAULT; 3592 } 3593 return 0; 3594 } 3595 io_get_ext_arg(unsigned flags,const void __user * argp,size_t * argsz,struct __kernel_timespec __user ** ts,const sigset_t __user ** sig)3596 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz, 3597 struct __kernel_timespec __user **ts, 3598 const sigset_t __user **sig) 3599 { 3600 struct io_uring_getevents_arg arg; 3601 3602 /* 3603 * If EXT_ARG isn't set, then we have no timespec and the argp pointer 3604 * is just a pointer to the sigset_t. 3605 */ 3606 if (!(flags & IORING_ENTER_EXT_ARG)) { 3607 *sig = (const sigset_t __user *) argp; 3608 *ts = NULL; 3609 return 0; 3610 } 3611 3612 /* 3613 * EXT_ARG is set - ensure we agree on the size of it and copy in our 3614 * timespec and sigset_t pointers if good. 3615 */ 3616 if (*argsz != sizeof(arg)) 3617 return -EINVAL; 3618 if (copy_from_user(&arg, argp, sizeof(arg))) 3619 return -EFAULT; 3620 if (arg.pad) 3621 return -EINVAL; 3622 *sig = u64_to_user_ptr(arg.sigmask); 3623 *argsz = arg.sigmask_sz; 3624 *ts = u64_to_user_ptr(arg.ts); 3625 return 0; 3626 } 3627 SYSCALL_DEFINE6(io_uring_enter,unsigned int,fd,u32,to_submit,u32,min_complete,u32,flags,const void __user *,argp,size_t,argsz)3628 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit, 3629 u32, min_complete, u32, flags, const void __user *, argp, 3630 size_t, argsz) 3631 { 3632 struct io_ring_ctx *ctx; 3633 struct file *file; 3634 long ret; 3635 3636 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP | 3637 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG | 3638 IORING_ENTER_REGISTERED_RING))) 3639 return -EINVAL; 3640 3641 /* 3642 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we 3643 * need only dereference our task private array to find it. 3644 */ 3645 if (flags & IORING_ENTER_REGISTERED_RING) { 3646 struct io_uring_task *tctx = current->io_uring; 3647 3648 if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX)) 3649 return -EINVAL; 3650 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX); 3651 file = tctx->registered_rings[fd]; 3652 if (unlikely(!file)) 3653 return -EBADF; 3654 } else { 3655 file = fget(fd); 3656 if (unlikely(!file)) 3657 return -EBADF; 3658 ret = -EOPNOTSUPP; 3659 if (unlikely(!io_is_uring_fops(file))) 3660 goto out; 3661 } 3662 3663 ctx = file->private_data; 3664 ret = -EBADFD; 3665 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED)) 3666 goto out; 3667 3668 /* 3669 * For SQ polling, the thread will do all submissions and completions. 3670 * Just return the requested submit count, and wake the thread if 3671 * we were asked to. 3672 */ 3673 ret = 0; 3674 if (ctx->flags & IORING_SETUP_SQPOLL) { 3675 io_cqring_overflow_flush(ctx); 3676 3677 if (unlikely(ctx->sq_data->thread == NULL)) { 3678 ret = -EOWNERDEAD; 3679 goto out; 3680 } 3681 if (flags & IORING_ENTER_SQ_WAKEUP) 3682 wake_up(&ctx->sq_data->wait); 3683 if (flags & IORING_ENTER_SQ_WAIT) 3684 io_sqpoll_wait_sq(ctx); 3685 3686 ret = to_submit; 3687 } else if (to_submit) { 3688 ret = io_uring_add_tctx_node(ctx); 3689 if (unlikely(ret)) 3690 goto out; 3691 3692 mutex_lock(&ctx->uring_lock); 3693 ret = io_submit_sqes(ctx, to_submit); 3694 if (ret != to_submit) { 3695 mutex_unlock(&ctx->uring_lock); 3696 goto out; 3697 } 3698 if (flags & IORING_ENTER_GETEVENTS) { 3699 if (ctx->syscall_iopoll) 3700 goto iopoll_locked; 3701 /* 3702 * Ignore errors, we'll soon call io_cqring_wait() and 3703 * it should handle ownership problems if any. 3704 */ 3705 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) 3706 (void)io_run_local_work_locked(ctx, min_complete); 3707 } 3708 mutex_unlock(&ctx->uring_lock); 3709 } 3710 3711 if (flags & IORING_ENTER_GETEVENTS) { 3712 int ret2; 3713 3714 if (ctx->syscall_iopoll) { 3715 /* 3716 * We disallow the app entering submit/complete with 3717 * polling, but we still need to lock the ring to 3718 * prevent racing with polled issue that got punted to 3719 * a workqueue. 3720 */ 3721 mutex_lock(&ctx->uring_lock); 3722 iopoll_locked: 3723 ret2 = io_validate_ext_arg(flags, argp, argsz); 3724 if (likely(!ret2)) { 3725 min_complete = min(min_complete, 3726 ctx->cq_entries); 3727 ret2 = io_iopoll_check(ctx, min_complete); 3728 } 3729 mutex_unlock(&ctx->uring_lock); 3730 } else { 3731 const sigset_t __user *sig; 3732 struct __kernel_timespec __user *ts; 3733 3734 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig); 3735 if (likely(!ret2)) { 3736 min_complete = min(min_complete, 3737 ctx->cq_entries); 3738 ret2 = io_cqring_wait(ctx, min_complete, sig, 3739 argsz, ts); 3740 } 3741 } 3742 3743 if (!ret) { 3744 ret = ret2; 3745 3746 /* 3747 * EBADR indicates that one or more CQE were dropped. 3748 * Once the user has been informed we can clear the bit 3749 * as they are obviously ok with those drops. 3750 */ 3751 if (unlikely(ret2 == -EBADR)) 3752 clear_bit(IO_CHECK_CQ_DROPPED_BIT, 3753 &ctx->check_cq); 3754 } 3755 } 3756 out: 3757 if (!(flags & IORING_ENTER_REGISTERED_RING)) 3758 fput(file); 3759 return ret; 3760 } 3761 3762 static const struct file_operations io_uring_fops = { 3763 .release = io_uring_release, 3764 .mmap = io_uring_mmap, 3765 #ifndef CONFIG_MMU 3766 .get_unmapped_area = io_uring_nommu_get_unmapped_area, 3767 .mmap_capabilities = io_uring_nommu_mmap_capabilities, 3768 #else 3769 .get_unmapped_area = io_uring_mmu_get_unmapped_area, 3770 #endif 3771 .poll = io_uring_poll, 3772 #ifdef CONFIG_PROC_FS 3773 .show_fdinfo = io_uring_show_fdinfo, 3774 #endif 3775 }; 3776 io_is_uring_fops(struct file * file)3777 bool io_is_uring_fops(struct file *file) 3778 { 3779 return file->f_op == &io_uring_fops; 3780 } 3781 io_allocate_scq_urings(struct io_ring_ctx * ctx,struct io_uring_params * p)3782 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx, 3783 struct io_uring_params *p) 3784 { 3785 struct io_rings *rings; 3786 size_t size, sq_array_offset; 3787 void *ptr; 3788 3789 /* make sure these are sane, as we already accounted them */ 3790 ctx->sq_entries = p->sq_entries; 3791 ctx->cq_entries = p->cq_entries; 3792 3793 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset); 3794 if (size == SIZE_MAX) 3795 return -EOVERFLOW; 3796 3797 if (!(ctx->flags & IORING_SETUP_NO_MMAP)) 3798 rings = io_mem_alloc(size); 3799 else 3800 rings = io_rings_map(ctx, p->cq_off.user_addr, size); 3801 3802 if (IS_ERR(rings)) 3803 return PTR_ERR(rings); 3804 3805 ctx->rings = rings; 3806 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY)) 3807 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset); 3808 rings->sq_ring_mask = p->sq_entries - 1; 3809 rings->cq_ring_mask = p->cq_entries - 1; 3810 rings->sq_ring_entries = p->sq_entries; 3811 rings->cq_ring_entries = p->cq_entries; 3812 3813 if (p->flags & IORING_SETUP_SQE128) 3814 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries); 3815 else 3816 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries); 3817 if (size == SIZE_MAX) { 3818 io_rings_free(ctx); 3819 return -EOVERFLOW; 3820 } 3821 3822 if (!(ctx->flags & IORING_SETUP_NO_MMAP)) 3823 ptr = io_mem_alloc(size); 3824 else 3825 ptr = io_sqes_map(ctx, p->sq_off.user_addr, size); 3826 3827 if (IS_ERR(ptr)) { 3828 io_rings_free(ctx); 3829 return PTR_ERR(ptr); 3830 } 3831 3832 ctx->sq_sqes = ptr; 3833 return 0; 3834 } 3835 io_uring_install_fd(struct file * file)3836 static int io_uring_install_fd(struct file *file) 3837 { 3838 int fd; 3839 3840 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC); 3841 if (fd < 0) 3842 return fd; 3843 fd_install(fd, file); 3844 return fd; 3845 } 3846 3847 /* 3848 * Allocate an anonymous fd, this is what constitutes the application 3849 * visible backing of an io_uring instance. The application mmaps this 3850 * fd to gain access to the SQ/CQ ring details. 3851 */ io_uring_get_file(struct io_ring_ctx * ctx)3852 static struct file *io_uring_get_file(struct io_ring_ctx *ctx) 3853 { 3854 return anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx, 3855 O_RDWR | O_CLOEXEC, NULL); 3856 } 3857 io_uring_create(unsigned entries,struct io_uring_params * p,struct io_uring_params __user * params)3858 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p, 3859 struct io_uring_params __user *params) 3860 { 3861 struct io_ring_ctx *ctx; 3862 struct io_uring_task *tctx; 3863 struct file *file; 3864 int ret; 3865 3866 if (!entries) 3867 return -EINVAL; 3868 if (entries > IORING_MAX_ENTRIES) { 3869 if (!(p->flags & IORING_SETUP_CLAMP)) 3870 return -EINVAL; 3871 entries = IORING_MAX_ENTRIES; 3872 } 3873 3874 if ((p->flags & IORING_SETUP_REGISTERED_FD_ONLY) 3875 && !(p->flags & IORING_SETUP_NO_MMAP)) 3876 return -EINVAL; 3877 3878 /* 3879 * Use twice as many entries for the CQ ring. It's possible for the 3880 * application to drive a higher depth than the size of the SQ ring, 3881 * since the sqes are only used at submission time. This allows for 3882 * some flexibility in overcommitting a bit. If the application has 3883 * set IORING_SETUP_CQSIZE, it will have passed in the desired number 3884 * of CQ ring entries manually. 3885 */ 3886 p->sq_entries = roundup_pow_of_two(entries); 3887 if (p->flags & IORING_SETUP_CQSIZE) { 3888 /* 3889 * If IORING_SETUP_CQSIZE is set, we do the same roundup 3890 * to a power-of-two, if it isn't already. We do NOT impose 3891 * any cq vs sq ring sizing. 3892 */ 3893 if (!p->cq_entries) 3894 return -EINVAL; 3895 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) { 3896 if (!(p->flags & IORING_SETUP_CLAMP)) 3897 return -EINVAL; 3898 p->cq_entries = IORING_MAX_CQ_ENTRIES; 3899 } 3900 p->cq_entries = roundup_pow_of_two(p->cq_entries); 3901 if (p->cq_entries < p->sq_entries) 3902 return -EINVAL; 3903 } else { 3904 p->cq_entries = 2 * p->sq_entries; 3905 } 3906 3907 ctx = io_ring_ctx_alloc(p); 3908 if (!ctx) 3909 return -ENOMEM; 3910 3911 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) && 3912 !(ctx->flags & IORING_SETUP_IOPOLL) && 3913 !(ctx->flags & IORING_SETUP_SQPOLL)) 3914 ctx->task_complete = true; 3915 3916 if (ctx->task_complete || (ctx->flags & IORING_SETUP_IOPOLL)) 3917 ctx->lockless_cq = true; 3918 3919 /* 3920 * lazy poll_wq activation relies on ->task_complete for synchronisation 3921 * purposes, see io_activate_pollwq() 3922 */ 3923 if (!ctx->task_complete) 3924 ctx->poll_activated = true; 3925 3926 /* 3927 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user 3928 * space applications don't need to do io completion events 3929 * polling again, they can rely on io_sq_thread to do polling 3930 * work, which can reduce cpu usage and uring_lock contention. 3931 */ 3932 if (ctx->flags & IORING_SETUP_IOPOLL && 3933 !(ctx->flags & IORING_SETUP_SQPOLL)) 3934 ctx->syscall_iopoll = 1; 3935 3936 ctx->compat = in_compat_syscall(); 3937 if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK)) 3938 ctx->user = get_uid(current_user()); 3939 3940 /* 3941 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if 3942 * COOP_TASKRUN is set, then IPIs are never needed by the app. 3943 */ 3944 ret = -EINVAL; 3945 if (ctx->flags & IORING_SETUP_SQPOLL) { 3946 /* IPI related flags don't make sense with SQPOLL */ 3947 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN | 3948 IORING_SETUP_TASKRUN_FLAG | 3949 IORING_SETUP_DEFER_TASKRUN)) 3950 goto err; 3951 ctx->notify_method = TWA_SIGNAL_NO_IPI; 3952 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) { 3953 ctx->notify_method = TWA_SIGNAL_NO_IPI; 3954 } else { 3955 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG && 3956 !(ctx->flags & IORING_SETUP_DEFER_TASKRUN)) 3957 goto err; 3958 ctx->notify_method = TWA_SIGNAL; 3959 } 3960 3961 /* 3962 * For DEFER_TASKRUN we require the completion task to be the same as the 3963 * submission task. This implies that there is only one submitter, so enforce 3964 * that. 3965 */ 3966 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN && 3967 !(ctx->flags & IORING_SETUP_SINGLE_ISSUER)) { 3968 goto err; 3969 } 3970 3971 /* 3972 * This is just grabbed for accounting purposes. When a process exits, 3973 * the mm is exited and dropped before the files, hence we need to hang 3974 * on to this mm purely for the purposes of being able to unaccount 3975 * memory (locked/pinned vm). It's not used for anything else. 3976 */ 3977 mmgrab(current->mm); 3978 ctx->mm_account = current->mm; 3979 3980 ret = io_allocate_scq_urings(ctx, p); 3981 if (ret) 3982 goto err; 3983 3984 ret = io_sq_offload_create(ctx, p); 3985 if (ret) 3986 goto err; 3987 3988 ret = io_rsrc_init(ctx); 3989 if (ret) 3990 goto err; 3991 3992 p->sq_off.head = offsetof(struct io_rings, sq.head); 3993 p->sq_off.tail = offsetof(struct io_rings, sq.tail); 3994 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask); 3995 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries); 3996 p->sq_off.flags = offsetof(struct io_rings, sq_flags); 3997 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped); 3998 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY)) 3999 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings; 4000 p->sq_off.resv1 = 0; 4001 if (!(ctx->flags & IORING_SETUP_NO_MMAP)) 4002 p->sq_off.user_addr = 0; 4003 4004 p->cq_off.head = offsetof(struct io_rings, cq.head); 4005 p->cq_off.tail = offsetof(struct io_rings, cq.tail); 4006 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask); 4007 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries); 4008 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow); 4009 p->cq_off.cqes = offsetof(struct io_rings, cqes); 4010 p->cq_off.flags = offsetof(struct io_rings, cq_flags); 4011 p->cq_off.resv1 = 0; 4012 if (!(ctx->flags & IORING_SETUP_NO_MMAP)) 4013 p->cq_off.user_addr = 0; 4014 4015 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP | 4016 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS | 4017 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL | 4018 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED | 4019 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS | 4020 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP | 4021 IORING_FEAT_LINKED_FILE | IORING_FEAT_REG_REG_RING; 4022 4023 if (copy_to_user(params, p, sizeof(*p))) { 4024 ret = -EFAULT; 4025 goto err; 4026 } 4027 4028 if (ctx->flags & IORING_SETUP_SINGLE_ISSUER 4029 && !(ctx->flags & IORING_SETUP_R_DISABLED)) 4030 WRITE_ONCE(ctx->submitter_task, get_task_struct(current)); 4031 4032 file = io_uring_get_file(ctx); 4033 if (IS_ERR(file)) { 4034 ret = PTR_ERR(file); 4035 goto err; 4036 } 4037 4038 ret = __io_uring_add_tctx_node(ctx); 4039 if (ret) 4040 goto err_fput; 4041 tctx = current->io_uring; 4042 4043 /* 4044 * Install ring fd as the very last thing, so we don't risk someone 4045 * having closed it before we finish setup 4046 */ 4047 if (p->flags & IORING_SETUP_REGISTERED_FD_ONLY) 4048 ret = io_ring_add_registered_file(tctx, file, 0, IO_RINGFD_REG_MAX); 4049 else 4050 ret = io_uring_install_fd(file); 4051 if (ret < 0) 4052 goto err_fput; 4053 4054 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags); 4055 return ret; 4056 err: 4057 io_ring_ctx_wait_and_kill(ctx); 4058 return ret; 4059 err_fput: 4060 fput(file); 4061 return ret; 4062 } 4063 4064 /* 4065 * Sets up an aio uring context, and returns the fd. Applications asks for a 4066 * ring size, we return the actual sq/cq ring sizes (among other things) in the 4067 * params structure passed in. 4068 */ io_uring_setup(u32 entries,struct io_uring_params __user * params)4069 static long io_uring_setup(u32 entries, struct io_uring_params __user *params) 4070 { 4071 struct io_uring_params p; 4072 int i; 4073 4074 if (copy_from_user(&p, params, sizeof(p))) 4075 return -EFAULT; 4076 for (i = 0; i < ARRAY_SIZE(p.resv); i++) { 4077 if (p.resv[i]) 4078 return -EINVAL; 4079 } 4080 4081 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL | 4082 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE | 4083 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ | 4084 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL | 4085 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG | 4086 IORING_SETUP_SQE128 | IORING_SETUP_CQE32 | 4087 IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN | 4088 IORING_SETUP_NO_MMAP | IORING_SETUP_REGISTERED_FD_ONLY | 4089 IORING_SETUP_NO_SQARRAY)) 4090 return -EINVAL; 4091 4092 return io_uring_create(entries, &p, params); 4093 } 4094 io_uring_allowed(void)4095 static inline bool io_uring_allowed(void) 4096 { 4097 int disabled = READ_ONCE(sysctl_io_uring_disabled); 4098 kgid_t io_uring_group; 4099 4100 if (disabled == 2) 4101 return false; 4102 4103 if (disabled == 0 || capable(CAP_SYS_ADMIN)) 4104 return true; 4105 4106 io_uring_group = make_kgid(&init_user_ns, sysctl_io_uring_group); 4107 if (!gid_valid(io_uring_group)) 4108 return false; 4109 4110 return in_group_p(io_uring_group); 4111 } 4112 SYSCALL_DEFINE2(io_uring_setup,u32,entries,struct io_uring_params __user *,params)4113 SYSCALL_DEFINE2(io_uring_setup, u32, entries, 4114 struct io_uring_params __user *, params) 4115 { 4116 if (!io_uring_allowed()) 4117 return -EPERM; 4118 4119 return io_uring_setup(entries, params); 4120 } 4121 io_probe(struct io_ring_ctx * ctx,void __user * arg,unsigned nr_args)4122 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg, 4123 unsigned nr_args) 4124 { 4125 struct io_uring_probe *p; 4126 size_t size; 4127 int i, ret; 4128 4129 size = struct_size(p, ops, nr_args); 4130 if (size == SIZE_MAX) 4131 return -EOVERFLOW; 4132 p = kzalloc(size, GFP_KERNEL); 4133 if (!p) 4134 return -ENOMEM; 4135 4136 ret = -EFAULT; 4137 if (copy_from_user(p, arg, size)) 4138 goto out; 4139 ret = -EINVAL; 4140 if (memchr_inv(p, 0, size)) 4141 goto out; 4142 4143 p->last_op = IORING_OP_LAST - 1; 4144 if (nr_args > IORING_OP_LAST) 4145 nr_args = IORING_OP_LAST; 4146 4147 for (i = 0; i < nr_args; i++) { 4148 p->ops[i].op = i; 4149 if (!io_issue_defs[i].not_supported) 4150 p->ops[i].flags = IO_URING_OP_SUPPORTED; 4151 } 4152 p->ops_len = i; 4153 4154 ret = 0; 4155 if (copy_to_user(arg, p, size)) 4156 ret = -EFAULT; 4157 out: 4158 kfree(p); 4159 return ret; 4160 } 4161 io_register_personality(struct io_ring_ctx * ctx)4162 static int io_register_personality(struct io_ring_ctx *ctx) 4163 { 4164 const struct cred *creds; 4165 u32 id; 4166 int ret; 4167 4168 creds = get_current_cred(); 4169 4170 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds, 4171 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL); 4172 if (ret < 0) { 4173 put_cred(creds); 4174 return ret; 4175 } 4176 return id; 4177 } 4178 io_register_restrictions(struct io_ring_ctx * ctx,void __user * arg,unsigned int nr_args)4179 static __cold int io_register_restrictions(struct io_ring_ctx *ctx, 4180 void __user *arg, unsigned int nr_args) 4181 { 4182 struct io_uring_restriction *res; 4183 size_t size; 4184 int i, ret; 4185 4186 /* Restrictions allowed only if rings started disabled */ 4187 if (!(ctx->flags & IORING_SETUP_R_DISABLED)) 4188 return -EBADFD; 4189 4190 /* We allow only a single restrictions registration */ 4191 if (ctx->restrictions.registered) 4192 return -EBUSY; 4193 4194 if (!arg || nr_args > IORING_MAX_RESTRICTIONS) 4195 return -EINVAL; 4196 4197 size = array_size(nr_args, sizeof(*res)); 4198 if (size == SIZE_MAX) 4199 return -EOVERFLOW; 4200 4201 res = memdup_user(arg, size); 4202 if (IS_ERR(res)) 4203 return PTR_ERR(res); 4204 4205 ret = 0; 4206 4207 for (i = 0; i < nr_args; i++) { 4208 switch (res[i].opcode) { 4209 case IORING_RESTRICTION_REGISTER_OP: 4210 if (res[i].register_op >= IORING_REGISTER_LAST) { 4211 ret = -EINVAL; 4212 goto out; 4213 } 4214 4215 __set_bit(res[i].register_op, 4216 ctx->restrictions.register_op); 4217 break; 4218 case IORING_RESTRICTION_SQE_OP: 4219 if (res[i].sqe_op >= IORING_OP_LAST) { 4220 ret = -EINVAL; 4221 goto out; 4222 } 4223 4224 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op); 4225 break; 4226 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED: 4227 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags; 4228 break; 4229 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED: 4230 ctx->restrictions.sqe_flags_required = res[i].sqe_flags; 4231 break; 4232 default: 4233 ret = -EINVAL; 4234 goto out; 4235 } 4236 } 4237 4238 out: 4239 /* Reset all restrictions if an error happened */ 4240 if (ret != 0) 4241 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions)); 4242 else 4243 ctx->restrictions.registered = true; 4244 4245 kfree(res); 4246 return ret; 4247 } 4248 io_register_enable_rings(struct io_ring_ctx * ctx)4249 static int io_register_enable_rings(struct io_ring_ctx *ctx) 4250 { 4251 if (!(ctx->flags & IORING_SETUP_R_DISABLED)) 4252 return -EBADFD; 4253 4254 if (ctx->flags & IORING_SETUP_SINGLE_ISSUER && !ctx->submitter_task) { 4255 WRITE_ONCE(ctx->submitter_task, get_task_struct(current)); 4256 /* 4257 * Lazy activation attempts would fail if it was polled before 4258 * submitter_task is set. 4259 */ 4260 if (wq_has_sleeper(&ctx->poll_wq)) 4261 io_activate_pollwq(ctx); 4262 } 4263 4264 if (ctx->restrictions.registered) 4265 ctx->restricted = 1; 4266 4267 ctx->flags &= ~IORING_SETUP_R_DISABLED; 4268 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait)) 4269 wake_up(&ctx->sq_data->wait); 4270 return 0; 4271 } 4272 __io_register_iowq_aff(struct io_ring_ctx * ctx,cpumask_var_t new_mask)4273 static __cold int __io_register_iowq_aff(struct io_ring_ctx *ctx, 4274 cpumask_var_t new_mask) 4275 { 4276 int ret; 4277 4278 if (!(ctx->flags & IORING_SETUP_SQPOLL)) { 4279 ret = io_wq_cpu_affinity(current->io_uring, new_mask); 4280 } else { 4281 mutex_unlock(&ctx->uring_lock); 4282 ret = io_sqpoll_wq_cpu_affinity(ctx, new_mask); 4283 mutex_lock(&ctx->uring_lock); 4284 } 4285 4286 return ret; 4287 } 4288 io_register_iowq_aff(struct io_ring_ctx * ctx,void __user * arg,unsigned len)4289 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx, 4290 void __user *arg, unsigned len) 4291 { 4292 cpumask_var_t new_mask; 4293 int ret; 4294 4295 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) 4296 return -ENOMEM; 4297 4298 cpumask_clear(new_mask); 4299 if (len > cpumask_size()) 4300 len = cpumask_size(); 4301 4302 if (in_compat_syscall()) { 4303 ret = compat_get_bitmap(cpumask_bits(new_mask), 4304 (const compat_ulong_t __user *)arg, 4305 len * 8 /* CHAR_BIT */); 4306 } else { 4307 ret = copy_from_user(new_mask, arg, len); 4308 } 4309 4310 if (ret) { 4311 free_cpumask_var(new_mask); 4312 return -EFAULT; 4313 } 4314 4315 ret = __io_register_iowq_aff(ctx, new_mask); 4316 free_cpumask_var(new_mask); 4317 return ret; 4318 } 4319 io_unregister_iowq_aff(struct io_ring_ctx * ctx)4320 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx) 4321 { 4322 return __io_register_iowq_aff(ctx, NULL); 4323 } 4324 io_register_iowq_max_workers(struct io_ring_ctx * ctx,void __user * arg)4325 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx, 4326 void __user *arg) 4327 __must_hold(&ctx->uring_lock) 4328 { 4329 struct io_tctx_node *node; 4330 struct io_uring_task *tctx = NULL; 4331 struct io_sq_data *sqd = NULL; 4332 __u32 new_count[2]; 4333 int i, ret; 4334 4335 if (copy_from_user(new_count, arg, sizeof(new_count))) 4336 return -EFAULT; 4337 for (i = 0; i < ARRAY_SIZE(new_count); i++) 4338 if (new_count[i] > INT_MAX) 4339 return -EINVAL; 4340 4341 if (ctx->flags & IORING_SETUP_SQPOLL) { 4342 sqd = ctx->sq_data; 4343 if (sqd) { 4344 /* 4345 * Observe the correct sqd->lock -> ctx->uring_lock 4346 * ordering. Fine to drop uring_lock here, we hold 4347 * a ref to the ctx. 4348 */ 4349 refcount_inc(&sqd->refs); 4350 mutex_unlock(&ctx->uring_lock); 4351 mutex_lock(&sqd->lock); 4352 mutex_lock(&ctx->uring_lock); 4353 if (sqd->thread) 4354 tctx = sqd->thread->io_uring; 4355 } 4356 } else { 4357 tctx = current->io_uring; 4358 } 4359 4360 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits)); 4361 4362 for (i = 0; i < ARRAY_SIZE(new_count); i++) 4363 if (new_count[i]) 4364 ctx->iowq_limits[i] = new_count[i]; 4365 ctx->iowq_limits_set = true; 4366 4367 if (tctx && tctx->io_wq) { 4368 ret = io_wq_max_workers(tctx->io_wq, new_count); 4369 if (ret) 4370 goto err; 4371 } else { 4372 memset(new_count, 0, sizeof(new_count)); 4373 } 4374 4375 if (sqd) { 4376 mutex_unlock(&ctx->uring_lock); 4377 mutex_unlock(&sqd->lock); 4378 io_put_sq_data(sqd); 4379 mutex_lock(&ctx->uring_lock); 4380 } 4381 4382 if (copy_to_user(arg, new_count, sizeof(new_count))) 4383 return -EFAULT; 4384 4385 /* that's it for SQPOLL, only the SQPOLL task creates requests */ 4386 if (sqd) 4387 return 0; 4388 4389 /* now propagate the restriction to all registered users */ 4390 list_for_each_entry(node, &ctx->tctx_list, ctx_node) { 4391 struct io_uring_task *tctx = node->task->io_uring; 4392 4393 if (WARN_ON_ONCE(!tctx->io_wq)) 4394 continue; 4395 4396 for (i = 0; i < ARRAY_SIZE(new_count); i++) 4397 new_count[i] = ctx->iowq_limits[i]; 4398 /* ignore errors, it always returns zero anyway */ 4399 (void)io_wq_max_workers(tctx->io_wq, new_count); 4400 } 4401 return 0; 4402 err: 4403 if (sqd) { 4404 mutex_unlock(&ctx->uring_lock); 4405 mutex_unlock(&sqd->lock); 4406 io_put_sq_data(sqd); 4407 mutex_lock(&ctx->uring_lock); 4408 4409 } 4410 return ret; 4411 } 4412 __io_uring_register(struct io_ring_ctx * ctx,unsigned opcode,void __user * arg,unsigned nr_args)4413 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode, 4414 void __user *arg, unsigned nr_args) 4415 __releases(ctx->uring_lock) 4416 __acquires(ctx->uring_lock) 4417 { 4418 int ret; 4419 4420 /* 4421 * We don't quiesce the refs for register anymore and so it can't be 4422 * dying as we're holding a file ref here. 4423 */ 4424 if (WARN_ON_ONCE(percpu_ref_is_dying(&ctx->refs))) 4425 return -ENXIO; 4426 4427 if (ctx->submitter_task && ctx->submitter_task != current) 4428 return -EEXIST; 4429 4430 if (ctx->restricted) { 4431 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST); 4432 if (!test_bit(opcode, ctx->restrictions.register_op)) 4433 return -EACCES; 4434 } 4435 4436 switch (opcode) { 4437 case IORING_REGISTER_BUFFERS: 4438 ret = -EFAULT; 4439 if (!arg) 4440 break; 4441 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL); 4442 break; 4443 case IORING_UNREGISTER_BUFFERS: 4444 ret = -EINVAL; 4445 if (arg || nr_args) 4446 break; 4447 ret = io_sqe_buffers_unregister(ctx); 4448 break; 4449 case IORING_REGISTER_FILES: 4450 ret = -EFAULT; 4451 if (!arg) 4452 break; 4453 ret = io_sqe_files_register(ctx, arg, nr_args, NULL); 4454 break; 4455 case IORING_UNREGISTER_FILES: 4456 ret = -EINVAL; 4457 if (arg || nr_args) 4458 break; 4459 ret = io_sqe_files_unregister(ctx); 4460 break; 4461 case IORING_REGISTER_FILES_UPDATE: 4462 ret = io_register_files_update(ctx, arg, nr_args); 4463 break; 4464 case IORING_REGISTER_EVENTFD: 4465 ret = -EINVAL; 4466 if (nr_args != 1) 4467 break; 4468 ret = io_eventfd_register(ctx, arg, 0); 4469 break; 4470 case IORING_REGISTER_EVENTFD_ASYNC: 4471 ret = -EINVAL; 4472 if (nr_args != 1) 4473 break; 4474 ret = io_eventfd_register(ctx, arg, 1); 4475 break; 4476 case IORING_UNREGISTER_EVENTFD: 4477 ret = -EINVAL; 4478 if (arg || nr_args) 4479 break; 4480 ret = io_eventfd_unregister(ctx); 4481 break; 4482 case IORING_REGISTER_PROBE: 4483 ret = -EINVAL; 4484 if (!arg || nr_args > 256) 4485 break; 4486 ret = io_probe(ctx, arg, nr_args); 4487 break; 4488 case IORING_REGISTER_PERSONALITY: 4489 ret = -EINVAL; 4490 if (arg || nr_args) 4491 break; 4492 ret = io_register_personality(ctx); 4493 break; 4494 case IORING_UNREGISTER_PERSONALITY: 4495 ret = -EINVAL; 4496 if (arg) 4497 break; 4498 ret = io_unregister_personality(ctx, nr_args); 4499 break; 4500 case IORING_REGISTER_ENABLE_RINGS: 4501 ret = -EINVAL; 4502 if (arg || nr_args) 4503 break; 4504 ret = io_register_enable_rings(ctx); 4505 break; 4506 case IORING_REGISTER_RESTRICTIONS: 4507 ret = io_register_restrictions(ctx, arg, nr_args); 4508 break; 4509 case IORING_REGISTER_FILES2: 4510 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE); 4511 break; 4512 case IORING_REGISTER_FILES_UPDATE2: 4513 ret = io_register_rsrc_update(ctx, arg, nr_args, 4514 IORING_RSRC_FILE); 4515 break; 4516 case IORING_REGISTER_BUFFERS2: 4517 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER); 4518 break; 4519 case IORING_REGISTER_BUFFERS_UPDATE: 4520 ret = io_register_rsrc_update(ctx, arg, nr_args, 4521 IORING_RSRC_BUFFER); 4522 break; 4523 case IORING_REGISTER_IOWQ_AFF: 4524 ret = -EINVAL; 4525 if (!arg || !nr_args) 4526 break; 4527 ret = io_register_iowq_aff(ctx, arg, nr_args); 4528 break; 4529 case IORING_UNREGISTER_IOWQ_AFF: 4530 ret = -EINVAL; 4531 if (arg || nr_args) 4532 break; 4533 ret = io_unregister_iowq_aff(ctx); 4534 break; 4535 case IORING_REGISTER_IOWQ_MAX_WORKERS: 4536 ret = -EINVAL; 4537 if (!arg || nr_args != 2) 4538 break; 4539 ret = io_register_iowq_max_workers(ctx, arg); 4540 break; 4541 case IORING_REGISTER_RING_FDS: 4542 ret = io_ringfd_register(ctx, arg, nr_args); 4543 break; 4544 case IORING_UNREGISTER_RING_FDS: 4545 ret = io_ringfd_unregister(ctx, arg, nr_args); 4546 break; 4547 case IORING_REGISTER_PBUF_RING: 4548 ret = -EINVAL; 4549 if (!arg || nr_args != 1) 4550 break; 4551 ret = io_register_pbuf_ring(ctx, arg); 4552 break; 4553 case IORING_UNREGISTER_PBUF_RING: 4554 ret = -EINVAL; 4555 if (!arg || nr_args != 1) 4556 break; 4557 ret = io_unregister_pbuf_ring(ctx, arg); 4558 break; 4559 case IORING_REGISTER_SYNC_CANCEL: 4560 ret = -EINVAL; 4561 if (!arg || nr_args != 1) 4562 break; 4563 ret = io_sync_cancel(ctx, arg); 4564 break; 4565 case IORING_REGISTER_FILE_ALLOC_RANGE: 4566 ret = -EINVAL; 4567 if (!arg || nr_args) 4568 break; 4569 ret = io_register_file_alloc_range(ctx, arg); 4570 break; 4571 default: 4572 ret = -EINVAL; 4573 break; 4574 } 4575 4576 return ret; 4577 } 4578 SYSCALL_DEFINE4(io_uring_register,unsigned int,fd,unsigned int,opcode,void __user *,arg,unsigned int,nr_args)4579 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode, 4580 void __user *, arg, unsigned int, nr_args) 4581 { 4582 struct io_ring_ctx *ctx; 4583 long ret = -EBADF; 4584 struct file *file; 4585 bool use_registered_ring; 4586 4587 use_registered_ring = !!(opcode & IORING_REGISTER_USE_REGISTERED_RING); 4588 opcode &= ~IORING_REGISTER_USE_REGISTERED_RING; 4589 4590 if (opcode >= IORING_REGISTER_LAST) 4591 return -EINVAL; 4592 4593 if (use_registered_ring) { 4594 /* 4595 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we 4596 * need only dereference our task private array to find it. 4597 */ 4598 struct io_uring_task *tctx = current->io_uring; 4599 4600 if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX)) 4601 return -EINVAL; 4602 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX); 4603 file = tctx->registered_rings[fd]; 4604 if (unlikely(!file)) 4605 return -EBADF; 4606 } else { 4607 file = fget(fd); 4608 if (unlikely(!file)) 4609 return -EBADF; 4610 ret = -EOPNOTSUPP; 4611 if (!io_is_uring_fops(file)) 4612 goto out_fput; 4613 } 4614 4615 ctx = file->private_data; 4616 4617 mutex_lock(&ctx->uring_lock); 4618 ret = __io_uring_register(ctx, opcode, arg, nr_args); 4619 mutex_unlock(&ctx->uring_lock); 4620 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret); 4621 out_fput: 4622 if (!use_registered_ring) 4623 fput(file); 4624 return ret; 4625 } 4626 io_uring_init(void)4627 static int __init io_uring_init(void) 4628 { 4629 #define __BUILD_BUG_VERIFY_OFFSET_SIZE(stype, eoffset, esize, ename) do { \ 4630 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \ 4631 BUILD_BUG_ON(sizeof_field(stype, ename) != esize); \ 4632 } while (0) 4633 4634 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \ 4635 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, sizeof(etype), ename) 4636 #define BUILD_BUG_SQE_ELEM_SIZE(eoffset, esize, ename) \ 4637 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, esize, ename) 4638 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64); 4639 BUILD_BUG_SQE_ELEM(0, __u8, opcode); 4640 BUILD_BUG_SQE_ELEM(1, __u8, flags); 4641 BUILD_BUG_SQE_ELEM(2, __u16, ioprio); 4642 BUILD_BUG_SQE_ELEM(4, __s32, fd); 4643 BUILD_BUG_SQE_ELEM(8, __u64, off); 4644 BUILD_BUG_SQE_ELEM(8, __u64, addr2); 4645 BUILD_BUG_SQE_ELEM(8, __u32, cmd_op); 4646 BUILD_BUG_SQE_ELEM(12, __u32, __pad1); 4647 BUILD_BUG_SQE_ELEM(16, __u64, addr); 4648 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in); 4649 BUILD_BUG_SQE_ELEM(24, __u32, len); 4650 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags); 4651 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags); 4652 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags); 4653 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags); 4654 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events); 4655 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events); 4656 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags); 4657 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags); 4658 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags); 4659 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags); 4660 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags); 4661 BUILD_BUG_SQE_ELEM(28, __u32, open_flags); 4662 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags); 4663 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice); 4664 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags); 4665 BUILD_BUG_SQE_ELEM(28, __u32, rename_flags); 4666 BUILD_BUG_SQE_ELEM(28, __u32, unlink_flags); 4667 BUILD_BUG_SQE_ELEM(28, __u32, hardlink_flags); 4668 BUILD_BUG_SQE_ELEM(28, __u32, xattr_flags); 4669 BUILD_BUG_SQE_ELEM(28, __u32, msg_ring_flags); 4670 BUILD_BUG_SQE_ELEM(32, __u64, user_data); 4671 BUILD_BUG_SQE_ELEM(40, __u16, buf_index); 4672 BUILD_BUG_SQE_ELEM(40, __u16, buf_group); 4673 BUILD_BUG_SQE_ELEM(42, __u16, personality); 4674 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in); 4675 BUILD_BUG_SQE_ELEM(44, __u32, file_index); 4676 BUILD_BUG_SQE_ELEM(44, __u16, addr_len); 4677 BUILD_BUG_SQE_ELEM(46, __u16, __pad3[0]); 4678 BUILD_BUG_SQE_ELEM(48, __u64, addr3); 4679 BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd); 4680 BUILD_BUG_SQE_ELEM(56, __u64, __pad2); 4681 4682 BUILD_BUG_ON(sizeof(struct io_uring_files_update) != 4683 sizeof(struct io_uring_rsrc_update)); 4684 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) > 4685 sizeof(struct io_uring_rsrc_update2)); 4686 4687 /* ->buf_index is u16 */ 4688 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0); 4689 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) != 4690 offsetof(struct io_uring_buf_ring, tail)); 4691 4692 /* should fit into one byte */ 4693 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8)); 4694 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8)); 4695 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS); 4696 4697 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int)); 4698 4699 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32)); 4700 4701 io_uring_optable_init(); 4702 4703 /* 4704 * Allow user copy in the per-command field, which starts after the 4705 * file in io_kiocb and until the opcode field. The openat2 handling 4706 * requires copying in user memory into the io_kiocb object in that 4707 * range, and HARDENED_USERCOPY will complain if we haven't 4708 * correctly annotated this range. 4709 */ 4710 req_cachep = kmem_cache_create_usercopy("io_kiocb", 4711 sizeof(struct io_kiocb), 0, 4712 SLAB_HWCACHE_ALIGN | SLAB_PANIC | 4713 SLAB_ACCOUNT | SLAB_TYPESAFE_BY_RCU, 4714 offsetof(struct io_kiocb, cmd.data), 4715 sizeof_field(struct io_kiocb, cmd.data), NULL); 4716 4717 iou_wq = alloc_workqueue("iou_exit", WQ_UNBOUND, 64); 4718 4719 #ifdef CONFIG_SYSCTL 4720 register_sysctl_init("kernel", kernel_io_uring_disabled_table); 4721 #endif 4722 4723 return 0; 4724 }; 4725 __initcall(io_uring_init); 4726