1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/kernel.h>
3 #include <linux/errno.h>
4 #include <linux/file.h>
6 #include <linux/slab.h>
7 #include <linux/nospec.h>
8 #include <linux/io_uring.h>
10 #include <uapi/linux/io_uring.h>
14 #include "filetable.h"
16 static int io_file_bitmap_get(struct io_ring_ctx *ctx)
18 struct io_file_table *table = &ctx->file_table;
19 unsigned long nr = ctx->nr_user_files;
23 ret = find_next_zero_bit(table->bitmap, nr, table->alloc_hint);
27 if (!table->alloc_hint)
30 nr = table->alloc_hint;
31 table->alloc_hint = 0;
37 bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
39 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
41 if (unlikely(!table->files))
44 table->bitmap = bitmap_zalloc(nr_files, GFP_KERNEL_ACCOUNT);
45 if (unlikely(!table->bitmap)) {
53 void io_free_file_tables(struct io_file_table *table)
56 bitmap_free(table->bitmap);
61 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
62 unsigned int issue_flags, u32 slot_index)
63 __must_hold(&req->ctx->uring_lock)
65 struct io_ring_ctx *ctx = req->ctx;
66 bool needs_switch = false;
67 struct io_fixed_file *file_slot;
70 if (io_is_uring_fops(file))
74 if (slot_index >= ctx->nr_user_files)
77 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
78 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
80 if (file_slot->file_ptr) {
81 struct file *old_file;
83 ret = io_rsrc_node_switch_start(ctx);
87 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
88 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
89 ctx->rsrc_node, old_file);
92 file_slot->file_ptr = 0;
93 io_file_bitmap_clear(&ctx->file_table, slot_index);
97 ret = io_scm_file_account(ctx, file);
99 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
100 io_fixed_file_set(file_slot, file);
101 io_file_bitmap_set(&ctx->file_table, slot_index);
105 io_rsrc_node_switch(ctx, ctx->file_data);
112 * Note when io_fixed_fd_install() returns error value, it will ensure
113 * fput() is called correspondingly.
115 int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
116 struct file *file, unsigned int file_slot)
118 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
119 struct io_ring_ctx *ctx = req->ctx;
122 io_ring_submit_lock(ctx, issue_flags);
125 ret = io_file_bitmap_get(ctx);
126 if (unlikely(ret < 0))
133 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
134 if (!ret && alloc_slot)
137 io_ring_submit_unlock(ctx, issue_flags);
138 if (unlikely(ret < 0))