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