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.org/pub/scm/linux/kernel/git/axboe/liburing.git 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/errno.h> 44 #include <linux/syscalls.h> 45 #include <linux/refcount.h> 46 #include <linux/bits.h> 47 48 #include <linux/sched/signal.h> 49 #include <linux/fs.h> 50 #include <linux/mm.h> 51 #include <linux/percpu.h> 52 #include <linux/slab.h> 53 #include <linux/anon_inodes.h> 54 #include <linux/uaccess.h> 55 #include <linux/nospec.h> 56 #include <linux/task_work.h> 57 #include <linux/io_uring.h> 58 #include <linux/io_uring/cmd.h> 59 #include <linux/audit.h> 60 #include <linux/security.h> 61 #include <linux/jump_label.h> 62 #include <linux/kcov.h> 63 64 #define CREATE_TRACE_POINTS 65 #include <trace/events/io_uring.h> 66 67 #include <uapi/linux/io_uring.h> 68 69 #include "io-wq.h" 70 71 #include "filetable.h" 72 #include "io_uring.h" 73 #include "opdef.h" 74 #include "refs.h" 75 #include "tctx.h" 76 #include "register.h" 77 #include "sqpoll.h" 78 #include "fdinfo.h" 79 #include "kbuf.h" 80 #include "rsrc.h" 81 #include "cancel.h" 82 #include "net.h" 83 #include "notif.h" 84 #include "waitid.h" 85 #include "futex.h" 86 #include "napi.h" 87 #include "uring_cmd.h" 88 #include "msg_ring.h" 89 #include "memmap.h" 90 #include "zcrx.h" 91 #include "bpf-ops.h" 92 93 #include "timeout.h" 94 #include "poll.h" 95 #include "rw.h" 96 #include "alloc_cache.h" 97 #include "eventfd.h" 98 #include "wait.h" 99 #include "bpf_filter.h" 100 #include "loop.h" 101 102 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \ 103 IOSQE_IO_HARDLINK | IOSQE_ASYNC) 104 105 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK) 106 107 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \ 108 REQ_F_INFLIGHT | REQ_F_CREDS | REQ_F_ASYNC_DATA) 109 110 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | IO_REQ_LINK_FLAGS | \ 111 REQ_F_REISSUE | REQ_F_POLLED | \ 112 IO_REQ_CLEAN_FLAGS) 113 114 #define IO_TCTX_REFS_CACHE_NR (1U << 10) 115 116 #define IO_COMPL_BATCH 32 117 #define IO_REQ_ALLOC_BATCH 8 118 119 /* requests with any of those set should undergo io_disarm_next() */ 120 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL) 121 122 static void io_queue_sqe(struct io_kiocb *req, unsigned int extra_flags); 123 static void __io_req_caches_free(struct io_ring_ctx *ctx); 124 125 static __read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(io_key_has_sqarray, HZ); 126 127 struct kmem_cache *req_cachep; 128 static struct workqueue_struct *iou_wq __ro_after_init; 129 130 static int __read_mostly sysctl_io_uring_disabled; 131 static int __read_mostly sysctl_io_uring_group = -1; 132 133 #ifdef CONFIG_SYSCTL 134 static const struct ctl_table kernel_io_uring_disabled_table[] = { 135 { 136 .procname = "io_uring_disabled", 137 .data = &sysctl_io_uring_disabled, 138 .maxlen = sizeof(sysctl_io_uring_disabled), 139 .mode = 0644, 140 .proc_handler = proc_dointvec_minmax, 141 .extra1 = SYSCTL_ZERO, 142 .extra2 = SYSCTL_TWO, 143 }, 144 { 145 .procname = "io_uring_group", 146 .data = &sysctl_io_uring_group, 147 .maxlen = sizeof(gid_t), 148 .mode = 0644, 149 .proc_handler = proc_dointvec, 150 }, 151 }; 152 #endif 153 154 static void io_poison_cached_req(struct io_kiocb *req) 155 { 156 req->ctx = IO_URING_PTR_POISON; 157 req->tctx = IO_URING_PTR_POISON; 158 req->file = IO_URING_PTR_POISON; 159 req->creds = IO_URING_PTR_POISON; 160 req->io_task_work.func = IO_URING_PTR_POISON; 161 req->apoll = IO_URING_PTR_POISON; 162 } 163 164 void io_poison_req(struct io_kiocb *req) 165 { 166 io_poison_cached_req(req); 167 req->async_data = IO_URING_PTR_POISON; 168 req->kbuf = IO_URING_PTR_POISON; 169 req->comp_list.next = IO_URING_PTR_POISON; 170 req->file_node = IO_URING_PTR_POISON; 171 req->link = IO_URING_PTR_POISON; 172 } 173 174 static inline void req_fail_link_node(struct io_kiocb *req, int res) 175 { 176 req_set_fail(req); 177 io_req_set_res(req, res, 0); 178 } 179 180 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx) 181 { 182 if (IS_ENABLED(CONFIG_KASAN)) 183 io_poison_cached_req(req); 184 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list); 185 } 186 187 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref) 188 { 189 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs); 190 191 complete(&ctx->ref_comp); 192 } 193 194 static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits) 195 { 196 unsigned int hash_buckets; 197 int i; 198 199 do { 200 hash_buckets = 1U << bits; 201 table->hbs = kvmalloc_objs(table->hbs[0], hash_buckets, 202 GFP_KERNEL_ACCOUNT); 203 if (table->hbs) 204 break; 205 if (bits == 1) 206 return -ENOMEM; 207 bits--; 208 } while (1); 209 210 table->hash_bits = bits; 211 for (i = 0; i < hash_buckets; i++) 212 INIT_HLIST_HEAD(&table->hbs[i].list); 213 return 0; 214 } 215 216 static void io_free_alloc_caches(struct io_ring_ctx *ctx) 217 { 218 io_alloc_cache_free(&ctx->apoll_cache, kfree); 219 io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free); 220 io_alloc_cache_free(&ctx->rw_cache, io_rw_cache_free); 221 io_alloc_cache_free(&ctx->cmd_cache, io_cmd_cache_free); 222 io_futex_cache_free(ctx); 223 io_rsrc_cache_free(ctx); 224 } 225 226 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p) 227 { 228 struct io_ring_ctx *ctx; 229 int hash_bits; 230 bool ret; 231 232 ctx = kzalloc_obj(*ctx); 233 if (!ctx) 234 return NULL; 235 236 xa_init(&ctx->io_bl_xa); 237 xa_init(&ctx->hpage_acct); 238 239 /* 240 * Use 5 bits less than the max cq entries, that should give us around 241 * 32 entries per hash list if totally full and uniformly spread, but 242 * don't keep too many buckets to not overconsume memory. 243 */ 244 hash_bits = ilog2(p->cq_entries) - 5; 245 hash_bits = clamp(hash_bits, 1, 8); 246 if (io_alloc_hash_table(&ctx->cancel_table, hash_bits)) 247 goto err; 248 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free, 249 0, GFP_KERNEL)) 250 goto err; 251 252 ctx->flags = p->flags; 253 ctx->hybrid_poll_time = LLONG_MAX; 254 atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT); 255 init_waitqueue_head(&ctx->sqo_sq_wait); 256 INIT_LIST_HEAD(&ctx->sqd_list); 257 INIT_LIST_HEAD(&ctx->cq_overflow_list); 258 ret = io_alloc_cache_init(&ctx->apoll_cache, IO_POLL_ALLOC_CACHE_MAX, 259 sizeof(struct async_poll), 0); 260 ret |= io_alloc_cache_init(&ctx->netmsg_cache, IO_ALLOC_CACHE_MAX, 261 sizeof(struct io_async_msghdr), 262 offsetof(struct io_async_msghdr, clear)); 263 ret |= io_alloc_cache_init(&ctx->rw_cache, IO_ALLOC_CACHE_MAX, 264 sizeof(struct io_async_rw), 265 offsetof(struct io_async_rw, clear)); 266 ret |= io_alloc_cache_init(&ctx->cmd_cache, IO_ALLOC_CACHE_MAX, 267 sizeof(struct io_async_cmd), 268 sizeof(struct io_async_cmd)); 269 ret |= io_futex_cache_init(ctx); 270 ret |= io_rsrc_cache_init(ctx); 271 if (ret) 272 goto free_ref; 273 init_completion(&ctx->ref_comp); 274 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1); 275 mutex_init(&ctx->uring_lock); 276 init_waitqueue_head(&ctx->cq_wait); 277 init_waitqueue_head(&ctx->poll_wq); 278 spin_lock_init(&ctx->completion_lock); 279 raw_spin_lock_init(&ctx->timeout_lock); 280 INIT_LIST_HEAD(&ctx->iopoll_list); 281 INIT_LIST_HEAD(&ctx->defer_list); 282 INIT_LIST_HEAD(&ctx->timeout_list); 283 INIT_LIST_HEAD(&ctx->ltimeout_list); 284 mpscq_init(&ctx->work_list, &ctx->work_head); 285 INIT_LIST_HEAD(&ctx->tctx_list); 286 mutex_init(&ctx->tctx_lock); 287 ctx->submit_state.free_list.next = NULL; 288 INIT_HLIST_HEAD(&ctx->waitid_list); 289 xa_init_flags(&ctx->zcrx_ctxs, XA_FLAGS_ALLOC); 290 #ifdef CONFIG_FUTEX 291 INIT_HLIST_HEAD(&ctx->futex_list); 292 #endif 293 INIT_WQ_LIST(&ctx->submit_state.compl_reqs); 294 INIT_HLIST_HEAD(&ctx->cancelable_uring_cmd); 295 io_napi_init(ctx); 296 mutex_init(&ctx->mmap_lock); 297 ctx->kcov_handle = kcov_common_handle(); 298 299 return ctx; 300 301 free_ref: 302 percpu_ref_exit(&ctx->refs); 303 err: 304 io_free_alloc_caches(ctx); 305 kvfree(ctx->cancel_table.hbs); 306 xa_destroy(&ctx->io_bl_xa); 307 xa_destroy(&ctx->hpage_acct); 308 kfree(ctx); 309 return NULL; 310 } 311 312 static void io_clean_op(struct io_kiocb *req) 313 { 314 if (unlikely(req->flags & REQ_F_BUFFER_SELECTED)) 315 io_kbuf_drop_legacy(req); 316 317 if (req->flags & REQ_F_NEED_CLEANUP) { 318 const struct io_cold_def *def = &io_cold_defs[req->opcode]; 319 320 if (def->cleanup) 321 def->cleanup(req); 322 } 323 if (req->flags & REQ_F_INFLIGHT) 324 atomic_dec(&req->tctx->inflight_tracked); 325 if (req->flags & REQ_F_CREDS) 326 put_cred(req->creds); 327 if (req->flags & REQ_F_ASYNC_DATA) { 328 kfree(req->async_data); 329 req->async_data = NULL; 330 } 331 req->flags &= ~IO_REQ_CLEAN_FLAGS; 332 } 333 334 /* 335 * Mark the request as inflight, so that file cancelation will find it. 336 * Can be used if the file is an io_uring instance, or if the request itself 337 * relies on ->mm being alive for the duration of the request. 338 */ 339 inline void io_req_track_inflight(struct io_kiocb *req) 340 { 341 if (!(req->flags & REQ_F_INFLIGHT)) { 342 req->flags |= REQ_F_INFLIGHT; 343 atomic_inc(&req->tctx->inflight_tracked); 344 } 345 } 346 347 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req) 348 { 349 if (WARN_ON_ONCE(!req->link)) 350 return NULL; 351 352 req->flags &= ~REQ_F_ARM_LTIMEOUT; 353 req->flags |= REQ_F_LINK_TIMEOUT; 354 355 /* linked timeouts should have two refs once prep'ed */ 356 io_req_set_refcount(req); 357 __io_req_set_refcount(req->link, 2); 358 return req->link; 359 } 360 361 static void io_prep_async_work(struct io_kiocb *req) 362 { 363 const struct io_issue_def *def = &io_issue_defs[req->opcode]; 364 365 if (!(req->flags & REQ_F_CREDS)) { 366 req->flags |= REQ_F_CREDS; 367 req->creds = get_current_cred(); 368 } 369 370 req->work.list.next = NULL; 371 atomic_set(&req->work.flags, 0); 372 if (req->flags & REQ_F_FORCE_ASYNC) 373 atomic_or(IO_WQ_WORK_CONCURRENT, &req->work.flags); 374 375 if (req->file && !(req->flags & REQ_F_FIXED_FILE)) 376 req->flags |= io_file_get_flags(req->file); 377 378 if (req->file && (req->flags & REQ_F_ISREG)) { 379 bool should_hash = def->hash_reg_file; 380 381 /* don't serialize this request if the fs doesn't need it */ 382 if (should_hash && (req->file->f_flags & O_DIRECT) && 383 (req->file->f_op->fop_flags & FOP_DIO_PARALLEL_WRITE)) 384 should_hash = false; 385 if (should_hash || (req->flags & REQ_F_IOPOLL)) 386 io_wq_hash_work(&req->work, file_inode(req->file)); 387 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) { 388 if (def->unbound_nonreg_file) 389 atomic_or(IO_WQ_WORK_UNBOUND, &req->work.flags); 390 } 391 } 392 393 static void io_prep_async_link(struct io_kiocb *req) 394 { 395 struct io_kiocb *cur; 396 397 if (req->flags & REQ_F_LINK_TIMEOUT) { 398 struct io_ring_ctx *ctx = req->ctx; 399 400 raw_spin_lock_irq(&ctx->timeout_lock); 401 io_for_each_link(cur, req) 402 io_prep_async_work(cur); 403 raw_spin_unlock_irq(&ctx->timeout_lock); 404 } else { 405 io_for_each_link(cur, req) 406 io_prep_async_work(cur); 407 } 408 } 409 410 /* Called for every request that is issued: keep it inline */ 411 static __always_inline bool io_assign_file(struct io_kiocb *req, 412 const struct io_issue_def *def, 413 unsigned int issue_flags) 414 { 415 if (req->file || !def->needs_file) 416 return true; 417 418 if (req->flags & REQ_F_FIXED_FILE) 419 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags); 420 else 421 req->file = io_file_get_normal(req, req->cqe.fd); 422 423 return !!req->file; 424 } 425 426 void io_queue_iowq(struct io_kiocb *req) 427 { 428 struct io_uring_task *tctx = req->tctx; 429 430 BUG_ON(!tctx); 431 lockdep_assert_held(&req->ctx->uring_lock); 432 433 if ((current->flags & PF_KTHREAD) || !tctx->io_wq) { 434 io_req_task_queue_fail(req, -ECANCELED); 435 return; 436 } 437 438 /* 439 * The file is looked up as late as possible, as it may be the result 440 * of an earlier request of the link. This one is up now, and what kind 441 * of work it is depends on the file. If that fails, leave the error 442 * handling to the worker. 443 * 444 * Not for a splice: whatever it writes to, it may wait for its input 445 * for ever. It has to remain unbound work that isn't hashed. 446 */ 447 if (req->opcode != IORING_OP_SPLICE) 448 io_assign_file(req, &io_issue_defs[req->opcode], 0); 449 450 /* init ->work of the whole link before punting */ 451 io_prep_async_link(req); 452 453 /* 454 * Not expected to happen, but if we do have a bug where this _can_ 455 * happen, catch it here and ensure the request is marked as 456 * canceled. That will make io-wq go through the usual work cancel 457 * procedure rather than attempt to run this request (or create a new 458 * worker for it). 459 */ 460 if (WARN_ON_ONCE(!same_thread_group(tctx->task, current))) 461 atomic_or(IO_WQ_WORK_CANCEL, &req->work.flags); 462 463 trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work)); 464 io_wq_enqueue(tctx->io_wq, &req->work); 465 } 466 467 unsigned io_linked_nr(struct io_kiocb *req) 468 { 469 struct io_kiocb *tmp; 470 unsigned nr = 0; 471 472 io_for_each_link(tmp, req) 473 nr++; 474 return nr; 475 } 476 477 static __cold noinline void io_queue_deferred(struct io_ring_ctx *ctx) 478 { 479 bool drain_seen = false, first = true; 480 481 lockdep_assert_held(&ctx->uring_lock); 482 __io_req_caches_free(ctx); 483 /* nothing outside of ->defer_list is alive */ 484 if (ctx->nr_req_allocated == ctx->nr_drained) 485 ctx->drain_req = NULL; 486 487 while (!list_empty(&ctx->defer_list)) { 488 struct io_defer_entry *de = list_first_entry(&ctx->defer_list, 489 struct io_defer_entry, list); 490 491 drain_seen |= de->req->flags & REQ_F_IO_DRAIN; 492 if ((drain_seen || first) && ctx->nr_req_allocated != ctx->nr_drained) 493 return; 494 495 list_del_init(&de->list); 496 ctx->nr_drained -= io_linked_nr(de->req); 497 /* it runs alone, track its completion unless it's a link */ 498 if ((de->req->flags & REQ_F_IO_DRAIN) && !de->req->link) 499 ctx->drain_req = de->req; 500 io_req_task_queue(de->req); 501 kfree(de); 502 first = false; 503 } 504 } 505 506 void __io_commit_cqring_flush(struct io_ring_ctx *ctx) 507 { 508 if (ctx->int_flags & IO_RING_F_POLL_ACTIVATED) 509 io_poll_wq_wake(ctx); 510 if (ctx->int_flags & IO_RING_F_OFF_TIMEOUT_USED) 511 io_flush_timeouts(ctx); 512 if (ctx->int_flags & IO_RING_F_HAS_EVFD) 513 io_eventfd_signal(ctx, true, false); 514 } 515 516 static inline void __io_cq_lock(struct io_ring_ctx *ctx) 517 { 518 if (!(ctx->int_flags & IO_RING_F_LOCKLESS_CQ)) 519 spin_lock(&ctx->completion_lock); 520 } 521 522 static inline void io_cq_lock(struct io_ring_ctx *ctx) 523 __acquires(ctx->completion_lock) 524 { 525 spin_lock(&ctx->completion_lock); 526 } 527 528 static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx) 529 { 530 io_commit_cqring(ctx); 531 if (!(ctx->int_flags & IO_RING_F_TASK_COMPLETE)) { 532 if (!(ctx->int_flags & IO_RING_F_LOCKLESS_CQ)) 533 spin_unlock(&ctx->completion_lock); 534 /* IOPOLL rings only need to wake up if it's also SQPOLL */ 535 if (!(ctx->int_flags & IO_RING_F_SYSCALL_IOPOLL)) 536 io_cqring_wake(ctx); 537 } 538 io_commit_cqring_flush(ctx); 539 } 540 541 static void io_cq_unlock_post(struct io_ring_ctx *ctx) 542 __releases(ctx->completion_lock) 543 { 544 io_commit_cqring(ctx); 545 spin_unlock(&ctx->completion_lock); 546 io_cqring_wake(ctx); 547 io_commit_cqring_flush(ctx); 548 } 549 550 static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool dying) 551 { 552 lockdep_assert_held(&ctx->uring_lock); 553 554 /* don't abort if we're dying, entries must get freed */ 555 if (!dying && __io_cqring_events(ctx) == ctx->cq_entries) 556 return; 557 558 io_cq_lock(ctx); 559 while (!list_empty(&ctx->cq_overflow_list)) { 560 size_t cqe_size = sizeof(struct io_uring_cqe); 561 struct io_uring_cqe *cqe; 562 struct io_overflow_cqe *ocqe; 563 bool is_cqe32 = false; 564 565 ocqe = list_first_entry(&ctx->cq_overflow_list, 566 struct io_overflow_cqe, list); 567 if (ocqe->cqe.flags & IORING_CQE_F_32 || 568 ctx->flags & IORING_SETUP_CQE32) { 569 is_cqe32 = true; 570 cqe_size <<= 1; 571 } 572 if (ctx->flags & IORING_SETUP_CQE32) 573 is_cqe32 = false; 574 575 if (!dying) { 576 if (!io_get_cqe_overflow(ctx, &cqe, true, is_cqe32)) 577 break; 578 memcpy(cqe, &ocqe->cqe, cqe_size); 579 } 580 list_del(&ocqe->list); 581 kfree(ocqe); 582 583 /* 584 * For silly syzbot cases that deliberately overflow by huge 585 * amounts, check if we need to resched and drop and 586 * reacquire the locks if so. Nothing real would ever hit this. 587 * Ideally we'd have a non-posting unlock for this, but hard 588 * to care for a non-real case. 589 */ 590 if (need_resched()) { 591 ctx->cqe_sentinel = ctx->cqe_cached; 592 io_cq_unlock_post(ctx); 593 mutex_unlock(&ctx->uring_lock); 594 cond_resched(); 595 mutex_lock(&ctx->uring_lock); 596 io_cq_lock(ctx); 597 } 598 } 599 600 if (list_empty(&ctx->cq_overflow_list)) { 601 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq); 602 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags); 603 } 604 io_cq_unlock_post(ctx); 605 } 606 607 static void io_cqring_overflow_kill(struct io_ring_ctx *ctx) 608 { 609 if (ctx->rings) 610 __io_cqring_overflow_flush(ctx, true); 611 } 612 613 void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx) 614 { 615 mutex_lock(&ctx->uring_lock); 616 __io_cqring_overflow_flush(ctx, false); 617 mutex_unlock(&ctx->uring_lock); 618 } 619 620 void io_cqring_overflow_flush_locked(struct io_ring_ctx *ctx) 621 { 622 __io_cqring_overflow_flush(ctx, false); 623 } 624 625 /* must to be called somewhat shortly after putting a request */ 626 static inline void io_put_task(struct io_kiocb *req) 627 { 628 struct io_uring_task *tctx = req->tctx; 629 630 if (likely(tctx->task == current)) { 631 tctx->cached_refs++; 632 } else { 633 percpu_counter_sub(&tctx->inflight, 1); 634 if (unlikely(atomic_read(&tctx->in_cancel))) 635 wake_up(&tctx->wait); 636 put_task_struct(tctx->task); 637 } 638 } 639 640 void io_task_refs_refill(struct io_uring_task *tctx) 641 { 642 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR; 643 644 percpu_counter_add(&tctx->inflight, refill); 645 refcount_add(refill, ¤t->usage); 646 tctx->cached_refs += refill; 647 } 648 649 __cold void io_uring_drop_tctx_refs(struct task_struct *task) 650 { 651 struct io_uring_task *tctx = task->io_uring; 652 unsigned int refs = tctx->cached_refs; 653 654 if (refs) { 655 tctx->cached_refs = 0; 656 percpu_counter_sub(&tctx->inflight, refs); 657 put_task_struct_many(task, refs); 658 } 659 } 660 661 static __cold bool io_cqring_add_overflow(struct io_ring_ctx *ctx, 662 struct io_overflow_cqe *ocqe) 663 { 664 lockdep_assert_held(&ctx->completion_lock); 665 666 if (!ocqe) { 667 struct io_rings *r = ctx->rings; 668 669 /* 670 * If we're in ring overflow flush mode, or in task cancel mode, 671 * or cannot allocate an overflow entry, then we need to drop it 672 * on the floor. 673 */ 674 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1); 675 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq); 676 return false; 677 } 678 if (list_empty(&ctx->cq_overflow_list)) { 679 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq); 680 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags); 681 682 } 683 list_add_tail(&ocqe->list, &ctx->cq_overflow_list); 684 return true; 685 } 686 687 static struct io_overflow_cqe *io_alloc_ocqe(struct io_ring_ctx *ctx, 688 struct io_cqe *cqe, 689 struct io_big_cqe *big_cqe, gfp_t gfp) 690 { 691 struct io_overflow_cqe *ocqe; 692 size_t ocq_size = sizeof(struct io_overflow_cqe); 693 bool is_cqe32 = false; 694 695 if (cqe->flags & IORING_CQE_F_32 || ctx->flags & IORING_SETUP_CQE32) { 696 is_cqe32 = true; 697 ocq_size += sizeof(struct io_uring_cqe); 698 } 699 700 ocqe = kzalloc(ocq_size, gfp | __GFP_ACCOUNT); 701 trace_io_uring_cqe_overflow(ctx, cqe->user_data, cqe->res, cqe->flags, ocqe); 702 if (ocqe) { 703 ocqe->cqe.user_data = cqe->user_data; 704 ocqe->cqe.res = cqe->res; 705 ocqe->cqe.flags = cqe->flags; 706 if (is_cqe32 && big_cqe) { 707 ocqe->cqe.big_cqe[0] = big_cqe->extra1; 708 ocqe->cqe.big_cqe[1] = big_cqe->extra2; 709 } 710 } 711 if (big_cqe) 712 big_cqe->extra1 = big_cqe->extra2 = 0; 713 return ocqe; 714 } 715 716 /* 717 * Compute queued CQEs for free-space calculation, clamped to cq_entries. 718 */ 719 static unsigned int io_cqring_queued(struct io_ring_ctx *ctx) 720 { 721 struct io_rings *rings = io_get_rings(ctx); 722 int diff; 723 724 diff = (int)(ctx->cached_cq_tail - READ_ONCE(rings->cq.head)); 725 if (diff >= 0) 726 return min((unsigned int)diff, ctx->cq_entries); 727 return 0; 728 } 729 730 /* 731 * Fill an empty dummy CQE, in case alignment is off for posting a 32b CQE 732 * because the ring is a single 16b entry away from wrapping. 733 */ 734 static bool io_fill_nop_cqe(struct io_ring_ctx *ctx, unsigned int off) 735 { 736 if (io_cqring_queued(ctx) < ctx->cq_entries) { 737 struct io_uring_cqe *cqe = &ctx->rings->cqes[off]; 738 739 cqe->user_data = 0; 740 cqe->res = 0; 741 cqe->flags = IORING_CQE_F_SKIP; 742 ctx->cached_cq_tail++; 743 return true; 744 } 745 return false; 746 } 747 748 /* 749 * writes to the cq entry need to come after reading head; the 750 * control dependency is enough as we're using WRITE_ONCE to 751 * fill the cq entry 752 */ 753 bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow, bool cqe32) 754 { 755 struct io_rings *rings = ctx->rings; 756 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1); 757 unsigned int free, len; 758 759 /* 760 * Posting into the CQ when there are pending overflowed CQEs may break 761 * ordering guarantees, which will affect links, F_MORE users and more. 762 * Force overflow the completion. 763 */ 764 if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))) 765 return false; 766 767 /* 768 * A single entry may be left if a 32b CQE is asked for. It must not be 769 * handed out later on if this fails, as the CQE is going to overflow. 770 */ 771 ctx->cqe_cached = NULL; 772 ctx->cqe_sentinel = NULL; 773 774 /* 775 * Post dummy CQE if a 32b CQE is needed and there's only room for a 776 * 16b CQE before the ring wraps. 777 */ 778 if (cqe32 && (ctx->flags & IORING_SETUP_CQE_MIXED) && 779 off + 1 == ctx->cq_entries) { 780 /* one for the dummy CQE, two for the 32b CQE itself */ 781 if (ctx->cq_entries - io_cqring_queued(ctx) < 3) 782 return false; 783 if (!io_fill_nop_cqe(ctx, off)) 784 return false; 785 off = 0; 786 } 787 788 free = ctx->cq_entries - io_cqring_queued(ctx); 789 /* we need a contiguous range, limit based on the current array offset */ 790 len = min(free, ctx->cq_entries - off); 791 if (ctx->flags & IORING_SETUP_CQE32) { 792 if (!len) 793 return false; 794 off <<= 1; 795 len <<= 1; 796 } else if (len < (cqe32 + 1)) { 797 return false; 798 } 799 800 ctx->cqe_cached = &rings->cqes[off]; 801 ctx->cqe_sentinel = ctx->cqe_cached + len; 802 return true; 803 } 804 805 static bool io_fill_cqe_aux32(struct io_ring_ctx *ctx, 806 struct io_uring_cqe src_cqe[2]) 807 { 808 struct io_uring_cqe *cqe; 809 810 if (WARN_ON_ONCE(!(ctx->flags & (IORING_SETUP_CQE32|IORING_SETUP_CQE_MIXED)))) 811 return false; 812 if (unlikely(!io_get_cqe(ctx, &cqe, true))) 813 return false; 814 815 memcpy(cqe, src_cqe, 2 * sizeof(*cqe)); 816 trace_io_uring_complete(ctx, NULL, cqe); 817 return true; 818 } 819 820 static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res, 821 u32 cflags) 822 { 823 bool cqe32 = cflags & IORING_CQE_F_32; 824 struct io_uring_cqe *cqe; 825 826 if (likely(io_get_cqe(ctx, &cqe, cqe32))) { 827 WRITE_ONCE(cqe->user_data, user_data); 828 WRITE_ONCE(cqe->res, res); 829 WRITE_ONCE(cqe->flags, cflags); 830 831 if (cqe32 || (ctx->flags & IORING_SETUP_CQE32)) { 832 WRITE_ONCE(cqe->big_cqe[0], 0); 833 WRITE_ONCE(cqe->big_cqe[1], 0); 834 } 835 836 trace_io_uring_complete(ctx, NULL, cqe); 837 return true; 838 } 839 return false; 840 } 841 842 static inline struct io_cqe io_init_cqe(u64 user_data, s32 res, u32 cflags) 843 { 844 return (struct io_cqe) { .user_data = user_data, .res = res, .flags = cflags }; 845 } 846 847 static __cold void io_cqe_overflow(struct io_ring_ctx *ctx, struct io_cqe *cqe, 848 struct io_big_cqe *big_cqe) 849 { 850 struct io_overflow_cqe *ocqe; 851 852 ocqe = io_alloc_ocqe(ctx, cqe, big_cqe, GFP_KERNEL); 853 spin_lock(&ctx->completion_lock); 854 io_cqring_add_overflow(ctx, ocqe); 855 spin_unlock(&ctx->completion_lock); 856 } 857 858 static __cold bool io_cqe_overflow_locked(struct io_ring_ctx *ctx, 859 struct io_cqe *cqe, 860 struct io_big_cqe *big_cqe) 861 { 862 struct io_overflow_cqe *ocqe; 863 864 ocqe = io_alloc_ocqe(ctx, cqe, big_cqe, GFP_NOWAIT); 865 return io_cqring_add_overflow(ctx, ocqe); 866 } 867 868 bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags) 869 { 870 bool filled; 871 872 io_cq_lock(ctx); 873 filled = io_fill_cqe_aux(ctx, user_data, res, cflags); 874 if (unlikely(!filled)) { 875 struct io_cqe cqe = io_init_cqe(user_data, res, cflags); 876 877 filled = io_cqe_overflow_locked(ctx, &cqe, NULL); 878 } 879 io_cq_unlock_post(ctx); 880 return filled; 881 } 882 883 /* 884 * Must be called from inline task_work so we know a flush will happen later, 885 * and obviously with ctx->uring_lock held (tw always has that). 886 */ 887 void io_add_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags) 888 { 889 lockdep_assert_held(&ctx->uring_lock); 890 lockdep_assert(ctx->int_flags & IO_RING_F_LOCKLESS_CQ); 891 892 if (!io_fill_cqe_aux(ctx, user_data, res, cflags)) { 893 struct io_cqe cqe = io_init_cqe(user_data, res, cflags); 894 895 io_cqe_overflow(ctx, &cqe, NULL); 896 } 897 ctx->submit_state.cq_flush = true; 898 } 899 900 /* 901 * A helper for multishot requests posting additional CQEs. 902 * Should only be used from a task_work including IO_URING_F_MULTISHOT. 903 */ 904 bool io_req_post_cqe(struct io_kiocb *req, s32 res, u32 cflags) 905 { 906 struct io_ring_ctx *ctx = req->ctx; 907 bool posted; 908 909 /* 910 * If multishot has already posted deferred completions, ensure that 911 * those are flushed first before posting this one. If not, CQEs 912 * could get reordered. 913 */ 914 if (!wq_list_empty(&ctx->submit_state.compl_reqs)) 915 __io_submit_flush_completions(ctx); 916 917 lockdep_assert(!io_wq_current_is_worker()); 918 lockdep_assert_held(&ctx->uring_lock); 919 920 if (!(ctx->int_flags & IO_RING_F_LOCKLESS_CQ)) { 921 spin_lock(&ctx->completion_lock); 922 posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags); 923 spin_unlock(&ctx->completion_lock); 924 } else { 925 posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags); 926 } 927 928 ctx->submit_state.cq_flush = true; 929 return posted; 930 } 931 932 /* 933 * A helper for multishot requests posting additional CQEs. 934 * Should only be used from a task_work including IO_URING_F_MULTISHOT. 935 */ 936 bool io_req_post_cqe32(struct io_kiocb *req, struct io_uring_cqe cqe[2]) 937 { 938 struct io_ring_ctx *ctx = req->ctx; 939 bool posted; 940 941 lockdep_assert(!io_wq_current_is_worker()); 942 lockdep_assert_held(&ctx->uring_lock); 943 944 cqe[0].user_data = req->cqe.user_data; 945 if (!(ctx->int_flags & IO_RING_F_LOCKLESS_CQ)) { 946 spin_lock(&ctx->completion_lock); 947 posted = io_fill_cqe_aux32(ctx, cqe); 948 spin_unlock(&ctx->completion_lock); 949 } else { 950 posted = io_fill_cqe_aux32(ctx, cqe); 951 } 952 953 ctx->submit_state.cq_flush = true; 954 return posted; 955 } 956 957 /* drop the request file before the CQE is posted, not deferred after it */ 958 static void io_req_put_file(struct io_kiocb *req, bool sync) 959 { 960 struct file *file = req->file; 961 962 if (!file || (req->flags & (REQ_F_FIXED_FILE | REQ_F_REISSUE))) 963 return; 964 965 WRITE_ONCE(req->file, NULL); 966 /* releasing a ring may wait on other rings, keep that deferred */ 967 if (sync && !io_is_uring_fops(file)) 968 __fput_sync(file); 969 else 970 fput(file); 971 } 972 973 static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags) 974 { 975 struct io_ring_ctx *ctx = req->ctx; 976 bool completed = true; 977 978 /* 979 * All execution paths but io-wq use the deferred completions by 980 * passing IO_URING_F_COMPLETE_DEFER and thus should not end up here. 981 */ 982 if (WARN_ON_ONCE(!(issue_flags & IO_URING_F_IOWQ))) 983 return; 984 985 io_req_put_file(req, true); 986 987 /* 988 * Handle special CQ sync cases via task_work. DEFER_TASKRUN requires 989 * the submitter task context, IOPOLL protects with uring_lock. A drain 990 * request ends the drain under uring_lock as its CQE is posted. 991 */ 992 if ((ctx->int_flags & IO_RING_F_LOCKLESS_CQ) || 993 (req->flags & (REQ_F_REISSUE | REQ_F_IO_DRAIN))) { 994 defer_complete: 995 req->io_task_work.func = io_req_task_complete; 996 io_req_task_work_add(req); 997 return; 998 } 999 1000 io_cq_lock(ctx); 1001 if (!(req->flags & REQ_F_CQE_SKIP)) 1002 completed = io_fill_cqe_req(ctx, req); 1003 io_cq_unlock_post(ctx); 1004 1005 if (!completed) 1006 goto defer_complete; 1007 1008 /* 1009 * Request not freed here because we know it's called from io-wq only, 1010 * which holds a reference. Hence it can't be the last put. The CQE 1011 * has been posted, last put frees it. 1012 */ 1013 req->flags |= REQ_F_CQE_SKIP; 1014 req_ref_put(req); 1015 } 1016 1017 void io_req_defer_failed(struct io_kiocb *req, s32 res) 1018 __must_hold(&ctx->uring_lock) 1019 { 1020 const struct io_cold_def *def = &io_cold_defs[req->opcode]; 1021 1022 lockdep_assert_held(&req->ctx->uring_lock); 1023 1024 req_set_fail(req); 1025 io_req_set_res(req, res, io_put_kbuf(req, res, NULL)); 1026 if (def->fail) 1027 def->fail(req); 1028 io_req_complete_defer(req); 1029 } 1030 1031 /* 1032 * A request might get retired back into the request caches even before opcode 1033 * handlers and io_issue_sqe() are done with it, e.g. inline completion path. 1034 * Because of that, io_alloc_req() should be called only under ->uring_lock 1035 * and with extra caution to not get a request that is still worked on. 1036 */ 1037 __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx) 1038 __must_hold(&ctx->uring_lock) 1039 { 1040 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO; 1041 void *reqs[IO_REQ_ALLOC_BATCH]; 1042 int nr_reqs = ARRAY_SIZE(reqs); 1043 1044 /* 1045 * Bulk alloc is all-or-nothing. If we fail to get a batch, retry a 1046 * single allocation to be on the safe side. 1047 */ 1048 if (!kmem_cache_alloc_bulk(req_cachep, gfp, nr_reqs, reqs)) { 1049 reqs[0] = kmem_cache_alloc(req_cachep, gfp); 1050 if (!reqs[0]) 1051 return false; 1052 nr_reqs = 1; 1053 } 1054 1055 percpu_ref_get_many(&ctx->refs, nr_reqs); 1056 ctx->nr_req_allocated += nr_reqs; 1057 1058 while (nr_reqs--) 1059 io_req_add_to_cache(reqs[nr_reqs], ctx); 1060 return true; 1061 } 1062 1063 __cold void io_free_req(struct io_kiocb *req) 1064 { 1065 /* refs were already put, restore them for io_req_task_complete() */ 1066 req->flags &= ~REQ_F_REFCOUNT; 1067 req->io_task_work.func = io_req_task_complete; 1068 io_req_task_work_add(req); 1069 } 1070 1071 static void __io_req_find_next_prep(struct io_kiocb *req) 1072 { 1073 struct io_ring_ctx *ctx = req->ctx; 1074 1075 spin_lock(&ctx->completion_lock); 1076 io_disarm_next(req); 1077 spin_unlock(&ctx->completion_lock); 1078 } 1079 1080 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req) 1081 { 1082 struct io_kiocb *nxt; 1083 1084 /* 1085 * If LINK is set, we have dependent requests in this chain. If we 1086 * didn't fail this request, queue the first one up, moving any other 1087 * dependencies to the next request. In case of failure, fail the rest 1088 * of the chain. 1089 */ 1090 if (unlikely(req->flags & IO_DISARM_MASK)) 1091 __io_req_find_next_prep(req); 1092 nxt = req->link; 1093 req->link = NULL; 1094 return nxt; 1095 } 1096 1097 static void io_req_task_cancel(struct io_tw_req tw_req, io_tw_token_t tw) 1098 { 1099 struct io_kiocb *req = tw_req.req; 1100 1101 io_tw_lock(req->ctx, tw); 1102 io_req_defer_failed(req, req->cqe.res); 1103 } 1104 1105 void io_req_task_submit(struct io_tw_req tw_req, io_tw_token_t tw) 1106 { 1107 struct io_kiocb *req = tw_req.req; 1108 struct io_ring_ctx *ctx = req->ctx; 1109 1110 io_tw_lock(ctx, tw); 1111 if (unlikely(tw.cancel)) 1112 io_req_defer_failed(req, -EFAULT); 1113 else if (req->flags & REQ_F_FORCE_ASYNC) 1114 io_queue_iowq(req); 1115 else 1116 io_queue_sqe(req, 0); 1117 } 1118 1119 void io_req_task_queue_fail(struct io_kiocb *req, int ret) 1120 { 1121 io_req_set_res(req, ret, 0); 1122 req->io_task_work.func = io_req_task_cancel; 1123 io_req_task_work_add(req); 1124 } 1125 1126 void io_req_task_queue(struct io_kiocb *req) 1127 { 1128 req->io_task_work.func = io_req_task_submit; 1129 io_req_task_work_add(req); 1130 } 1131 1132 void io_queue_next(struct io_kiocb *req) 1133 { 1134 struct io_kiocb *nxt = io_req_find_next(req); 1135 1136 if (nxt) 1137 io_req_task_queue(nxt); 1138 } 1139 1140 static inline void io_req_put_rsrc_nodes(struct io_kiocb *req) 1141 { 1142 struct io_ring_ctx *ctx = req->ctx; 1143 1144 if (req->file_node) { 1145 io_put_rsrc_node(ctx, req->file_node); 1146 req->file_node = NULL; 1147 } 1148 if (req->flags & REQ_F_BUF_NODE) 1149 io_put_rsrc_node(ctx, req->buf_node); 1150 } 1151 1152 static void io_free_batch_list(struct io_ring_ctx *ctx, 1153 struct io_wq_work_node *node) 1154 __must_hold(&ctx->uring_lock) 1155 { 1156 do { 1157 struct io_kiocb *req = container_of(node, struct io_kiocb, 1158 comp_list); 1159 1160 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) { 1161 if (req->flags & REQ_F_REISSUE) { 1162 node = req->comp_list.next; 1163 req->flags &= ~REQ_F_REISSUE; 1164 io_queue_iowq(req); 1165 continue; 1166 } 1167 if (req->flags & REQ_F_REFCOUNT) { 1168 node = req->comp_list.next; 1169 /* CQE posted, the last put only frees */ 1170 req->flags |= REQ_F_CQE_SKIP; 1171 if (!req_ref_put_and_test(req)) 1172 continue; 1173 } 1174 if ((req->flags & REQ_F_POLLED) && req->apoll) { 1175 struct async_poll *apoll = req->apoll; 1176 1177 if (apoll->double_poll) 1178 kfree(apoll->double_poll); 1179 io_cache_free(&ctx->apoll_cache, apoll); 1180 req->flags &= ~REQ_F_POLLED; 1181 } 1182 if (req->flags & IO_REQ_LINK_FLAGS) 1183 io_queue_next(req); 1184 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS)) 1185 io_clean_op(req); 1186 } 1187 io_put_file(req); 1188 io_req_put_rsrc_nodes(req); 1189 io_put_task(req); 1190 1191 node = req->comp_list.next; 1192 io_req_add_to_cache(req, ctx); 1193 } while (node); 1194 } 1195 1196 /* 1197 * The dispatched drain request ran alone, and anything submitted after it was 1198 * deferred. Once it completed, new requests may run if nothing is waiting. 1199 */ 1200 static __cold bool io_drain_req_completed(struct io_ring_ctx *ctx) 1201 { 1202 struct io_wq_work_node *node; 1203 1204 __wq_list_for_each(node, &ctx->submit_state.compl_reqs) { 1205 struct io_kiocb *req = container_of(node, struct io_kiocb, 1206 comp_list); 1207 1208 /* a requeued request hasn't completed */ 1209 if (req == ctx->drain_req && !(req->flags & REQ_F_REISSUE)) { 1210 ctx->drain_req = NULL; 1211 return true; 1212 } 1213 } 1214 return false; 1215 } 1216 1217 void __io_submit_flush_completions(struct io_ring_ctx *ctx) 1218 __must_hold(&ctx->uring_lock) 1219 { 1220 struct io_submit_state *state = &ctx->submit_state; 1221 struct io_wq_work_node *node; 1222 bool drain_done = false; 1223 1224 /* 1225 * Drop the files before the CQEs are posted, so they're released by 1226 * the time the completions are visible. Not for requests that are 1227 * requeued or still referenced, those aren't freed below. 1228 */ 1229 __wq_list_for_each(node, &state->compl_reqs) { 1230 struct io_kiocb *req = container_of(node, struct io_kiocb, 1231 comp_list); 1232 1233 if (!io_req_shared(req)) 1234 io_req_put_file(req, true); 1235 } 1236 1237 __io_cq_lock(ctx); 1238 __wq_list_for_each(node, &state->compl_reqs) { 1239 struct io_kiocb *req = container_of(node, struct io_kiocb, 1240 comp_list); 1241 1242 /* 1243 * Requests marked with REQUEUE should not post a CQE, they 1244 * will go through the io-wq retry machinery and post one 1245 * later. 1246 */ 1247 if (!(req->flags & (REQ_F_CQE_SKIP | REQ_F_REISSUE)) && 1248 unlikely(!io_fill_cqe_req(ctx, req))) { 1249 if (ctx->int_flags & IO_RING_F_LOCKLESS_CQ) 1250 io_cqe_overflow(ctx, &req->cqe, &req->big_cqe); 1251 else 1252 io_cqe_overflow_locked(ctx, &req->cqe, &req->big_cqe); 1253 } 1254 } 1255 __io_cq_unlock_post(ctx); 1256 1257 if (unlikely(ctx->int_flags & IO_RING_F_DRAIN_ACTIVE) && ctx->drain_req) 1258 drain_done = io_drain_req_completed(ctx); 1259 1260 if (!wq_list_empty(&state->compl_reqs)) { 1261 io_free_batch_list(ctx, state->compl_reqs.first); 1262 INIT_WQ_LIST(&state->compl_reqs); 1263 } 1264 1265 if (unlikely(ctx->int_flags & IO_RING_F_DRAIN_ACTIVE)) { 1266 io_queue_deferred(ctx); 1267 if (drain_done && list_empty(&ctx->defer_list)) 1268 ctx->int_flags &= ~IO_RING_F_DRAIN_ACTIVE; 1269 } 1270 1271 ctx->submit_state.cq_flush = false; 1272 } 1273 1274 /* 1275 * We can't just wait for polled events to come to us, we have to actively 1276 * find and complete them. 1277 */ 1278 __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx) 1279 { 1280 if (!(ctx->flags & IORING_SETUP_IOPOLL)) 1281 return; 1282 1283 mutex_lock(&ctx->uring_lock); 1284 while (!list_empty(&ctx->iopoll_list)) { 1285 /* let it sleep and repeat later if can't complete a request */ 1286 if (io_do_iopoll(ctx, true) == 0) 1287 break; 1288 /* 1289 * Ensure we allow local-to-the-cpu processing to take place, 1290 * in this case we need to ensure that we reap all events. 1291 * Also let task_work, etc. to progress by releasing the mutex 1292 */ 1293 if (need_resched()) { 1294 mutex_unlock(&ctx->uring_lock); 1295 cond_resched(); 1296 mutex_lock(&ctx->uring_lock); 1297 } 1298 } 1299 mutex_unlock(&ctx->uring_lock); 1300 1301 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) 1302 io_cancel_local_task_work(ctx); 1303 } 1304 1305 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned int min_events) 1306 { 1307 unsigned long check_cq; 1308 1309 min_events = min(min_events, ctx->cq_entries); 1310 1311 lockdep_assert_held(&ctx->uring_lock); 1312 1313 if (!io_allowed_run_tw(ctx)) 1314 return -EEXIST; 1315 1316 check_cq = READ_ONCE(ctx->check_cq); 1317 if (unlikely(check_cq)) { 1318 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)) 1319 __io_cqring_overflow_flush(ctx, false); 1320 /* 1321 * Similarly do not spin if we have not informed the user of any 1322 * dropped CQE. 1323 */ 1324 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)) 1325 return -EBADR; 1326 } 1327 /* 1328 * Don't enter poll loop if we already have events pending. 1329 * If we do, we can potentially be spinning for commands that 1330 * already triggered a CQE (eg in error). 1331 */ 1332 if (io_cqring_events(ctx)) 1333 return 0; 1334 1335 do { 1336 int ret = 0; 1337 1338 /* 1339 * If a submit got punted to a workqueue, we can have the 1340 * application entering polling for a command before it gets 1341 * issued. That app will hold the uring_lock for the duration 1342 * of the poll right here, so we need to take a breather every 1343 * now and then to ensure that the issue has a chance to add 1344 * the poll to the issued list. Otherwise we can spin here 1345 * forever, while the workqueue is stuck trying to acquire the 1346 * very same mutex. 1347 */ 1348 if (list_empty(&ctx->iopoll_list) || io_task_work_pending(ctx)) { 1349 (void) io_run_local_work_locked(ctx, min_events); 1350 1351 if (task_work_pending(current) || list_empty(&ctx->iopoll_list)) { 1352 mutex_unlock(&ctx->uring_lock); 1353 io_run_task_work(); 1354 mutex_lock(&ctx->uring_lock); 1355 } 1356 /* some requests don't go through iopoll_list */ 1357 if (list_empty(&ctx->iopoll_list)) 1358 break; 1359 } 1360 ret = io_do_iopoll(ctx, !min_events); 1361 if (unlikely(ret < 0)) 1362 return ret; 1363 1364 if (task_sigpending(current)) 1365 return -EINTR; 1366 if (need_resched()) 1367 break; 1368 } while (io_cqring_events(ctx) < min_events); 1369 1370 return 0; 1371 } 1372 1373 void io_req_task_complete(struct io_tw_req tw_req, io_tw_token_t tw) 1374 { 1375 struct io_kiocb *req = tw_req.req; 1376 1377 if (io_req_complete_ready(req)) 1378 io_req_complete_defer(req); 1379 } 1380 1381 /* 1382 * After the iocb has been issued, it's safe to be found on the poll list. 1383 * Adding the kiocb to the list AFTER submission ensures that we don't 1384 * find it from a io_do_iopoll() thread before the issuer is done 1385 * accessing the kiocb cookie. 1386 */ 1387 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags) 1388 { 1389 struct io_ring_ctx *ctx = req->ctx; 1390 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED; 1391 1392 /* workqueue context doesn't hold uring_lock, grab it now */ 1393 if (unlikely(needs_lock)) 1394 mutex_lock(&ctx->uring_lock); 1395 1396 /* 1397 * Track whether we have multiple files in our lists. This will impact 1398 * how we do polling eventually, not spinning if we're on potentially 1399 * different devices. 1400 */ 1401 if (list_empty(&ctx->iopoll_list)) { 1402 ctx->poll_multi_queue = false; 1403 } else if (!ctx->poll_multi_queue) { 1404 struct io_kiocb *list_req; 1405 1406 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb, iopoll_node); 1407 if (list_req->file != req->file) 1408 ctx->poll_multi_queue = true; 1409 } 1410 1411 list_add_tail(&req->iopoll_node, &ctx->iopoll_list); 1412 1413 if (unlikely(needs_lock)) { 1414 /* 1415 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle 1416 * in sq thread task context or in io worker task context. If 1417 * current task context is sq thread, we don't need to check 1418 * whether should wake up sq thread. 1419 */ 1420 if ((ctx->flags & IORING_SETUP_SQPOLL) && 1421 wq_has_sleeper(&ctx->sq_data->wait)) 1422 wake_up(&ctx->sq_data->wait); 1423 1424 mutex_unlock(&ctx->uring_lock); 1425 } 1426 } 1427 1428 io_req_flags_t io_file_get_flags(struct file *file) 1429 { 1430 io_req_flags_t res = 0; 1431 1432 BUILD_BUG_ON(REQ_F_ISREG_BIT != REQ_F_SUPPORT_NOWAIT_BIT + 1); 1433 1434 if (S_ISREG(file_inode(file)->i_mode)) 1435 res |= REQ_F_ISREG; 1436 if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT)) 1437 res |= REQ_F_SUPPORT_NOWAIT; 1438 return res; 1439 } 1440 1441 static __cold void io_drain_req(struct io_kiocb *req) 1442 __must_hold(&ctx->uring_lock) 1443 { 1444 struct io_ring_ctx *ctx = req->ctx; 1445 bool drain = req->flags & IOSQE_IO_DRAIN; 1446 struct io_defer_entry *de; 1447 1448 de = kmalloc_obj(*de, GFP_KERNEL_ACCOUNT); 1449 if (!de) { 1450 io_req_defer_failed(req, -ENOMEM); 1451 return; 1452 } 1453 1454 io_prep_async_link(req); 1455 trace_io_uring_defer(req); 1456 de->req = req; 1457 1458 ctx->nr_drained += io_linked_nr(req); 1459 list_add_tail(&de->list, &ctx->defer_list); 1460 io_queue_deferred(ctx); 1461 if (!drain && list_empty(&ctx->defer_list)) 1462 ctx->int_flags &= ~IO_RING_F_DRAIN_ACTIVE; 1463 } 1464 1465 #define REQ_ISSUE_SLOW_FLAGS (REQ_F_CREDS | REQ_F_ARM_LTIMEOUT) 1466 1467 static inline int __io_issue_sqe(struct io_kiocb *req, 1468 unsigned int issue_flags, 1469 const struct io_issue_def *def) 1470 { 1471 const struct cred *creds = NULL; 1472 struct io_kiocb *link = NULL; 1473 int ret; 1474 1475 if (unlikely(req->flags & REQ_ISSUE_SLOW_FLAGS)) { 1476 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred()) 1477 creds = override_creds(req->creds); 1478 if (req->flags & REQ_F_ARM_LTIMEOUT) 1479 link = __io_prep_linked_timeout(req); 1480 } 1481 1482 if (!def->audit_skip) 1483 audit_uring_entry(req->opcode); 1484 1485 ret = def->issue(req, issue_flags); 1486 1487 if (!def->audit_skip) 1488 audit_uring_exit(!ret, ret); 1489 1490 if (unlikely(creds || link)) { 1491 if (creds) 1492 revert_creds(creds); 1493 if (link) 1494 io_queue_linked_timeout(link); 1495 } 1496 1497 return ret; 1498 } 1499 1500 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags) 1501 { 1502 const struct io_issue_def *def = &io_issue_defs[req->opcode]; 1503 int ret; 1504 1505 if (unlikely(!io_assign_file(req, def, issue_flags))) 1506 return -EBADF; 1507 1508 ret = __io_issue_sqe(req, issue_flags, def); 1509 1510 if (ret == IOU_COMPLETE) { 1511 /* not all handlers take care of the internal restart codes */ 1512 if (unlikely(req->cqe.res <= -ERESTARTSYS)) 1513 req->cqe.res = io_fixup_restart_res(req->cqe.res); 1514 if (issue_flags & IO_URING_F_COMPLETE_DEFER) 1515 io_req_complete_defer(req); 1516 else 1517 io_req_complete_post(req, issue_flags); 1518 1519 return 0; 1520 } 1521 1522 if (ret == IOU_ISSUE_SKIP_COMPLETE) { 1523 ret = 0; 1524 1525 if (req->flags & REQ_F_IOPOLL) 1526 io_iopoll_req_issued(req, issue_flags); 1527 } 1528 if (unlikely(ret <= -ERESTARTSYS)) 1529 ret = io_fixup_restart_res(ret); 1530 return ret; 1531 } 1532 1533 int io_poll_issue(struct io_kiocb *req, io_tw_token_t tw) 1534 { 1535 const unsigned int issue_flags = IO_URING_F_NONBLOCK | 1536 IO_URING_F_MULTISHOT | 1537 IO_URING_F_COMPLETE_DEFER; 1538 int ret; 1539 1540 io_tw_lock(req->ctx, tw); 1541 1542 WARN_ON_ONCE(!req->file); 1543 if (WARN_ON_ONCE(req->flags & REQ_F_IOPOLL)) 1544 return -EFAULT; 1545 1546 ret = __io_issue_sqe(req, issue_flags, &io_issue_defs[req->opcode]); 1547 1548 WARN_ON_ONCE(ret == IOU_ISSUE_SKIP_COMPLETE); 1549 return ret; 1550 } 1551 1552 /* 1553 * io-wq is done with @work. Returns true if it held the last reference, and 1554 * hands out the next request of the link then. The caller has to make sure 1555 * that cancellations can find the latter before it calls io_wq_free_work(). 1556 */ 1557 bool io_wq_put_work(struct io_wq_work *work, struct io_wq_work **linked) 1558 { 1559 struct io_kiocb *req = container_of(work, struct io_kiocb, work); 1560 struct io_kiocb *nxt = NULL; 1561 1562 *linked = NULL; 1563 if (!req_ref_put_and_test_atomic(req)) 1564 return false; 1565 1566 /* 1567 * Only continue the link from here if the completion has been posted. 1568 * If it's still pending, io_free_req() completes the request and the 1569 * next link follows from there, after the CQE. 1570 */ 1571 if ((req->flags & IO_REQ_LINK_FLAGS) && (req->flags & REQ_F_CQE_SKIP)) { 1572 struct io_ring_ctx *ctx = req->ctx; 1573 1574 mutex_lock(&ctx->uring_lock); 1575 nxt = io_req_find_next(req); 1576 mutex_unlock(&ctx->uring_lock); 1577 } 1578 if (nxt) 1579 *linked = &nxt->work; 1580 return true; 1581 } 1582 1583 void io_wq_free_work(struct io_wq_work *work) 1584 { 1585 io_free_req(container_of(work, struct io_kiocb, work)); 1586 } 1587 1588 void io_wq_submit_work(struct io_wq_work *work) 1589 { 1590 struct io_kiocb *req = container_of(work, struct io_kiocb, work); 1591 const struct io_issue_def *def = &io_issue_defs[req->opcode]; 1592 unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ; 1593 bool needs_poll = false; 1594 int ret = 0, err = -ECANCELED; 1595 1596 /* one will be dropped by io_wq_put_work() after returning to io-wq */ 1597 if (!(req->flags & REQ_F_REFCOUNT)) 1598 __io_req_set_refcount(req, 2); 1599 else 1600 req_ref_get(req); 1601 1602 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */ 1603 if (atomic_read(&work->flags) & IO_WQ_WORK_CANCEL) { 1604 fail: 1605 io_req_put_file(req, false); 1606 io_req_task_queue_fail(req, err); 1607 return; 1608 } 1609 if (!io_assign_file(req, def, issue_flags)) { 1610 err = -EBADF; 1611 atomic_or(IO_WQ_WORK_CANCEL, &work->flags); 1612 goto fail; 1613 } 1614 1615 /* 1616 * If DEFER_TASKRUN is set, it's only allowed to post CQEs from the 1617 * submitter task context. Final request completions are handed to the 1618 * right context, however this is not the case of auxiliary CQEs, 1619 * which is the main mean of operation for multishot requests. 1620 * Don't allow any multishot execution from io-wq. It's more restrictive 1621 * than necessary and also cleaner. 1622 */ 1623 if (req->flags & (REQ_F_MULTISHOT|REQ_F_APOLL_MULTISHOT)) { 1624 err = -EBADFD; 1625 if (!io_file_can_poll(req)) 1626 goto fail; 1627 if (req->file->f_flags & O_NONBLOCK || 1628 req->file->f_mode & FMODE_NOWAIT) { 1629 err = -ECANCELED; 1630 if (io_arm_poll_handler(req, issue_flags) != IO_APOLL_OK) 1631 goto fail; 1632 return; 1633 } else { 1634 req->flags &= ~(REQ_F_APOLL_MULTISHOT|REQ_F_MULTISHOT); 1635 } 1636 } 1637 1638 if (req->flags & REQ_F_FORCE_ASYNC) { 1639 bool opcode_poll = def->pollin || def->pollout; 1640 1641 if (opcode_poll && io_file_can_poll(req)) { 1642 needs_poll = true; 1643 issue_flags |= IO_URING_F_NONBLOCK; 1644 } 1645 } 1646 1647 do { 1648 ret = io_issue_sqe(req, issue_flags); 1649 if (ret != -EAGAIN) 1650 break; 1651 1652 /* 1653 * If REQ_F_NOWAIT is set, then don't wait or retry with 1654 * poll. -EAGAIN is final for that case. 1655 */ 1656 if (req->flags & REQ_F_NOWAIT) 1657 break; 1658 1659 /* 1660 * We can get EAGAIN for iopolled IO even though we're 1661 * forcing a sync submission from here, since we can't 1662 * wait for request slots on the block side. 1663 */ 1664 if (!needs_poll) { 1665 if (!(req->flags & REQ_F_IOPOLL)) 1666 break; 1667 if (io_wq_worker_stopped()) 1668 break; 1669 cond_resched(); 1670 continue; 1671 } 1672 1673 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK) 1674 return; 1675 /* aborted or ready, in either case retry blocking */ 1676 needs_poll = false; 1677 issue_flags &= ~IO_URING_F_NONBLOCK; 1678 } while (1); 1679 1680 /* avoid locking problems by failing it from a clean context */ 1681 if (ret) { 1682 io_req_put_file(req, true); 1683 io_req_task_queue_fail(req, ret); 1684 } 1685 } 1686 1687 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd, 1688 unsigned int issue_flags) 1689 { 1690 struct io_ring_ctx *ctx = req->ctx; 1691 struct io_rsrc_node *node; 1692 struct file *file = NULL; 1693 1694 io_ring_submit_lock(ctx, issue_flags); 1695 node = io_rsrc_node_lookup(&ctx->file_table.data, fd); 1696 if (node) { 1697 node->refs++; 1698 req->file_node = node; 1699 req->flags |= io_slot_flags(node); 1700 file = io_slot_file(node); 1701 } 1702 io_ring_submit_unlock(ctx, issue_flags); 1703 return file; 1704 } 1705 1706 struct file *io_file_get_normal(struct io_kiocb *req, int fd) 1707 { 1708 struct file *file = fget(fd); 1709 1710 trace_io_uring_file_get(req, fd); 1711 1712 /* we don't allow fixed io_uring files */ 1713 if (file && io_is_uring_fops(file)) 1714 io_req_track_inflight(req); 1715 return file; 1716 } 1717 1718 static int io_req_sqe_copy(struct io_kiocb *req, unsigned int issue_flags) 1719 { 1720 const struct io_cold_def *def = &io_cold_defs[req->opcode]; 1721 1722 if (req->flags & REQ_F_SQE_COPIED) 1723 return 0; 1724 req->flags |= REQ_F_SQE_COPIED; 1725 if (!def->sqe_copy) 1726 return 0; 1727 if (WARN_ON_ONCE(!(issue_flags & IO_URING_F_INLINE))) 1728 return -EFAULT; 1729 def->sqe_copy(req); 1730 return 0; 1731 } 1732 1733 static void io_queue_async(struct io_kiocb *req, unsigned int issue_flags, int ret) 1734 __must_hold(&req->ctx->uring_lock) 1735 { 1736 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) { 1737 fail: 1738 io_req_defer_failed(req, ret); 1739 return; 1740 } 1741 1742 ret = io_req_sqe_copy(req, issue_flags); 1743 if (unlikely(ret)) 1744 goto fail; 1745 1746 switch (io_arm_poll_handler(req, 0)) { 1747 case IO_APOLL_READY: 1748 io_req_task_queue(req); 1749 break; 1750 case IO_APOLL_ABORTED: 1751 io_queue_iowq(req); 1752 break; 1753 case IO_APOLL_OK: 1754 break; 1755 } 1756 } 1757 1758 static inline void io_queue_sqe(struct io_kiocb *req, unsigned int extra_flags) 1759 __must_hold(&req->ctx->uring_lock) 1760 { 1761 unsigned int issue_flags = IO_URING_F_NONBLOCK | 1762 IO_URING_F_COMPLETE_DEFER | extra_flags; 1763 int ret; 1764 1765 ret = io_issue_sqe(req, issue_flags); 1766 1767 /* 1768 * We async punt it if the file wasn't marked NOWAIT, or if the file 1769 * doesn't support non-blocking read/write attempts 1770 */ 1771 if (unlikely(ret)) 1772 io_queue_async(req, issue_flags, ret); 1773 } 1774 1775 static void io_queue_sqe_fallback(struct io_kiocb *req) 1776 __must_hold(&req->ctx->uring_lock) 1777 { 1778 if (unlikely(req->flags & REQ_F_FAIL)) { 1779 /* 1780 * We don't submit, fail them all, for that replace hardlinks 1781 * with normal links. Extra REQ_F_LINK is tolerated. 1782 */ 1783 req->flags &= ~REQ_F_HARDLINK; 1784 req->flags |= REQ_F_LINK; 1785 io_req_defer_failed(req, req->cqe.res); 1786 } else { 1787 /* can't fail with IO_URING_F_INLINE */ 1788 io_req_sqe_copy(req, IO_URING_F_INLINE); 1789 if (unlikely(req->ctx->int_flags & IO_RING_F_DRAIN_ACTIVE)) 1790 io_drain_req(req); 1791 else 1792 io_queue_iowq(req); 1793 } 1794 } 1795 1796 /* 1797 * Check SQE restrictions (opcode and flags). 1798 * 1799 * Returns 'true' if SQE is allowed, 'false' otherwise. 1800 */ 1801 static inline bool io_check_restriction(struct io_ring_ctx *ctx, 1802 struct io_kiocb *req, 1803 unsigned int sqe_flags) 1804 { 1805 if (!(ctx->int_flags & IO_RING_F_OP_RESTRICTED)) 1806 return true; 1807 if (!test_bit(req->opcode, ctx->restrictions.sqe_op)) 1808 return false; 1809 1810 if ((sqe_flags & ctx->restrictions.sqe_flags_required) != 1811 ctx->restrictions.sqe_flags_required) 1812 return false; 1813 1814 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed | 1815 ctx->restrictions.sqe_flags_required)) 1816 return false; 1817 1818 return true; 1819 } 1820 1821 static void io_init_drain(struct io_ring_ctx *ctx) 1822 { 1823 struct io_kiocb *head = ctx->submit_state.link.head; 1824 1825 ctx->int_flags |= IO_RING_F_DRAIN_ACTIVE; 1826 if (head) { 1827 /* 1828 * If we need to drain a request in the middle of a link, drain 1829 * the head request and the next request/link after the current 1830 * link. Considering sequential execution of links, 1831 * REQ_F_IO_DRAIN will be maintained for every request of our 1832 * link. 1833 */ 1834 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC; 1835 ctx->int_flags |= IO_RING_F_DRAIN_NEXT; 1836 } 1837 } 1838 1839 static __cold int io_init_fail_req(struct io_kiocb *req, int err) 1840 { 1841 /* ensure per-opcode data is cleared if we fail before prep */ 1842 memset(&req->cmd.data, 0, sizeof(req->cmd.data)); 1843 return err; 1844 } 1845 1846 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req, 1847 const struct io_uring_sqe *sqe, unsigned int *left) 1848 __must_hold(&ctx->uring_lock) 1849 { 1850 const struct io_issue_def *def; 1851 unsigned int sqe_flags; 1852 int personality; 1853 1854 req->ctx = ctx; 1855 req->opcode = READ_ONCE(sqe->opcode); 1856 /* same numerical values with corresponding REQ_F_*, safe to copy */ 1857 sqe_flags = READ_ONCE(sqe->flags); 1858 req->flags = (__force io_req_flags_t) sqe_flags; 1859 req->cqe.user_data = READ_ONCE(sqe->user_data); 1860 req->file = NULL; 1861 req->tctx = current->io_uring; 1862 req->cancel_seq_set = false; 1863 req->async_data = NULL; 1864 1865 if (unlikely(req->opcode >= IORING_OP_LAST)) { 1866 req->opcode = 0; 1867 return io_init_fail_req(req, -EINVAL); 1868 } 1869 req->opcode = array_index_nospec(req->opcode, IORING_OP_LAST); 1870 1871 def = &io_issue_defs[req->opcode]; 1872 if (def->is_128 && !(ctx->flags & IORING_SETUP_SQE128)) { 1873 /* 1874 * A 128b op on a non-128b SQ requires mixed SQE support as 1875 * well as 2 contiguous entries. 1876 */ 1877 if (!(ctx->flags & IORING_SETUP_SQE_MIXED) || 1878 (unsigned)(sqe - ctx->sq_sqes) >= ctx->sq_entries - 1) 1879 return io_init_fail_req(req, -EINVAL); 1880 if (*left >= 2) { 1881 /* 1882 * A 128b operation on a mixed SQ uses two entries, so 1883 * we have to increment the head and cached refs, and 1884 * decrement what's left. 1885 */ 1886 current->io_uring->cached_refs++; 1887 (*left)--; 1888 } else if (!(ctx->flags & IORING_SETUP_SQPOLL) || 1889 !__io_sqring_entries(ctx)) { 1890 return io_init_fail_req(req, -EINVAL); 1891 } 1892 /* 1893 * else: the SQPOLL thread caps the number of entries it submits 1894 * in one go, which is none of the application's business. Take 1895 * the 2nd entry on top. 1896 */ 1897 ctx->cached_sq_head++; 1898 } 1899 1900 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) { 1901 /* enforce forwards compatibility on users */ 1902 if (sqe_flags & ~SQE_VALID_FLAGS) 1903 return io_init_fail_req(req, -EINVAL); 1904 if (sqe_flags & IOSQE_BUFFER_SELECT) { 1905 if (!def->buffer_select) 1906 return io_init_fail_req(req, -EOPNOTSUPP); 1907 req->buf_index = READ_ONCE(sqe->buf_group); 1908 } 1909 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS) 1910 ctx->int_flags |= IO_RING_F_DRAIN_DISABLED; 1911 if (sqe_flags & IOSQE_IO_DRAIN) { 1912 if (ctx->int_flags & IO_RING_F_DRAIN_DISABLED) 1913 return io_init_fail_req(req, -EOPNOTSUPP); 1914 io_init_drain(ctx); 1915 } 1916 } 1917 if (unlikely(ctx->int_flags & (IO_RING_F_OP_RESTRICTED | IO_RING_F_DRAIN_ACTIVE | IO_RING_F_DRAIN_NEXT))) { 1918 if (!io_check_restriction(ctx, req, sqe_flags)) 1919 return io_init_fail_req(req, -EACCES); 1920 /* knock it to the slow queue path, will be drained there */ 1921 if (ctx->int_flags & IO_RING_F_DRAIN_ACTIVE) 1922 req->flags |= REQ_F_FORCE_ASYNC; 1923 /* if there is no link, we're at "next" request and need to drain */ 1924 if (unlikely(ctx->int_flags & IO_RING_F_DRAIN_NEXT) && !ctx->submit_state.link.head) { 1925 ctx->int_flags &= ~IO_RING_F_DRAIN_NEXT; 1926 ctx->int_flags |= IO_RING_F_DRAIN_ACTIVE; 1927 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC; 1928 } 1929 } 1930 1931 if (!def->ioprio && sqe->ioprio) 1932 return io_init_fail_req(req, -EINVAL); 1933 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL)) 1934 return io_init_fail_req(req, -EINVAL); 1935 1936 if (def->needs_file) { 1937 struct io_submit_state *state = &ctx->submit_state; 1938 1939 req->cqe.fd = READ_ONCE(sqe->fd); 1940 1941 /* 1942 * Plug now if we have more than 2 IO left after this, and the 1943 * target is potentially a read/write to block based storage. 1944 */ 1945 if (state->need_plug && def->plug) { 1946 state->plug_started = true; 1947 state->need_plug = false; 1948 blk_start_plug_nr_ios(&state->plug, state->submit_nr); 1949 } 1950 } 1951 1952 personality = READ_ONCE(sqe->personality); 1953 if (personality) { 1954 int ret; 1955 1956 req->creds = xa_load(&ctx->personalities, personality); 1957 if (!req->creds) 1958 return io_init_fail_req(req, -EINVAL); 1959 get_cred(req->creds); 1960 ret = security_uring_override_creds(req->creds); 1961 if (ret) { 1962 put_cred(req->creds); 1963 return io_init_fail_req(req, ret); 1964 } 1965 req->flags |= REQ_F_CREDS; 1966 } 1967 1968 return def->prep(req, sqe); 1969 } 1970 1971 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe, 1972 struct io_kiocb *req, int ret) 1973 { 1974 struct io_ring_ctx *ctx = req->ctx; 1975 struct io_submit_link *link = &ctx->submit_state.link; 1976 struct io_kiocb *head = link->head; 1977 1978 trace_io_uring_req_failed(sqe, req, ret); 1979 1980 /* 1981 * Avoid breaking links in the middle as it renders links with SQPOLL 1982 * unusable. Instead of failing eagerly, continue assembling the link if 1983 * applicable and mark the head with REQ_F_FAIL. The link flushing code 1984 * should find the flag and handle the rest. 1985 */ 1986 req_fail_link_node(req, ret); 1987 if (head && !(head->flags & REQ_F_FAIL)) 1988 req_fail_link_node(head, -ECANCELED); 1989 1990 if (!(req->flags & IO_REQ_LINK_FLAGS)) { 1991 if (head) { 1992 link->last->link = req; 1993 link->head = NULL; 1994 req = head; 1995 } 1996 io_queue_sqe_fallback(req); 1997 return ret; 1998 } 1999 2000 if (head) 2001 link->last->link = req; 2002 else 2003 link->head = req; 2004 link->last = req; 2005 return 0; 2006 } 2007 2008 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req, 2009 const struct io_uring_sqe *sqe, unsigned int *left) 2010 __must_hold(&ctx->uring_lock) 2011 { 2012 struct io_submit_link *link = &ctx->submit_state.link; 2013 int ret; 2014 2015 ret = io_init_req(ctx, req, sqe, left); 2016 if (unlikely(ret)) 2017 return io_submit_fail_init(sqe, req, ret); 2018 2019 if (unlikely(ctx->bpf_filters)) { 2020 ret = io_uring_run_bpf_filters(ctx->bpf_filters, req); 2021 if (ret) 2022 return io_submit_fail_init(sqe, req, ret); 2023 } 2024 2025 trace_io_uring_submit_req(req); 2026 2027 /* 2028 * If we already have a head request, queue this one for async 2029 * submittal once the head completes. If we don't have a head but 2030 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be 2031 * submitted sync once the chain is complete. If none of those 2032 * conditions are true (normal request), then just queue it. 2033 */ 2034 if (unlikely(link->head)) { 2035 trace_io_uring_link(req, link->last); 2036 io_req_sqe_copy(req, IO_URING_F_INLINE); 2037 link->last->link = req; 2038 link->last = req; 2039 2040 if (req->flags & IO_REQ_LINK_FLAGS) 2041 return 0; 2042 /* last request of the link, flush it */ 2043 req = link->head; 2044 link->head = NULL; 2045 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)) 2046 goto fallback; 2047 2048 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS | 2049 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) { 2050 if (req->flags & IO_REQ_LINK_FLAGS) { 2051 link->head = req; 2052 link->last = req; 2053 } else { 2054 fallback: 2055 io_queue_sqe_fallback(req); 2056 } 2057 return 0; 2058 } 2059 2060 io_queue_sqe(req, IO_URING_F_INLINE); 2061 return 0; 2062 } 2063 2064 /* 2065 * Batched submission is done, ensure local IO is flushed out. 2066 */ 2067 static void io_submit_state_end(struct io_ring_ctx *ctx) 2068 { 2069 struct io_submit_state *state = &ctx->submit_state; 2070 2071 if (unlikely(state->link.head)) 2072 io_queue_sqe_fallback(state->link.head); 2073 /* flush only after queuing links as they can generate completions */ 2074 io_submit_flush_completions(ctx); 2075 if (state->plug_started) 2076 blk_finish_plug(&state->plug); 2077 } 2078 2079 /* 2080 * Start submission side cache. 2081 */ 2082 static void io_submit_state_start(struct io_submit_state *state, 2083 unsigned int max_ios) 2084 { 2085 state->plug_started = false; 2086 state->need_plug = max_ios > 2; 2087 state->submit_nr = max_ios; 2088 /* set only head, no need to init link_last in advance */ 2089 state->link.head = NULL; 2090 } 2091 2092 static void io_commit_sqring(struct io_ring_ctx *ctx) 2093 { 2094 struct io_rings *rings = ctx->rings; 2095 2096 if (ctx->flags & IORING_SETUP_SQ_REWIND) { 2097 ctx->cached_sq_head = 0; 2098 } else { 2099 /* 2100 * Ensure any loads from the SQEs are done at this point, 2101 * since once we write the new head, the application could 2102 * write new data to them. 2103 */ 2104 smp_store_release(&rings->sq.head, ctx->cached_sq_head); 2105 } 2106 } 2107 2108 /* 2109 * Fetch an sqe, if one is available. Note this returns a pointer to memory 2110 * that is mapped by userspace. This means that care needs to be taken to 2111 * ensure that reads are stable, as we cannot rely on userspace always 2112 * being a good citizen. If members of the sqe are validated and then later 2113 * used, it's important that those reads are done through READ_ONCE() to 2114 * prevent a re-load down the line. 2115 */ 2116 static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe) 2117 { 2118 unsigned mask = ctx->sq_entries - 1; 2119 unsigned head = ctx->cached_sq_head++ & mask; 2120 2121 if (static_branch_unlikely(&io_key_has_sqarray.key) && 2122 (!(ctx->flags & IORING_SETUP_NO_SQARRAY))) { 2123 head = READ_ONCE(ctx->sq_array[head]); 2124 if (unlikely(head >= ctx->sq_entries)) { 2125 WRITE_ONCE(ctx->rings->sq_dropped, 2126 READ_ONCE(ctx->rings->sq_dropped) + 1); 2127 return false; 2128 } 2129 head = array_index_nospec(head, ctx->sq_entries); 2130 } 2131 2132 /* 2133 * The cached sq head (or cq tail) serves two purposes: 2134 * 2135 * 1) allows us to batch the cost of updating the user visible 2136 * head updates. 2137 * 2) allows the kernel side to track the head on its own, even 2138 * though the application is the one updating it. 2139 */ 2140 2141 /* double index for 128-byte SQEs, twice as long */ 2142 if (ctx->flags & IORING_SETUP_SQE128) 2143 head <<= 1; 2144 *sqe = &ctx->sq_sqes[head]; 2145 return true; 2146 } 2147 2148 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr) 2149 __must_hold(&ctx->uring_lock) 2150 { 2151 unsigned int entries; 2152 unsigned int left; 2153 int ret; 2154 2155 if (ctx->flags & IORING_SETUP_SQ_REWIND) 2156 entries = ctx->sq_entries; 2157 else 2158 entries = __io_sqring_entries(ctx); 2159 2160 entries = min(nr, entries); 2161 if (unlikely(!entries)) 2162 return 0; 2163 2164 ret = left = entries; 2165 io_get_task_refs(left); 2166 io_submit_state_start(&ctx->submit_state, left); 2167 2168 do { 2169 const struct io_uring_sqe *sqe; 2170 struct io_kiocb *req; 2171 2172 if (unlikely(!io_alloc_req(ctx, &req))) 2173 break; 2174 if (unlikely(!io_get_sqe(ctx, &sqe))) { 2175 io_req_add_to_cache(req, ctx); 2176 break; 2177 } 2178 2179 /* 2180 * Continue submitting even for sqe failure if the 2181 * ring was setup with IORING_SETUP_SUBMIT_ALL 2182 */ 2183 if (unlikely(io_submit_sqe(ctx, req, sqe, &left)) && 2184 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) { 2185 left--; 2186 break; 2187 } 2188 } while (--left); 2189 2190 if (unlikely(left)) { 2191 ret -= left; 2192 /* try again if it submitted nothing and can't allocate a req */ 2193 if (!ret && io_req_cache_empty(ctx)) 2194 ret = -EAGAIN; 2195 current->io_uring->cached_refs += left; 2196 } 2197 2198 io_submit_state_end(ctx); 2199 /* Commit SQ ring head once we've consumed and submitted all SQEs */ 2200 io_commit_sqring(ctx); 2201 return ret; 2202 } 2203 2204 static void io_rings_free(struct io_ring_ctx *ctx) 2205 { 2206 /* ring memory is not charged to RLIMIT_MEMLOCK, hence no user */ 2207 io_free_region(NULL, &ctx->sq_region); 2208 io_free_region(NULL, &ctx->ring_region); 2209 ctx->rings = NULL; 2210 RCU_INIT_POINTER(ctx->rings_rcu, NULL); 2211 ctx->sq_sqes = NULL; 2212 } 2213 2214 static int rings_size(unsigned int flags, unsigned int sq_entries, 2215 unsigned int cq_entries, struct io_rings_layout *rl) 2216 { 2217 struct io_rings *rings; 2218 size_t sqe_size; 2219 size_t off; 2220 2221 if (flags & IORING_SETUP_CQE_MIXED) { 2222 if (cq_entries < 2) 2223 return -EOVERFLOW; 2224 } 2225 if (flags & IORING_SETUP_SQE_MIXED) { 2226 if (sq_entries < 2) 2227 return -EOVERFLOW; 2228 } 2229 2230 rl->sq_array_offset = SIZE_MAX; 2231 2232 sqe_size = sizeof(struct io_uring_sqe); 2233 if (flags & IORING_SETUP_SQE128) 2234 sqe_size *= 2; 2235 2236 rl->sq_size = array_size(sqe_size, sq_entries); 2237 if (rl->sq_size == SIZE_MAX) 2238 return -EOVERFLOW; 2239 2240 off = struct_size(rings, cqes, cq_entries); 2241 if (flags & IORING_SETUP_CQE32) 2242 off = size_mul(off, 2); 2243 if (off == SIZE_MAX) 2244 return -EOVERFLOW; 2245 2246 #ifdef CONFIG_SMP 2247 off = ALIGN(off, SMP_CACHE_BYTES); 2248 if (off == 0) 2249 return -EOVERFLOW; 2250 #endif 2251 2252 if (!(flags & IORING_SETUP_NO_SQARRAY)) { 2253 size_t sq_array_size; 2254 2255 rl->sq_array_offset = off; 2256 2257 sq_array_size = array_size(sizeof(u32), sq_entries); 2258 off = size_add(off, sq_array_size); 2259 if (off == SIZE_MAX) 2260 return -EOVERFLOW; 2261 } 2262 2263 rl->rings_size = off; 2264 return 0; 2265 } 2266 2267 static __cold void __io_req_caches_free(struct io_ring_ctx *ctx) 2268 { 2269 struct io_kiocb *req; 2270 int nr = 0; 2271 2272 while (!io_req_cache_empty(ctx)) { 2273 req = io_extract_req(ctx); 2274 io_poison_req(req); 2275 kmem_cache_free(req_cachep, req); 2276 nr++; 2277 } 2278 if (nr) { 2279 ctx->nr_req_allocated -= nr; 2280 percpu_ref_put_many(&ctx->refs, nr); 2281 } 2282 } 2283 2284 static __cold void io_req_caches_free(struct io_ring_ctx *ctx) 2285 { 2286 guard(mutex)(&ctx->uring_lock); 2287 __io_req_caches_free(ctx); 2288 } 2289 2290 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx) 2291 { 2292 io_unregister_bpf_ops(ctx); 2293 io_sq_thread_finish(ctx); 2294 2295 mutex_lock(&ctx->uring_lock); 2296 io_unregister_zcrx(ctx); 2297 io_cqring_overflow_kill(ctx); 2298 io_eventfd_unregister(ctx); 2299 io_free_alloc_caches(ctx); 2300 io_destroy_buffers(ctx); 2301 io_free_region(ctx->user, &ctx->param_region); 2302 mutex_unlock(&ctx->uring_lock); 2303 if (ctx->sq_creds) 2304 put_cred(ctx->sq_creds); 2305 if (ctx->submitter_task) 2306 put_task_struct(ctx->submitter_task); 2307 2308 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list)); 2309 2310 if (ctx->mm_account) { 2311 mmdrop(ctx->mm_account); 2312 ctx->mm_account = NULL; 2313 } 2314 io_rings_free(ctx); 2315 2316 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY)) 2317 static_branch_slow_dec_deferred(&io_key_has_sqarray); 2318 2319 percpu_ref_exit(&ctx->refs); 2320 free_uid(ctx->user); 2321 io_req_caches_free(ctx); 2322 2323 if (ctx->restrictions.bpf_filters) { 2324 WARN_ON_ONCE(ctx->bpf_filters != 2325 ctx->restrictions.bpf_filters->filters); 2326 } else { 2327 WARN_ON_ONCE(ctx->bpf_filters); 2328 } 2329 io_put_bpf_filters(&ctx->restrictions); 2330 2331 WARN_ON_ONCE(ctx->nr_req_allocated); 2332 2333 if (ctx->hash_map) 2334 io_wq_put_hash(ctx->hash_map); 2335 io_napi_free(ctx); 2336 kvfree(ctx->cancel_table.hbs); 2337 xa_destroy(&ctx->io_bl_xa); 2338 xa_destroy(&ctx->hpage_acct); 2339 kfree(ctx); 2340 } 2341 2342 static __cold void io_activate_pollwq_cb(struct callback_head *cb) 2343 { 2344 struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx, 2345 poll_wq_task_work); 2346 2347 mutex_lock(&ctx->uring_lock); 2348 ctx->int_flags |= IO_RING_F_POLL_ACTIVATED; 2349 mutex_unlock(&ctx->uring_lock); 2350 2351 /* 2352 * Wake ups for some events between start of polling and activation 2353 * might've been lost due to loose synchronisation. 2354 */ 2355 wake_up_all(&ctx->poll_wq); 2356 percpu_ref_put(&ctx->refs); 2357 } 2358 2359 __cold void io_activate_pollwq(struct io_ring_ctx *ctx) 2360 { 2361 spin_lock(&ctx->completion_lock); 2362 /* already activated or in progress */ 2363 if ((ctx->int_flags & IO_RING_F_POLL_ACTIVATED) || ctx->poll_wq_task_work.func) 2364 goto out; 2365 if (WARN_ON_ONCE(!(ctx->int_flags & IO_RING_F_TASK_COMPLETE))) 2366 goto out; 2367 if (!ctx->submitter_task) 2368 goto out; 2369 /* 2370 * with ->submitter_task only the submitter task completes requests, we 2371 * only need to sync with it, which is done by injecting a tw 2372 */ 2373 init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb); 2374 percpu_ref_get(&ctx->refs); 2375 if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL)) 2376 percpu_ref_put(&ctx->refs); 2377 out: 2378 spin_unlock(&ctx->completion_lock); 2379 } 2380 2381 static __poll_t io_uring_poll(struct file *file, poll_table *wait) 2382 { 2383 struct io_ring_ctx *ctx = file->private_data; 2384 __poll_t mask = 0; 2385 2386 if (unlikely(!(data_race(ctx->int_flags) & IO_RING_F_POLL_ACTIVATED))) 2387 io_activate_pollwq(ctx); 2388 /* 2389 * provides mb() which pairs with barrier from wq_has_sleeper 2390 * call in io_commit_cqring 2391 */ 2392 poll_wait(file, &ctx->poll_wq, wait); 2393 2394 rcu_read_lock(); 2395 2396 if (!__io_sqring_full(ctx)) 2397 mask |= EPOLLOUT | EPOLLWRNORM; 2398 2399 /* 2400 * Don't flush cqring overflow list here, just do a simple check. 2401 * Otherwise there could possible be ABBA deadlock: 2402 * CPU0 CPU1 2403 * ---- ---- 2404 * lock(&ctx->uring_lock); 2405 * lock(&ep->mtx); 2406 * lock(&ctx->uring_lock); 2407 * lock(&ep->mtx); 2408 * 2409 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this 2410 * pushes them to do the flush. 2411 */ 2412 2413 if (__io_cqring_events_user(ctx) || io_has_work(ctx)) 2414 mask |= EPOLLIN | EPOLLRDNORM; 2415 2416 rcu_read_unlock(); 2417 return mask; 2418 } 2419 2420 struct io_tctx_exit { 2421 struct callback_head task_work; 2422 struct completion completion; 2423 struct io_ring_ctx *ctx; 2424 bool in_cancel; 2425 }; 2426 2427 static __cold void io_tctx_exit_cb(struct callback_head *cb) 2428 { 2429 struct io_uring_task *tctx = current->io_uring; 2430 struct io_tctx_exit *work; 2431 2432 work = container_of(cb, struct io_tctx_exit, task_work); 2433 /* 2434 * When @in_cancel, we're in cancellation and it's racy to remove the 2435 * node. It'll be removed by the end of cancellation, just ignore it. 2436 * tctx can be NULL if the queueing of this task_work raced with 2437 * work cancelation off the exec path. 2438 */ 2439 work->in_cancel = tctx && atomic_read(&tctx->in_cancel); 2440 if (tctx && !work->in_cancel) 2441 io_uring_del_tctx_node((unsigned long)work->ctx); 2442 complete(&work->completion); 2443 } 2444 2445 /* 2446 * Cancel what can be canceled on a dying ring and reap what has completed. 2447 * Only waits on polled I/O, never anything else. 2448 */ 2449 static __cold void io_ring_ctx_cancel(struct io_ring_ctx *ctx) 2450 { 2451 struct io_sq_data *sqd = ctx->sq_data; 2452 2453 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) { 2454 scoped_guard(mutex, &ctx->uring_lock) 2455 io_cqring_overflow_kill(ctx); 2456 } 2457 2458 /* 2459 * If we're doing polled IO and end up having requests being 2460 * submitted async (out-of-line), then completions can come in while 2461 * we're waiting for refs to drop. We need to reap these manually, 2462 * as nobody else will be looking for them. 2463 */ 2464 do { 2465 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) 2466 io_cancel_local_task_work(ctx); 2467 cond_resched(); 2468 } while (io_uring_try_cancel_requests(ctx, NULL, IO_CANCEL_ALL)); 2469 2470 if (sqd) { 2471 struct task_struct *tsk; 2472 2473 io_sq_thread_park(sqd); 2474 tsk = sqpoll_task_locked(sqd); 2475 if (tsk && tsk->io_uring && tsk->io_uring->io_wq) 2476 io_wq_cancel_cb(tsk->io_uring->io_wq, 2477 io_cancel_ctx_cb, ctx, true); 2478 io_sq_thread_unpark(sqd); 2479 } 2480 2481 io_req_caches_free(ctx); 2482 } 2483 2484 /* Number of requests that should be waited for */ 2485 static __cold unsigned int io_ring_ctx_inflight(struct io_ring_ctx *ctx) 2486 { 2487 guard(mutex)(&ctx->uring_lock); 2488 __io_req_caches_free(ctx); 2489 return ctx->nr_req_allocated - ctx->nr_notifs; 2490 } 2491 2492 /* 2493 * Run task_work completions for current. Only do so if the io_uring callback 2494 * itself can get pruned first, otherwise we risk recursing. 2495 */ 2496 static __cold bool io_ring_run_own_completions(struct io_uring_task *tctx) 2497 { 2498 unsigned int count = 0; 2499 2500 if (!tctx || mpscq_empty(&tctx->task_list)) 2501 return true; 2502 if (!task_work_cancel(current, &tctx->task_work)) 2503 return false; 2504 tctx_task_work_run(tctx, UINT_MAX, &count); 2505 return true; 2506 } 2507 2508 /* 2509 * Requests may remain after cancelations have been run, as not all requests 2510 * are cancelable. Storage I/O is an example. Wait for those so that once 2511 * close(2) returns, files pinned by these requests have been released. 2512 */ 2513 static __cold void io_ring_ctx_wait_inflight(struct io_ring_ctx *ctx) 2514 { 2515 struct io_uring_task *tctx = current->io_uring; 2516 bool ran_own = true; 2517 2518 if (current->flags & (PF_KTHREAD | PF_EXITING)) 2519 return; 2520 if (tctx && atomic_read(&tctx->in_cancel)) 2521 return; 2522 2523 while (io_ring_ctx_inflight(ctx) && !fatal_signal_pending(current)) { 2524 unsigned int state; 2525 2526 if (test_thread_flag(TIF_NOTIFY_SIGNAL)) { 2527 clear_notify_signal(); 2528 if (task_work_pending(current)) 2529 set_notify_resume(current); 2530 } 2531 state = TASK_INTERRUPTIBLE; 2532 if (signal_pending(current)) 2533 state = TASK_KILLABLE; 2534 set_current_state(state | TASK_FREEZABLE); 2535 /* don't sleep on work that's already there and that we can run */ 2536 if (ran_own && ((tctx && !mpscq_empty(&tctx->task_list)) || 2537 io_local_work_pending(ctx))) 2538 __set_current_state(TASK_RUNNING); 2539 else 2540 schedule_timeout(1); 2541 2542 /* completions may be queued behind us */ 2543 if (!io_ring_run_own_completions(tctx)) { 2544 if (!ran_own) 2545 break; 2546 ran_own = false; 2547 } else { 2548 ran_own = true; 2549 } 2550 io_ring_ctx_cancel(ctx); 2551 } 2552 } 2553 2554 static __cold void io_ring_exit_work(struct work_struct *work) 2555 { 2556 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work); 2557 unsigned long timeout = jiffies + IO_URING_EXIT_WAIT_MAX; 2558 unsigned long interval = HZ / 20; 2559 struct io_tctx_exit exit; 2560 struct io_tctx_node *node; 2561 int ret; 2562 2563 do { 2564 io_ring_ctx_cancel(ctx); 2565 2566 if (WARN_ON_ONCE(time_after(jiffies, timeout))) { 2567 /* there is little hope left, don't run it too often */ 2568 interval = HZ * 60; 2569 } 2570 /* 2571 * This is really an uninterruptible wait, as it has to be 2572 * complete. But it's also run from a kworker, which doesn't 2573 * take signals, so it's fine to make it interruptible. This 2574 * avoids scenarios where we knowingly can wait much longer 2575 * on completions, for example if someone does a SIGSTOP on 2576 * a task that needs to finish task_work to make this loop 2577 * complete. That's a synthetic situation that should not 2578 * cause a stuck task backtrace, and hence a potential panic 2579 * on stuck tasks if that is enabled. 2580 */ 2581 } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval)); 2582 2583 init_completion(&exit.completion); 2584 init_task_work(&exit.task_work, io_tctx_exit_cb); 2585 exit.ctx = ctx; 2586 2587 mutex_lock(&ctx->uring_lock); 2588 mutex_lock(&ctx->tctx_lock); 2589 while (!list_empty(&ctx->tctx_list)) { 2590 WARN_ON_ONCE(time_after(jiffies, timeout)); 2591 2592 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node, 2593 ctx_node); 2594 /* don't spin on a single task if cancellation failed */ 2595 list_rotate_left(&ctx->tctx_list); 2596 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL); 2597 if (WARN_ON_ONCE(ret)) 2598 continue; 2599 2600 mutex_unlock(&ctx->tctx_lock); 2601 mutex_unlock(&ctx->uring_lock); 2602 /* 2603 * See comment above for 2604 * wait_for_completion_interruptible_timeout() on why this 2605 * wait is marked as interruptible. 2606 */ 2607 wait_for_completion_interruptible(&exit.completion); 2608 /* 2609 * The task removes the node when it is done with its 2610 * cancellation. Give it the time for that: it doesn't get back 2611 * to it as long as it finds new task_work each time it has run 2612 * the old one, and we may be one of many who send it. 2613 */ 2614 if (exit.in_cancel) 2615 schedule_timeout_idle(HZ / 20); 2616 mutex_lock(&ctx->uring_lock); 2617 mutex_lock(&ctx->tctx_lock); 2618 } 2619 mutex_unlock(&ctx->tctx_lock); 2620 mutex_unlock(&ctx->uring_lock); 2621 spin_lock(&ctx->completion_lock); 2622 spin_unlock(&ctx->completion_lock); 2623 2624 /* pairs with the RCU read sections in the task_work add paths */ 2625 if (ctx->flags & (IORING_SETUP_DEFER_TASKRUN | IORING_SETUP_SQPOLL)) 2626 synchronize_rcu(); 2627 2628 io_ring_ctx_free(ctx); 2629 } 2630 2631 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx) 2632 { 2633 unsigned long index; 2634 struct cred *creds; 2635 2636 mutex_lock(&ctx->uring_lock); 2637 percpu_ref_kill(&ctx->refs); 2638 xa_for_each(&ctx->personalities, index, creds) 2639 io_unregister_personality(ctx, index); 2640 io_terminate_zcrx(ctx); 2641 /* Drop these now, rather than async, to unpin the files */ 2642 io_sqe_buffers_unregister(ctx); 2643 io_sqe_files_unregister(ctx); 2644 mutex_unlock(&ctx->uring_lock); 2645 2646 /* 2647 * Do the first round of cancelations upfront rather than leaving it 2648 * to to exit_work. Anything cancelable is then already on its way 2649 * out, and for requests owned by the task closing the ring, this 2650 * ensures any held files are put before close(2) returns. 2651 */ 2652 if (!(current->flags & PF_IO_WORKER)) { 2653 io_ring_ctx_cancel(ctx); 2654 io_ring_ctx_wait_inflight(ctx); 2655 } 2656 2657 INIT_WORK(&ctx->exit_work, io_ring_exit_work); 2658 /* 2659 * Use system_dfl_wq to avoid spawning tons of event kworkers 2660 * if we're exiting a ton of rings at the same time. It just adds 2661 * noise and overhead, there's no discernable change in runtime 2662 * over using system_percpu_wq. 2663 */ 2664 queue_work(iou_wq, &ctx->exit_work); 2665 } 2666 2667 static int io_uring_release(struct inode *inode, struct file *file) 2668 { 2669 struct io_ring_ctx *ctx = file->private_data; 2670 2671 file->private_data = NULL; 2672 io_ring_ctx_wait_and_kill(ctx); 2673 return 0; 2674 } 2675 2676 static struct io_uring_reg_wait *io_get_ext_arg_reg(struct io_ring_ctx *ctx, 2677 const struct io_uring_getevents_arg __user *uarg) 2678 { 2679 unsigned long size = sizeof(struct io_uring_reg_wait); 2680 unsigned long offset = (uintptr_t)uarg; 2681 unsigned long end; 2682 2683 if (unlikely(offset % sizeof(long))) 2684 return ERR_PTR(-EFAULT); 2685 2686 /* also protects from NULL ->cq_wait_arg as the size would be 0 */ 2687 if (unlikely(check_add_overflow(offset, size, &end) || 2688 end > ctx->cq_wait_size)) 2689 return ERR_PTR(-EFAULT); 2690 2691 offset = array_index_nospec(offset, ctx->cq_wait_size - size); 2692 return ctx->cq_wait_arg + offset; 2693 } 2694 2695 static int io_validate_ext_arg(struct io_ring_ctx *ctx, unsigned flags, 2696 const void __user *argp, size_t argsz) 2697 { 2698 struct io_uring_getevents_arg arg; 2699 2700 if (!(flags & IORING_ENTER_EXT_ARG)) 2701 return 0; 2702 if (flags & IORING_ENTER_EXT_ARG_REG) 2703 return -EINVAL; 2704 if (argsz != sizeof(arg)) 2705 return -EINVAL; 2706 if (copy_from_user(&arg, argp, sizeof(arg))) 2707 return -EFAULT; 2708 return 0; 2709 } 2710 2711 static int io_get_ext_arg(struct io_ring_ctx *ctx, unsigned flags, 2712 const void __user *argp, struct ext_arg *ext_arg) 2713 { 2714 const struct io_uring_getevents_arg __user *uarg = argp; 2715 struct io_uring_getevents_arg arg; 2716 2717 ext_arg->iowait = !(flags & IORING_ENTER_NO_IOWAIT); 2718 2719 /* 2720 * If EXT_ARG isn't set, then we have no timespec and the argp pointer 2721 * is just a pointer to the sigset_t. 2722 */ 2723 if (!(flags & IORING_ENTER_EXT_ARG)) { 2724 ext_arg->sig = (const sigset_t __user *) argp; 2725 return 0; 2726 } 2727 2728 if (flags & IORING_ENTER_EXT_ARG_REG) { 2729 struct io_uring_reg_wait *w; 2730 2731 if (ext_arg->argsz != sizeof(struct io_uring_reg_wait)) 2732 return -EINVAL; 2733 w = io_get_ext_arg_reg(ctx, argp); 2734 if (IS_ERR(w)) 2735 return PTR_ERR(w); 2736 2737 if (w->flags & ~IORING_REG_WAIT_TS) 2738 return -EINVAL; 2739 ext_arg->min_time = READ_ONCE(w->min_wait_usec) * NSEC_PER_USEC; 2740 ext_arg->sig = u64_to_user_ptr(READ_ONCE(w->sigmask)); 2741 ext_arg->argsz = READ_ONCE(w->sigmask_sz); 2742 if (w->flags & IORING_REG_WAIT_TS) { 2743 ext_arg->ts.tv_sec = READ_ONCE(w->ts.tv_sec); 2744 ext_arg->ts.tv_nsec = READ_ONCE(w->ts.tv_nsec); 2745 ext_arg->ts_set = true; 2746 } 2747 return 0; 2748 } 2749 2750 /* 2751 * EXT_ARG is set - ensure we agree on the size of it and copy in our 2752 * timespec and sigset_t pointers if good. 2753 */ 2754 if (ext_arg->argsz != sizeof(arg)) 2755 return -EINVAL; 2756 #ifdef CONFIG_64BIT 2757 if (!user_access_begin(uarg, sizeof(*uarg))) 2758 return -EFAULT; 2759 unsafe_get_user(arg.sigmask, &uarg->sigmask, uaccess_end); 2760 unsafe_get_user(arg.sigmask_sz, &uarg->sigmask_sz, uaccess_end); 2761 unsafe_get_user(arg.min_wait_usec, &uarg->min_wait_usec, uaccess_end); 2762 unsafe_get_user(arg.ts, &uarg->ts, uaccess_end); 2763 user_access_end(); 2764 #else 2765 if (copy_from_user(&arg, uarg, sizeof(arg))) 2766 return -EFAULT; 2767 #endif 2768 ext_arg->min_time = arg.min_wait_usec * NSEC_PER_USEC; 2769 ext_arg->sig = u64_to_user_ptr(arg.sigmask); 2770 ext_arg->argsz = arg.sigmask_sz; 2771 if (arg.ts) { 2772 if (get_timespec64(&ext_arg->ts, u64_to_user_ptr(arg.ts))) 2773 return -EFAULT; 2774 ext_arg->ts_set = true; 2775 } 2776 return 0; 2777 #ifdef CONFIG_64BIT 2778 uaccess_end: 2779 user_access_end(); 2780 return -EFAULT; 2781 #endif 2782 } 2783 2784 /* 2785 * Given an 'fd' value, return the ctx associated with if. If 'registered' is 2786 * true, then the registered index is used. Otherwise, the normal fd table. 2787 * Caller must call fput() on the returned file if it isn't a registered file, 2788 * unless it's an ERR_PTR. 2789 */ 2790 struct file *io_uring_ctx_get_file(unsigned int fd, bool registered) 2791 { 2792 struct file *file; 2793 2794 if (registered) { 2795 /* 2796 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we 2797 * need only dereference our task private array to find it. 2798 */ 2799 struct io_uring_task *tctx = current->io_uring; 2800 2801 if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX)) 2802 return ERR_PTR(-EINVAL); 2803 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX); 2804 file = tctx->registered_rings[fd]; 2805 } else { 2806 file = fget(fd); 2807 } 2808 2809 if (unlikely(!file)) 2810 return ERR_PTR(-EBADF); 2811 if (io_is_uring_fops(file)) 2812 return file; 2813 if (!registered) 2814 fput(file); 2815 return ERR_PTR(-EOPNOTSUPP); 2816 } 2817 2818 2819 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit, 2820 u32, min_complete, u32, flags, const void __user *, argp, 2821 size_t, argsz) 2822 { 2823 struct io_ring_ctx *ctx; 2824 struct file *file; 2825 long ret; 2826 2827 if (unlikely(flags & ~IORING_ENTER_FLAGS)) 2828 return -EINVAL; 2829 2830 file = io_uring_ctx_get_file(fd, flags & IORING_ENTER_REGISTERED_RING); 2831 if (IS_ERR(file)) 2832 return PTR_ERR(file); 2833 ctx = file->private_data; 2834 ret = -EBADFD; 2835 /* 2836 * Keep IORING_SETUP_R_DISABLED check before submitter_task load 2837 * in io_uring_add_tctx_node() -> __io_uring_add_tctx_node_from_submit() 2838 */ 2839 if (unlikely(smp_load_acquire(&ctx->flags) & IORING_SETUP_R_DISABLED)) 2840 goto out; 2841 2842 if (io_has_loop_ops(ctx)) { 2843 ret = io_run_loop(ctx); 2844 goto out; 2845 } 2846 2847 /* 2848 * For SQ polling, the thread will do all submissions and completions. 2849 * Just return the requested submit count, and wake the thread if 2850 * we were asked to. 2851 */ 2852 ret = 0; 2853 if (ctx->flags & IORING_SETUP_SQPOLL) { 2854 if (unlikely(ctx->sq_data->thread == NULL)) { 2855 ret = -EOWNERDEAD; 2856 goto out; 2857 } 2858 if (flags & IORING_ENTER_SQ_WAKEUP) 2859 wake_up(&ctx->sq_data->wait); 2860 if (flags & IORING_ENTER_SQ_WAIT) 2861 io_sqpoll_wait_sq(ctx); 2862 2863 ret = to_submit; 2864 } else if (to_submit) { 2865 ret = io_uring_add_tctx_node(ctx); 2866 if (unlikely(ret)) 2867 goto out; 2868 2869 mutex_lock(&ctx->uring_lock); 2870 ret = io_submit_sqes(ctx, to_submit); 2871 if (ret != to_submit) { 2872 mutex_unlock(&ctx->uring_lock); 2873 goto out; 2874 } 2875 if (flags & IORING_ENTER_GETEVENTS) { 2876 if (ctx->int_flags & IO_RING_F_SYSCALL_IOPOLL) 2877 goto iopoll_locked; 2878 /* 2879 * Ignore errors, we'll soon call io_cqring_wait() and 2880 * it should handle ownership problems if any. 2881 */ 2882 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) 2883 (void)io_run_local_work_locked(ctx, min_complete); 2884 } 2885 mutex_unlock(&ctx->uring_lock); 2886 } 2887 2888 if (flags & IORING_ENTER_GETEVENTS) { 2889 int ret2; 2890 2891 if (ctx->int_flags & IO_RING_F_SYSCALL_IOPOLL) { 2892 /* 2893 * We disallow the app entering submit/complete with 2894 * polling, but we still need to lock the ring to 2895 * prevent racing with polled issue that got punted to 2896 * a workqueue. 2897 */ 2898 mutex_lock(&ctx->uring_lock); 2899 iopoll_locked: 2900 ret2 = io_validate_ext_arg(ctx, flags, argp, argsz); 2901 if (likely(!ret2)) 2902 ret2 = io_iopoll_check(ctx, min_complete); 2903 mutex_unlock(&ctx->uring_lock); 2904 } else { 2905 struct ext_arg ext_arg = { .argsz = argsz }; 2906 2907 ret2 = io_get_ext_arg(ctx, flags, argp, &ext_arg); 2908 if (likely(!ret2)) 2909 ret2 = io_cqring_wait(ctx, min_complete, flags, 2910 &ext_arg); 2911 } 2912 2913 if (!ret) { 2914 ret = ret2; 2915 2916 /* 2917 * EBADR indicates that one or more CQE were dropped. 2918 * Once the user has been informed we can clear the bit 2919 * as they are obviously ok with those drops. 2920 */ 2921 if (unlikely(ret2 == -EBADR)) 2922 clear_bit(IO_CHECK_CQ_DROPPED_BIT, 2923 &ctx->check_cq); 2924 } 2925 } 2926 out: 2927 if (!(flags & IORING_ENTER_REGISTERED_RING)) 2928 fput(file); 2929 return ret; 2930 } 2931 2932 static const struct file_operations io_uring_fops = { 2933 .release = io_uring_release, 2934 .mmap = io_uring_mmap, 2935 .get_unmapped_area = io_uring_get_unmapped_area, 2936 #ifndef CONFIG_MMU 2937 .mmap_capabilities = io_uring_nommu_mmap_capabilities, 2938 #endif 2939 .poll = io_uring_poll, 2940 #ifdef CONFIG_PROC_FS 2941 .show_fdinfo = io_uring_show_fdinfo, 2942 #endif 2943 }; 2944 2945 bool io_is_uring_fops(struct file *file) 2946 { 2947 return file->f_op == &io_uring_fops; 2948 } 2949 2950 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx, 2951 struct io_ctx_config *config) 2952 { 2953 struct io_uring_params *p = &config->p; 2954 struct io_rings_layout *rl = &config->layout; 2955 struct io_uring_region_desc rd; 2956 struct io_rings *rings; 2957 int ret; 2958 2959 /* make sure these are sane, as we already accounted them */ 2960 ctx->sq_entries = p->sq_entries; 2961 ctx->cq_entries = p->cq_entries; 2962 2963 memset(&rd, 0, sizeof(rd)); 2964 rd.size = PAGE_ALIGN(rl->rings_size); 2965 if (ctx->flags & IORING_SETUP_NO_MMAP) { 2966 rd.user_addr = p->cq_off.user_addr; 2967 rd.flags |= IORING_MEM_REGION_TYPE_USER; 2968 } 2969 /* ring memory is not charged to RLIMIT_MEMLOCK, hence no user */ 2970 ret = io_create_region(NULL, &ctx->ring_region, &rd, IORING_OFF_CQ_RING); 2971 if (ret) 2972 return ret; 2973 ctx->rings = rings = io_region_get_ptr(&ctx->ring_region); 2974 rcu_assign_pointer(ctx->rings_rcu, rings); 2975 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY)) 2976 ctx->sq_array = (u32 *)((char *)rings + rl->sq_array_offset); 2977 2978 memset(&rd, 0, sizeof(rd)); 2979 rd.size = PAGE_ALIGN(rl->sq_size); 2980 if (ctx->flags & IORING_SETUP_NO_MMAP) { 2981 rd.user_addr = p->sq_off.user_addr; 2982 rd.flags |= IORING_MEM_REGION_TYPE_USER; 2983 } 2984 ret = io_create_region(NULL, &ctx->sq_region, &rd, IORING_OFF_SQES); 2985 if (ret) { 2986 io_rings_free(ctx); 2987 return ret; 2988 } 2989 ctx->sq_sqes = io_region_get_ptr(&ctx->sq_region); 2990 2991 memset(rings, 0, sizeof(*rings)); 2992 WRITE_ONCE(rings->sq_ring_mask, ctx->sq_entries - 1); 2993 WRITE_ONCE(rings->cq_ring_mask, ctx->cq_entries - 1); 2994 WRITE_ONCE(rings->sq_ring_entries, ctx->sq_entries); 2995 WRITE_ONCE(rings->cq_ring_entries, ctx->cq_entries); 2996 return 0; 2997 } 2998 2999 static int io_uring_install_fd(struct file *file) 3000 { 3001 int fd; 3002 3003 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC); 3004 if (fd < 0) 3005 return fd; 3006 fd_install(fd, file); 3007 return fd; 3008 } 3009 3010 /* 3011 * Allocate an anonymous fd, this is what constitutes the application 3012 * visible backing of an io_uring instance. The application mmaps this 3013 * fd to gain access to the SQ/CQ ring details. 3014 */ 3015 static struct file *io_uring_get_file(struct io_ring_ctx *ctx) 3016 { 3017 /* Create a new inode so that the LSM can block the creation. */ 3018 return anon_inode_create_getfile("[io_uring]", &io_uring_fops, ctx, 3019 O_RDWR | O_CLOEXEC, NULL); 3020 } 3021 3022 static int io_uring_sanitise_params(struct io_uring_params *p) 3023 { 3024 unsigned flags = p->flags; 3025 3026 if (flags & ~IORING_SETUP_FLAGS) 3027 return -EINVAL; 3028 3029 if (flags & IORING_SETUP_SQ_REWIND) { 3030 if ((flags & IORING_SETUP_SQPOLL) || 3031 !(flags & IORING_SETUP_NO_SQARRAY)) 3032 return -EINVAL; 3033 } 3034 3035 /* There is no way to mmap rings without a real fd */ 3036 if ((flags & IORING_SETUP_REGISTERED_FD_ONLY) && 3037 !(flags & IORING_SETUP_NO_MMAP)) 3038 return -EINVAL; 3039 3040 if (flags & IORING_SETUP_SQPOLL) { 3041 /* IPI related flags don't make sense with SQPOLL */ 3042 if (flags & (IORING_SETUP_COOP_TASKRUN | 3043 IORING_SETUP_TASKRUN_FLAG | 3044 IORING_SETUP_DEFER_TASKRUN)) 3045 return -EINVAL; 3046 } 3047 3048 if (flags & IORING_SETUP_TASKRUN_FLAG) { 3049 if (!(flags & (IORING_SETUP_COOP_TASKRUN | 3050 IORING_SETUP_DEFER_TASKRUN))) 3051 return -EINVAL; 3052 } 3053 3054 /* HYBRID_IOPOLL only valid with IOPOLL */ 3055 if ((flags & IORING_SETUP_HYBRID_IOPOLL) && !(flags & IORING_SETUP_IOPOLL)) 3056 return -EINVAL; 3057 3058 /* 3059 * For DEFER_TASKRUN we require the completion task to be the same as 3060 * the submission task. This implies that there is only one submitter. 3061 */ 3062 if ((flags & IORING_SETUP_DEFER_TASKRUN) && 3063 !(flags & IORING_SETUP_SINGLE_ISSUER)) 3064 return -EINVAL; 3065 3066 /* 3067 * Nonsensical to ask for CQE32 and mixed CQE support, it's not 3068 * supported to post 16b CQEs on a ring setup with CQE32. 3069 */ 3070 if ((flags & (IORING_SETUP_CQE32|IORING_SETUP_CQE_MIXED)) == 3071 (IORING_SETUP_CQE32|IORING_SETUP_CQE_MIXED)) 3072 return -EINVAL; 3073 /* 3074 * Nonsensical to ask for SQE128 and mixed SQE support, it's not 3075 * supported to post 64b SQEs on a ring setup with SQE128. 3076 */ 3077 if ((flags & (IORING_SETUP_SQE128|IORING_SETUP_SQE_MIXED)) == 3078 (IORING_SETUP_SQE128|IORING_SETUP_SQE_MIXED)) 3079 return -EINVAL; 3080 3081 return 0; 3082 } 3083 3084 static int io_uring_fill_params(struct io_uring_params *p) 3085 { 3086 unsigned entries = p->sq_entries; 3087 3088 if (!entries) 3089 return -EINVAL; 3090 if (entries > IORING_MAX_ENTRIES) { 3091 if (!(p->flags & IORING_SETUP_CLAMP)) 3092 return -EINVAL; 3093 entries = IORING_MAX_ENTRIES; 3094 } 3095 3096 /* 3097 * Use twice as many entries for the CQ ring. It's possible for the 3098 * application to drive a higher depth than the size of the SQ ring, 3099 * since the sqes are only used at submission time. This allows for 3100 * some flexibility in overcommitting a bit. If the application has 3101 * set IORING_SETUP_CQSIZE, it will have passed in the desired number 3102 * of CQ ring entries manually. 3103 */ 3104 p->sq_entries = roundup_pow_of_two(entries); 3105 if (p->flags & IORING_SETUP_CQSIZE) { 3106 /* 3107 * If IORING_SETUP_CQSIZE is set, we do the same roundup 3108 * to a power-of-two, if it isn't already. We do NOT impose 3109 * any cq vs sq ring sizing. 3110 */ 3111 if (!p->cq_entries) 3112 return -EINVAL; 3113 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) { 3114 if (!(p->flags & IORING_SETUP_CLAMP)) 3115 return -EINVAL; 3116 p->cq_entries = IORING_MAX_CQ_ENTRIES; 3117 } 3118 p->cq_entries = roundup_pow_of_two(p->cq_entries); 3119 if (p->cq_entries < p->sq_entries) 3120 return -EINVAL; 3121 } else { 3122 p->cq_entries = 2 * p->sq_entries; 3123 } 3124 3125 return 0; 3126 } 3127 3128 int io_prepare_config(struct io_ctx_config *config) 3129 { 3130 struct io_uring_params *p = &config->p; 3131 int ret; 3132 3133 ret = io_uring_sanitise_params(p); 3134 if (ret) 3135 return ret; 3136 3137 ret = io_uring_fill_params(p); 3138 if (ret) 3139 return ret; 3140 3141 ret = rings_size(p->flags, p->sq_entries, p->cq_entries, 3142 &config->layout); 3143 if (ret) 3144 return ret; 3145 3146 p->sq_off.head = offsetof(struct io_rings, sq.head); 3147 p->sq_off.tail = offsetof(struct io_rings, sq.tail); 3148 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask); 3149 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries); 3150 p->sq_off.flags = offsetof(struct io_rings, sq_flags); 3151 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped); 3152 p->sq_off.resv1 = 0; 3153 if (!(p->flags & IORING_SETUP_NO_MMAP)) 3154 p->sq_off.user_addr = 0; 3155 3156 p->cq_off.head = offsetof(struct io_rings, cq.head); 3157 p->cq_off.tail = offsetof(struct io_rings, cq.tail); 3158 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask); 3159 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries); 3160 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow); 3161 p->cq_off.cqes = offsetof(struct io_rings, cqes); 3162 p->cq_off.flags = offsetof(struct io_rings, cq_flags); 3163 p->cq_off.resv1 = 0; 3164 if (!(p->flags & IORING_SETUP_NO_MMAP)) 3165 p->cq_off.user_addr = 0; 3166 if (!(p->flags & IORING_SETUP_NO_SQARRAY)) 3167 p->sq_off.array = config->layout.sq_array_offset; 3168 3169 return 0; 3170 } 3171 3172 void io_restriction_clone(struct io_restriction *dst, struct io_restriction *src) 3173 { 3174 memcpy(&dst->register_op, &src->register_op, sizeof(dst->register_op)); 3175 memcpy(&dst->sqe_op, &src->sqe_op, sizeof(dst->sqe_op)); 3176 dst->sqe_flags_allowed = src->sqe_flags_allowed; 3177 dst->sqe_flags_required = src->sqe_flags_required; 3178 dst->op_registered = src->op_registered; 3179 dst->reg_registered = src->reg_registered; 3180 3181 io_bpf_filter_clone(dst, src); 3182 } 3183 3184 static void io_ctx_restriction_clone(struct io_ring_ctx *ctx, 3185 struct io_restriction *src) 3186 { 3187 struct io_restriction *dst = &ctx->restrictions; 3188 3189 io_restriction_clone(dst, src); 3190 if (dst->bpf_filters) 3191 WRITE_ONCE(ctx->bpf_filters, dst->bpf_filters->filters); 3192 if (dst->op_registered) 3193 ctx->int_flags |= IO_RING_F_OP_RESTRICTED; 3194 if (dst->reg_registered) 3195 ctx->int_flags |= IO_RING_F_REG_RESTRICTED | 3196 IO_RING_F_RESTRICT_INHERITED; 3197 } 3198 3199 static __cold int io_uring_create(struct io_ctx_config *config) 3200 { 3201 struct io_uring_params *p = &config->p; 3202 struct io_ring_ctx *ctx; 3203 struct io_uring_task *tctx; 3204 struct file *file; 3205 int ret; 3206 3207 ret = io_prepare_config(config); 3208 if (ret) 3209 return ret; 3210 3211 ctx = io_ring_ctx_alloc(p); 3212 if (!ctx) 3213 return -ENOMEM; 3214 3215 ctx->clockid = CLOCK_MONOTONIC; 3216 ctx->clock_offset = 0; 3217 3218 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY)) 3219 static_branch_deferred_inc(&io_key_has_sqarray); 3220 3221 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) && 3222 !(ctx->flags & IORING_SETUP_IOPOLL)) 3223 ctx->int_flags |= IO_RING_F_TASK_COMPLETE; 3224 3225 if ((ctx->int_flags & IO_RING_F_TASK_COMPLETE) || 3226 (ctx->flags & IORING_SETUP_IOPOLL)) 3227 ctx->int_flags |= IO_RING_F_LOCKLESS_CQ; 3228 3229 /* 3230 * lazy poll_wq activation relies on ->task_complete for synchronisation 3231 * purposes, see io_activate_pollwq() 3232 */ 3233 if (!(ctx->int_flags & IO_RING_F_TASK_COMPLETE)) 3234 ctx->int_flags |= IO_RING_F_POLL_ACTIVATED; 3235 3236 /* 3237 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user 3238 * space applications don't need to do io completion events 3239 * polling again, they can rely on io_sq_thread to do polling 3240 * work, which can reduce cpu usage and uring_lock contention. 3241 */ 3242 if (ctx->flags & IORING_SETUP_IOPOLL && 3243 !(ctx->flags & IORING_SETUP_SQPOLL)) 3244 ctx->int_flags |= IO_RING_F_SYSCALL_IOPOLL; 3245 3246 if (in_compat_syscall()) 3247 ctx->int_flags |= IO_RING_F_COMPAT; 3248 if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK)) 3249 ctx->user = get_uid(current_user()); 3250 3251 /* 3252 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if 3253 * COOP_TASKRUN is set, then IPIs are never needed by the app. 3254 */ 3255 if (ctx->flags & (IORING_SETUP_SQPOLL|IORING_SETUP_COOP_TASKRUN)) 3256 ctx->notify_method = TWA_SIGNAL_NO_IPI; 3257 else 3258 ctx->notify_method = TWA_SIGNAL; 3259 3260 /* 3261 * If the current task has restrictions enabled, then copy them to 3262 * our newly created ring and mark it as registered. 3263 */ 3264 if (current->io_uring_restrict) 3265 io_ctx_restriction_clone(ctx, current->io_uring_restrict); 3266 3267 /* 3268 * This is just grabbed for accounting purposes. When a process exits, 3269 * the mm is exited and dropped before the files, hence we need to hang 3270 * on to this mm purely for the purposes of being able to unaccount 3271 * memory (locked/pinned vm). It's not used for anything else. 3272 */ 3273 mmgrab(current->mm); 3274 ctx->mm_account = current->mm; 3275 3276 ret = io_allocate_scq_urings(ctx, config); 3277 if (ret) 3278 goto err; 3279 3280 ret = io_sq_offload_create(ctx, p); 3281 if (ret) 3282 goto err; 3283 3284 p->features = IORING_FEAT_FLAGS; 3285 3286 if (copy_to_user(config->uptr, p, sizeof(*p))) { 3287 ret = -EFAULT; 3288 goto err; 3289 } 3290 3291 if (ctx->flags & IORING_SETUP_SINGLE_ISSUER 3292 && !(ctx->flags & IORING_SETUP_R_DISABLED)) 3293 ctx->submitter_task = get_task_struct(current); 3294 3295 file = io_uring_get_file(ctx); 3296 if (IS_ERR(file)) { 3297 ret = PTR_ERR(file); 3298 goto err; 3299 } 3300 3301 ret = __io_uring_add_tctx_node(ctx); 3302 if (ret) 3303 goto err_fput; 3304 tctx = current->io_uring; 3305 3306 /* 3307 * Install ring fd as the very last thing, so we don't risk someone 3308 * having closed it before we finish setup 3309 */ 3310 if (p->flags & IORING_SETUP_REGISTERED_FD_ONLY) 3311 ret = io_ring_add_registered_file(tctx, file, 0, IO_RINGFD_REG_MAX); 3312 else 3313 ret = io_uring_install_fd(file); 3314 if (ret < 0) 3315 goto err_fput; 3316 3317 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags); 3318 return ret; 3319 err: 3320 io_ring_ctx_wait_and_kill(ctx); 3321 return ret; 3322 err_fput: 3323 fput(file); 3324 return ret; 3325 } 3326 3327 /* 3328 * Sets up an aio uring context, and returns the fd. Applications asks for a 3329 * ring size, we return the actual sq/cq ring sizes (among other things) in the 3330 * params structure passed in. 3331 */ 3332 static long io_uring_setup(u32 entries, struct io_uring_params __user *params) 3333 { 3334 struct io_ctx_config config; 3335 3336 memset(&config, 0, sizeof(config)); 3337 3338 if (copy_from_user(&config.p, params, sizeof(config.p))) 3339 return -EFAULT; 3340 3341 if (!mem_is_zero(&config.p.resv, sizeof(config.p.resv))) 3342 return -EINVAL; 3343 3344 config.p.sq_entries = entries; 3345 config.uptr = params; 3346 return io_uring_create(&config); 3347 } 3348 3349 static inline int io_uring_allowed(void) 3350 { 3351 int disabled = READ_ONCE(sysctl_io_uring_disabled); 3352 kgid_t io_uring_group; 3353 3354 if (disabled == 2) 3355 return -EPERM; 3356 3357 if (disabled == 0 || capable(CAP_SYS_ADMIN)) 3358 goto allowed_lsm; 3359 3360 io_uring_group = make_kgid(&init_user_ns, sysctl_io_uring_group); 3361 if (!gid_valid(io_uring_group)) 3362 return -EPERM; 3363 3364 if (!in_group_p(io_uring_group)) 3365 return -EPERM; 3366 3367 allowed_lsm: 3368 return security_uring_allowed(); 3369 } 3370 3371 SYSCALL_DEFINE2(io_uring_setup, u32, entries, 3372 struct io_uring_params __user *, params) 3373 { 3374 int ret; 3375 3376 ret = io_uring_allowed(); 3377 if (ret) 3378 return ret; 3379 3380 return io_uring_setup(entries, params); 3381 } 3382 3383 static int __init io_uring_init(void) 3384 { 3385 struct kmem_cache_args kmem_args = { 3386 .useroffset = offsetof(struct io_kiocb, cmd.data), 3387 .usersize = sizeof_field(struct io_kiocb, cmd.data), 3388 .freeptr_offset = offsetof(struct io_kiocb, work), 3389 .use_freeptr_offset = true, 3390 }; 3391 3392 #define __BUILD_BUG_VERIFY_OFFSET_SIZE(stype, eoffset, esize, ename) do { \ 3393 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \ 3394 BUILD_BUG_ON(sizeof_field(stype, ename) != esize); \ 3395 } while (0) 3396 3397 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \ 3398 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, sizeof(etype), ename) 3399 #define BUILD_BUG_SQE_ELEM_SIZE(eoffset, esize, ename) \ 3400 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, esize, ename) 3401 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64); 3402 BUILD_BUG_SQE_ELEM(0, __u8, opcode); 3403 BUILD_BUG_SQE_ELEM(1, __u8, flags); 3404 BUILD_BUG_SQE_ELEM(2, __u16, ioprio); 3405 BUILD_BUG_SQE_ELEM(4, __s32, fd); 3406 BUILD_BUG_SQE_ELEM(8, __u64, off); 3407 BUILD_BUG_SQE_ELEM(8, __u64, addr2); 3408 BUILD_BUG_SQE_ELEM(8, __u32, cmd_op); 3409 BUILD_BUG_SQE_ELEM(12, __u32, __pad1); 3410 BUILD_BUG_SQE_ELEM(16, __u64, addr); 3411 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in); 3412 BUILD_BUG_SQE_ELEM(24, __u32, len); 3413 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags); 3414 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags); 3415 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags); 3416 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags); 3417 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events); 3418 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events); 3419 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags); 3420 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags); 3421 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags); 3422 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags); 3423 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags); 3424 BUILD_BUG_SQE_ELEM(28, __u32, open_flags); 3425 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags); 3426 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice); 3427 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags); 3428 BUILD_BUG_SQE_ELEM(28, __u32, rename_flags); 3429 BUILD_BUG_SQE_ELEM(28, __u32, unlink_flags); 3430 BUILD_BUG_SQE_ELEM(28, __u32, hardlink_flags); 3431 BUILD_BUG_SQE_ELEM(28, __u32, xattr_flags); 3432 BUILD_BUG_SQE_ELEM(28, __u32, msg_ring_flags); 3433 BUILD_BUG_SQE_ELEM(32, __u64, user_data); 3434 BUILD_BUG_SQE_ELEM(40, __u16, buf_index); 3435 BUILD_BUG_SQE_ELEM(40, __u16, buf_group); 3436 BUILD_BUG_SQE_ELEM(42, __u16, personality); 3437 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in); 3438 BUILD_BUG_SQE_ELEM(44, __u32, file_index); 3439 BUILD_BUG_SQE_ELEM(44, __u16, addr_len); 3440 BUILD_BUG_SQE_ELEM(44, __u8, write_stream); 3441 BUILD_BUG_SQE_ELEM(45, __u8, __pad4[0]); 3442 BUILD_BUG_SQE_ELEM(46, __u16, __pad3[0]); 3443 BUILD_BUG_SQE_ELEM(48, __u64, addr3); 3444 BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd); 3445 BUILD_BUG_SQE_ELEM(48, __u64, attr_ptr); 3446 BUILD_BUG_SQE_ELEM(56, __u64, attr_type_mask); 3447 BUILD_BUG_SQE_ELEM(56, __u64, __pad2); 3448 3449 BUILD_BUG_ON(sizeof(struct io_uring_files_update) != 3450 sizeof(struct io_uring_rsrc_update)); 3451 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) > 3452 sizeof(struct io_uring_rsrc_update2)); 3453 3454 /* ->buf_index is u16 */ 3455 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0); 3456 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) != 3457 offsetof(struct io_uring_buf_ring, tail)); 3458 3459 /* should fit into one byte */ 3460 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8)); 3461 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8)); 3462 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS); 3463 3464 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof_field(struct io_kiocb, flags)); 3465 3466 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32)); 3467 3468 /* top 8bits are for internal use */ 3469 BUILD_BUG_ON((IORING_URING_CMD_MASK & 0xff000000) != 0); 3470 3471 io_uring_optable_init(); 3472 3473 /* imu->dir is u8 */ 3474 BUILD_BUG_ON((IO_BUF_DEST | IO_BUF_SOURCE) > U8_MAX); 3475 3476 /* 3477 * Allow user copy in the per-command field, which starts after the 3478 * file in io_kiocb and until the opcode field. The openat2 handling 3479 * requires copying in user memory into the io_kiocb object in that 3480 * range, and HARDENED_USERCOPY will complain if we haven't 3481 * correctly annotated this range. 3482 */ 3483 req_cachep = kmem_cache_create("io_kiocb", sizeof(struct io_kiocb), &kmem_args, 3484 SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT | 3485 SLAB_TYPESAFE_BY_RCU); 3486 3487 iou_wq = alloc_workqueue("iou_exit", WQ_UNBOUND, 64); 3488 BUG_ON(!iou_wq); 3489 3490 #ifdef CONFIG_SYSCTL 3491 register_sysctl_init("kernel", kernel_io_uring_disabled_table); 3492 #endif 3493 3494 return 0; 3495 }; 3496 __initcall(io_uring_init); 3497