// SPDX-License-Identifier: GPL-2.0-or-later /* * Network block device - make block devices work over TCP * * Note that you can not swap over this thing, yet. Seems to work but * deadlocks sometimes - you can not swap over TCP in general. * * Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz> * Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com> * * (part of code stolen from loop.c)
*/
unsignedlong flags;
pid_t pid; /* pid of nbd-client, if attached */
char *backend;
};
#define NBD_CMD_REQUEUED 1 /* * This flag will be set if nbd_queue_rq() succeed, and will be checked and * cleared in completion. Both setting and clearing of the flag are protected * by cmd->lock.
*/ #define NBD_CMD_INFLIGHT 2
/* Just part of request header or data payload is sent successfully */ #define NBD_CMD_PARTIAL_SEND 3
struct nbd_cmd { struct nbd_device *nbd; struct mutex lock; int index; int cookie; int retries;
blk_status_t status; unsignedlong flags;
u32 cmd_cookie;
};
/* * Clear INFLIGHT flag so that this cmd won't be completed in * normal completion path * * INFLIGHT flag will be set when the cmd is queued to nbd next * time.
*/
__clear_bit(NBD_CMD_INFLIGHT, &cmd->flags);
if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
blk_mq_requeue_request(req, true);
}
staticconstchar *nbdcmd_to_ascii(int cmd)
{ switch (cmd) { case NBD_CMD_READ: return"read"; case NBD_CMD_WRITE: return"write"; case NBD_CMD_DISC: return"disconnect"; case NBD_CMD_FLUSH: return"flush"; case NBD_CMD_TRIM: return"trim/discard";
} return"invalid";
}
/* * Remove from idr after del_gendisk() completes, so if the same ID is * reused, the following add_disk() will succeed.
*/
mutex_lock(&nbd_index_mutex);
idr_remove(&nbd_index_idr, nbd->index);
mutex_unlock(&nbd_index_mutex);
destroy_workqueue(nbd->recv_workq);
put_disk(disk);
}
/* * Forcibly shutdown the socket causing all listeners to error
*/ staticvoid sock_shutdown(struct nbd_device *nbd)
{ struct nbd_config *config = nbd->config; int i;
if (config->num_connections == 0) return; if (test_and_set_bit(NBD_RT_DISCONNECTED, &config->runtime_flags)) return;
for (i = 0; i < config->num_connections; i++) { struct nbd_sock *nsock = config->socks[i];
mutex_lock(&nsock->tx_lock);
nbd_mark_nsock_dead(nbd, nsock, 0);
mutex_unlock(&nsock->tx_lock);
}
dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
}
static u32 req_to_nbd_cmd_type(struct request *req)
{ switch (req_op(req)) { case REQ_OP_DISCARD: return NBD_CMD_TRIM; case REQ_OP_FLUSH: return NBD_CMD_FLUSH; case REQ_OP_WRITE: return NBD_CMD_WRITE; case REQ_OP_READ: return NBD_CMD_READ; case REQ_OP_WRITE_ZEROES: return NBD_CMD_WRITE_ZEROES; default: return U32_MAX;
}
}
staticstruct nbd_config *nbd_get_config_unlocked(struct nbd_device *nbd)
{ if (refcount_inc_not_zero(&nbd->config_refs)) { /* * Add smp_mb__after_atomic to ensure that reading nbd->config_refs * and reading nbd->config is ordered. The pair is the barrier in * nbd_alloc_and_init_config(), avoid nbd->config_refs is set * before nbd->config.
*/
smp_mb__after_atomic(); return nbd->config;
}
if (!mutex_trylock(&cmd->lock)) return BLK_EH_RESET_TIMER;
/* partial send is handled in nbd_sock's work function */ if (test_bit(NBD_CMD_PARTIAL_SEND, &cmd->flags)) {
mutex_unlock(&cmd->lock); return BLK_EH_RESET_TIMER;
}
if (!test_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
mutex_unlock(&cmd->lock); return BLK_EH_DONE;
}
if (config->num_connections > 1 ||
(config->num_connections == 1 && nbd->tag_set.timeout)) {
dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out, retrying (%d/%d alive)\n",
atomic_read(&config->live_connections),
config->num_connections); /* * Hooray we have more connections, requeue this IO, the submit * path will put it on a real connection. Or if only one * connection is configured, the submit path will wait util * a new connection is reconfigured or util dead timeout.
*/ if (config->socks) { if (cmd->index < config->num_connections) { struct nbd_sock *nsock =
config->socks[cmd->index];
mutex_lock(&nsock->tx_lock); /* We can have multiple outstanding requests, so * we don't want to mark the nsock dead if we've * already reconnected with a new socket, so * only mark it dead if its the same socket we * were sent out on.
*/ if (cmd->cookie == nsock->cookie)
nbd_mark_nsock_dead(nbd, nsock, 1);
mutex_unlock(&nsock->tx_lock);
}
nbd_requeue_cmd(cmd);
mutex_unlock(&cmd->lock);
nbd_config_put(nbd); return BLK_EH_DONE;
}
}
if (!nbd->tag_set.timeout) { /* * Userspace sets timeout=0 to disable socket disconnection, * so just warn and reset the timer.
*/ struct nbd_sock *nsock = config->socks[cmd->index];
cmd->retries++;
dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
(unsignedlonglong)blk_rq_pos(req) << 9,
blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
if (send)
result = sock_sendmsg(sock, &msg); else
result = sock_recvmsg(sock, &msg, msg.msg_flags);
if (result <= 0) { if (result == 0)
result = -EPIPE; /* short read */ break;
} if (sent)
*sent += result;
} while (msg_data_left(&msg));
memalloc_noreclaim_restore(noreclaim_flag);
revert_creds(old_cred);
return result;
}
/* * Send or receive packet. Return a positive value on success and * negtive value on failure, and never return 0.
*/ staticint sock_xmit(struct nbd_device *nbd, int index, int send, struct iov_iter *iter, int msg_flags, int *sent)
{ struct nbd_config *config = nbd->config; struct socket *sock = config->socks[index]->sock;
/* * Different settings for sk->sk_sndtimeo can result in different return values * if there is a signal pending when we enter sendmsg, because reasons?
*/ staticinlineint was_interrupted(int result)
{ return result == -ERESTARTSYS || result == -EINTR;
}
/* * We've already sent header or part of data payload, have no choice but * to set pending and schedule it in work. * * And we have to return BLK_STS_OK to block core, otherwise this same * request may be re-dispatched with different tag, but our header has * been sent out with old tag, and this way does confuse reply handling.
*/ staticvoid nbd_sched_pending_work(struct nbd_device *nbd, struct nbd_sock *nsock, struct nbd_cmd *cmd, int sent)
{ struct request *req = blk_mq_rq_from_pdu(cmd);
/* pending work should be scheduled only once */
WARN_ON_ONCE(test_bit(NBD_CMD_PARTIAL_SEND, &cmd->flags));
type = req_to_nbd_cmd_type(req); if (type == U32_MAX) return BLK_STS_IOERR;
if (rq_data_dir(req) == WRITE &&
(config->flags & NBD_FLAG_READ_ONLY)) {
dev_err_ratelimited(disk_to_dev(nbd->disk), "Write on read-only\n"); return BLK_STS_IOERR;
}
if (req->cmd_flags & REQ_FUA)
nbd_cmd_flags |= NBD_CMD_FLAG_FUA; if ((req->cmd_flags & REQ_NOUNMAP) && (type == NBD_CMD_WRITE_ZEROES))
nbd_cmd_flags |= NBD_CMD_FLAG_NO_HOLE;
/* We did a partial send previously, and we at least sent the whole * request struct, so just go and send the rest of the pages in the * request.
*/ if (sent) { if (sent >= sizeof(request)) {
skip = sent - sizeof(request);
/* initialize handle for tracing purposes */
handle = nbd_cmd_handle(cmd);
dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
req, nbdcmd_to_ascii(type),
(unsignedlonglong)blk_rq_pos(req) << 9, blk_rq_bytes(req));
result = sock_xmit(nbd, index, 1, &from,
(type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
trace_nbd_header_sent(req, handle); if (result < 0) { if (was_interrupted(result)) { /* If we haven't sent anything we can just return BUSY, * however if we have sent something we need to make * sure we only allow this req to be sent until we are * completely done.
*/ if (sent) {
nbd_sched_pending_work(nbd, nsock, cmd, sent); return BLK_STS_OK;
}
set_bit(NBD_CMD_REQUEUED, &cmd->flags); return BLK_STS_RESOURCE;
}
dev_err_ratelimited(disk_to_dev(nbd->disk), "Send control failed (result %d)\n", result); goto requeue;
}
send_pages: if (type != NBD_CMD_WRITE) goto out;
bio = req->bio; while (bio) { struct bio *next = bio->bi_next; struct bvec_iter iter; struct bio_vec bvec;
dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
req, bvec.bv_len);
iov_iter_bvec(&from, ITER_SOURCE, &bvec, 1, bvec.bv_len); if (skip) { if (skip >= iov_iter_count(&from)) {
skip -= iov_iter_count(&from); continue;
}
iov_iter_advance(&from, skip);
skip = 0;
}
result = sock_xmit(nbd, index, 1, &from, flags, &sent); if (result < 0) { if (was_interrupted(result)) {
nbd_sched_pending_work(nbd, nsock, cmd, sent); return BLK_STS_OK;
}
dev_err(disk_to_dev(nbd->disk), "Send data failed (result %d)\n",
result); goto requeue;
} /* * The completion might already have come in, * so break for the last one instead of letting * the iterator do it. This prevents use-after-free * of the bio.
*/ if (is_last) break;
}
bio = next;
}
out:
trace_nbd_payload_sent(req, handle);
nsock->pending = NULL;
nsock->sent = 0;
__set_bit(NBD_CMD_INFLIGHT, &cmd->flags); return BLK_STS_OK;
requeue: /* * Can't requeue in case we are dealing with partial send * * We must run from pending work function.
* */ if (test_bit(NBD_CMD_PARTIAL_SEND, &cmd->flags)) return BLK_STS_OK;
/* retry on a different socket */
dev_err_ratelimited(disk_to_dev(nbd->disk), "Request send failed, requeueing\n");
nbd_mark_nsock_dead(nbd, nsock, 1);
nbd_requeue_cmd(cmd); return BLK_STS_OK;
}
if (nbd_read_reply(nbd, nsock->sock, &reply)) break;
/* * Grab .q_usage_counter so request pool won't go away, then no * request use-after-free is possible during nbd_handle_reply(). * If queue is frozen, there won't be any inflight requests, we * needn't to handle the incoming garbage message.
*/ if (!percpu_ref_tryget(&q->q_usage_counter)) {
dev_err(disk_to_dev(nbd->disk), "%s: no io inflight\n",
__func__); break;
}
config = nbd_get_config_unlocked(nbd); if (!config) {
dev_err_ratelimited(disk_to_dev(nbd->disk), "Socks array is empty\n"); return BLK_STS_IOERR;
}
if (index >= config->num_connections) {
dev_err_ratelimited(disk_to_dev(nbd->disk), "Attempted send on invalid socket\n");
nbd_config_put(nbd); return BLK_STS_IOERR;
}
cmd->status = BLK_STS_OK;
again:
nsock = config->socks[index];
mutex_lock(&nsock->tx_lock); if (nsock->dead) { int old_index = index;
index = find_fallback(nbd, index);
mutex_unlock(&nsock->tx_lock); if (index < 0) { if (wait_for_reconnect(nbd)) {
index = old_index; goto again;
} /* All the sockets should already be down at this point, * we just want to make sure that DISCONNECTED is set so * any requests that come in that were queue'ed waiting * for the reconnect timer don't trigger the timer again * and instead just error out.
*/
sock_shutdown(nbd);
nbd_config_put(nbd); return BLK_STS_IOERR;
} goto again;
}
/* Handle the case that we have a pending request that was partially * transmitted that _has_ to be serviced first. We need to call requeue * here so that it gets put _after_ the request that is already on the * dispatch list.
*/
blk_mq_start_request(req); if (unlikely(nsock->pending && nsock->pending != req)) {
nbd_requeue_cmd(cmd);
ret = BLK_STS_OK; goto out;
}
ret = nbd_send_cmd(nbd, cmd, index);
out:
mutex_unlock(&nsock->tx_lock);
nbd_config_put(nbd); return ret;
}
/* * Since we look at the bio's to send the request over the network we * need to make sure the completion work doesn't mark this request done * before we are done doing our send. This keeps us from dereferencing * freed data if we have particularly fast completions (ie we get the * completion before we exit sock_xmit on the last bvec) or in the case * that the server is misbehaving (or there was an error) before we're * done sending everything over the wire.
*/
mutex_lock(&cmd->lock);
clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
/* We can be called directly from the user space process, which means we * could possibly have signals pending so our sendmsg will fail. In * this case we need to return that we are busy, otherwise error out as * appropriate.
*/
ret = nbd_handle_cmd(cmd, hctx->queue_num);
mutex_unlock(&cmd->lock);
if (!sk_is_tcp(sock->sk) &&
!sk_is_stream_unix(sock->sk)) {
dev_err(disk_to_dev(nbd->disk), "Unsupported socket: should be TCP or UNIX.\n");
*err = -EINVAL;
sockfd_put(sock); return NULL;
}
if (sock->ops->shutdown == sock_no_shutdown) {
dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
*err = -EINVAL;
sockfd_put(sock); return NULL;
}
/* Arg will be cast to int, check it to avoid overflow */ if (arg > INT_MAX) return -EINVAL;
sock = nbd_get_socket(nbd, arg, &err); if (!sock) return err;
/* * We need to make sure we don't get any errant requests while we're * reallocating the ->socks array.
*/
memflags = blk_mq_freeze_queue(nbd->disk->queue);
if (!netlink && !nbd->task_setup &&
!test_bit(NBD_RT_BOUND, &config->runtime_flags))
nbd->task_setup = current;
if (!netlink &&
(nbd->task_setup != current ||
test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
dev_err(disk_to_dev(nbd->disk), "Device being setup by another task");
err = -EBUSY; goto put_socket;
}
/* We take the tx_mutex in an error path in the recv_work, so we * need to queue_work outside of the tx_mutex.
*/
queue_work(nbd->recv_workq, &args->work);
staticint nbd_start_device(struct nbd_device *nbd)
{ struct nbd_config *config = nbd->config; int num_connections = config->num_connections; int error = 0, i;
if (nbd->pid) return -EBUSY; if (!config->socks) return -EINVAL; if (num_connections > 1 &&
!(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n"); return -EINVAL;
}
/* if another code path updated nr_hw_queues, retry until succeed */ if (num_connections != config->num_connections) {
num_connections = config->num_connections; goto retry;
}
nbd->pid = task_pid_nr(current);
nbd_parse_flags(nbd);
error = device_create_file(disk_to_dev(nbd->disk), &pid_attr); if (error) {
dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n"); return error;
}
set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
nbd_dev_dbg_init(nbd); for (i = 0; i < num_connections; i++) { struct recv_thread_args *args;
args = kzalloc(sizeof(*args), GFP_KERNEL); if (!args) {
sock_shutdown(nbd); /* * If num_connections is m (2 < m), * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful. * But NO.(n + 1) failed. We still have n recv threads. * So, add flush_workqueue here to prevent recv threads * dropping the last config_refs and trying to destroy * the workqueue from inside the workqueue.
*/ if (i)
flush_workqueue(nbd->recv_workq); return -ENOMEM;
}
sk_set_memalloc(config->socks[i]->sock->sk); if (nbd->tag_set.timeout)
config->socks[i]->sock->sk->sk_sndtimeo =
nbd->tag_set.timeout;
atomic_inc(&config->recv_threads);
refcount_inc(&nbd->config_refs);
INIT_WORK(&args->work, recv_work);
args->nbd = nbd;
args->nsock = config->socks[i];
args->index = i;
queue_work(nbd->recv_workq, &args->work);
} return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
}
if (max_part)
set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
mutex_unlock(&nbd->config_lock);
ret = wait_event_interruptible(config->recv_wq,
atomic_read(&config->recv_threads) == 0); if (ret) {
sock_shutdown(nbd);
nbd_clear_que(nbd);
}
flush_workqueue(nbd->recv_workq);
mutex_lock(&nbd->config_lock);
nbd_bdev_reset(nbd); /* user requested, ignore socket errors */ if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
ret = 0; if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
ret = -ETIMEDOUT; return ret;
}
/* Must be called with config_lock held */ staticint __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd, unsignedint cmd, unsignedlong arg)
{ struct nbd_config *config = nbd->config;
loff_t bytesize;
switch (cmd) { case NBD_DISCONNECT: return nbd_disconnect(nbd); case NBD_CLEAR_SOCK:
nbd_clear_sock_ioctl(nbd); return 0; case NBD_SET_SOCK: return nbd_add_socket(nbd, arg, false); case NBD_SET_BLKSIZE: return nbd_set_size(nbd, config->bytesize, arg); case NBD_SET_SIZE: return nbd_set_size(nbd, arg, nbd_blksize(config)); case NBD_SET_SIZE_BLOCKS: if (check_shl_overflow(arg, config->blksize_bits, &bytesize)) return -EINVAL; return nbd_set_size(nbd, bytesize, nbd_blksize(config)); case NBD_SET_TIMEOUT:
nbd_set_cmd_timeout(nbd, arg); return 0;
case NBD_SET_FLAGS:
config->flags = arg; return 0; case NBD_DO_IT: return nbd_start_device_ioctl(nbd); case NBD_CLEAR_QUE: /* * This is for compatibility only. The queue is always cleared * by NBD_DO_IT or NBD_CLEAR_SOCK.
*/ return 0; case NBD_PRINT_DEBUG: /* * For compatibility only, we no longer keep a list of * outstanding requests.
*/ return 0;
} return -ENOTTY;
}
/* The block layer will pass back some non-nbd ioctls in case we have * special handling for them, but we don't so just return an error.
*/ if (_IOC_TYPE(cmd) != 0xab) return -EINVAL;
mutex_lock(&nbd->config_lock);
/* Don't allow ioctl operations on a nbd device that was created with * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
*/ if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
(cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
error = __nbd_ioctl(bdev, nbd, cmd, arg); else
dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
mutex_unlock(&nbd->config_lock); return error;
}
nbd->config = config; /* * Order refcount_set(&nbd->config_refs, 1) and nbd->config assignment, * its pair is the barrier in nbd_get_config_unlocked(). * So nbd_get_config_unlocked() won't see nbd->config as null after * refcount_inc_not_zero() succeed.
*/
smp_mb__before_atomic();
refcount_set(&nbd->config_refs, 1);
return 0;
}
staticint nbd_open(struct gendisk *disk, blk_mode_t mode)
{ struct nbd_device *nbd; struct nbd_config *config; int ret = 0;
mutex_lock(&nbd_index_mutex);
nbd = disk->private_data; if (!nbd) {
ret = -ENXIO; goto out;
} if (!refcount_inc_not_zero(&nbd->refs)) {
ret = -ENXIO; goto out;
}
config = nbd_get_config_unlocked(nbd); if (!config) {
mutex_lock(&nbd->config_lock); if (refcount_inc_not_zero(&nbd->config_refs)) {
mutex_unlock(&nbd->config_lock); goto out;
}
ret = nbd_alloc_and_init_config(nbd); if (ret) {
mutex_unlock(&nbd->config_lock); goto out;
}
refcount_inc(&nbd->refs);
mutex_unlock(&nbd->config_lock); if (max_part)
set_bit(GD_NEED_PART_SCAN, &disk->state);
} elseif (nbd_disconnected(config)) { if (max_part)
set_bit(GD_NEED_PART_SCAN, &disk->state);
}
out:
mutex_unlock(&nbd_index_mutex); return ret;
}
dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir); if (IS_ERR(dir)) {
dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
nbd_name(nbd)); return -EIO;
}
config->dbg_dir = dir;
err = blk_mq_alloc_tag_set(&nbd->tag_set); if (err) goto out_free_nbd;
mutex_lock(&nbd_index_mutex); if (index >= 0) {
err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
GFP_KERNEL); if (err == -ENOSPC)
err = -EEXIST;
} else {
err = idr_alloc(&nbd_index_idr, nbd, 0,
(MINORMASK >> part_shift) + 1, GFP_KERNEL); if (err >= 0)
index = err;
}
nbd->index = index;
mutex_unlock(&nbd_index_mutex); if (err < 0) goto out_free_tags;
disk = blk_mq_alloc_disk(&nbd->tag_set, &lim, NULL); if (IS_ERR(disk)) {
err = PTR_ERR(disk); goto out_free_idr;
}
nbd->disk = disk;
nbd->recv_workq = alloc_workqueue("nbd%d-recv",
WQ_MEM_RECLAIM | WQ_HIGHPRI |
WQ_UNBOUND, 0, nbd->index); if (!nbd->recv_workq) {
dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
err = -ENOMEM; goto out_err_disk;
}
mutex_init(&nbd->config_lock);
refcount_set(&nbd->config_refs, 0); /* * Start out with a zero references to keep other threads from using * this device until it is fully initialized.
*/
refcount_set(&nbd->refs, 0);
INIT_LIST_HEAD(&nbd->list);
disk->major = NBD_MAJOR;
disk->first_minor = index << part_shift;
disk->minors = 1 << part_shift;
disk->fops = &nbd_fops;
disk->private_data = nbd;
sprintf(disk->disk_name, "nbd%d", index);
err = add_disk(disk); if (err) goto out_free_work;
/* * Now publish the device.
*/
refcount_set(&nbd->refs, refs);
nbd_total_devices++; return nbd;
/* We don't use this right now since we don't parse the incoming list, but we * still want it here so userspace knows what to expect.
*/ staticconststruct nla_policy __attribute__((unused))
nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
[NBD_DEVICE_INDEX] = { .type = NLA_U32 },
[NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
};
staticint nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
{ struct nbd_device *nbd; struct nbd_config *config; int index = -1; int ret; bool put_dev = false;
if (!netlink_capable(skb, CAP_SYS_ADMIN)) return -EPERM;
if (info->attrs[NBD_ATTR_INDEX]) {
index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
/* * Too big first_minor can cause duplicate creation of * sysfs files/links, since index << part_shift might overflow, or * MKDEV() expect that the max bits of first_minor is 20.
*/ if (index < 0 || index > MINORMASK >> part_shift) {
pr_err("illegal input index %d\n", index); return -EINVAL;
}
} if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_SOCKETS)) {
pr_err("must specify at least one socket\n"); return -EINVAL;
} if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_SIZE_BYTES)) {
pr_err("must specify a size in bytes for the device\n"); return -EINVAL;
}
again:
mutex_lock(&nbd_index_mutex); if (index == -1) {
nbd = nbd_find_get_unused();
} else {
nbd = idr_find(&nbd_index_idr, index); if (nbd) { if ((test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) ||
!refcount_inc_not_zero(&nbd->refs)) {
mutex_unlock(&nbd_index_mutex);
pr_err("device at index %d is going down\n",
index); return -EINVAL;
}
}
}
mutex_unlock(&nbd_index_mutex);
if (!nbd) {
nbd = nbd_dev_add(index, 2); if (IS_ERR(nbd)) {
pr_err("failed to add new device\n"); return PTR_ERR(nbd);
}
}
mutex_lock(&nbd->config_lock); if (refcount_read(&nbd->config_refs)) {
mutex_unlock(&nbd->config_lock);
nbd_put(nbd); if (index == -1) goto again;
pr_err("nbd%d already in use\n", index); return -EBUSY;
}
ret = nbd_alloc_and_init_config(nbd); if (ret) {
mutex_unlock(&nbd->config_lock);
nbd_put(nbd);
pr_err("couldn't allocate config\n"); return ret;
}
config = nbd->config;
set_bit(NBD_RT_BOUND, &config->runtime_flags);
ret = nbd_genl_size_set(info, nbd); if (ret) goto out;
if (info->attrs[NBD_ATTR_TIMEOUT])
nbd_set_cmd_timeout(nbd,
nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT])); if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
config->dead_conn_timeout =
nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
config->dead_conn_timeout *= HZ;
} if (info->attrs[NBD_ATTR_SERVER_FLAGS])
config->flags =
nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]); if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]); if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) { /* * We have 1 ref to keep the device around, and then 1 * ref for our current operation here, which will be * inherited by the config. If we already have * DESTROY_ON_DISCONNECT set then we know we don't have * that extra ref already held so we don't need the * put_dev.
*/ if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
&nbd->flags))
put_dev = true;
} else { if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
&nbd->flags))
refcount_inc(&nbd->refs);
} if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
&config->runtime_flags);
}
}
if (info->attrs[NBD_ATTR_SOCKETS]) { struct nlattr *attr; int rem, fd;
if (nla_type(attr) != NBD_SOCK_ITEM) {
pr_err("socks must be embedded in a SOCK_ITEM attr\n");
ret = -EINVAL; goto out;
}
ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
attr,
nbd_sock_policy,
info->extack); if (ret != 0) {
pr_err("error processing sock list\n");
ret = -EINVAL; goto out;
} if (!socks[NBD_SOCK_FD]) continue;
fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
ret = nbd_add_socket(nbd, fd, true); if (ret) goto out;
}
}
if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
GFP_KERNEL); if (!nbd->backend) {
ret = -ENOMEM; goto out;
}
}
ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr); if (ret) {
dev_err(disk_to_dev(nbd->disk), "device_create_file failed for backend!\n"); goto out;
}
set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
ret = nbd_start_device(nbd);
out:
mutex_unlock(&nbd->config_lock); if (!ret) {
set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
refcount_inc(&nbd->config_refs);
nbd_connect_reply(info, nbd->index);
}
nbd_config_put(nbd); if (put_dev)
nbd_put(nbd); return ret;
}
staticvoid nbd_disconnect_and_put(struct nbd_device *nbd)
{
mutex_lock(&nbd->config_lock);
nbd_disconnect(nbd);
sock_shutdown(nbd);
wake_up(&nbd->config->conn_wait); /* * Make sure recv thread has finished, we can safely call nbd_clear_que() * to cancel the inflight I/Os.
*/
flush_workqueue(nbd->recv_workq);
nbd_clear_que(nbd);
nbd->task_setup = NULL;
clear_bit(NBD_RT_BOUND, &nbd->config->runtime_flags);
mutex_unlock(&nbd->config_lock);
if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
&nbd->config->runtime_flags))
nbd_config_put(nbd);
}
if (!netlink_capable(skb, CAP_SYS_ADMIN)) return -EPERM;
if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_INDEX)) {
pr_err("must specify an index to disconnect\n"); return -EINVAL;
}
index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
mutex_lock(&nbd_index_mutex);
nbd = idr_find(&nbd_index_idr, index); if (!nbd) {
mutex_unlock(&nbd_index_mutex);
pr_err("couldn't find device at index %d\n", index); return -EINVAL;
} if (!refcount_inc_not_zero(&nbd->refs)) {
mutex_unlock(&nbd_index_mutex);
pr_err("device at index %d is going down\n", index); return -EINVAL;
}
mutex_unlock(&nbd_index_mutex); if (!refcount_inc_not_zero(&nbd->config_refs)) goto put_nbd;
nbd_disconnect_and_put(nbd);
nbd_config_put(nbd);
put_nbd:
nbd_put(nbd); return 0;
}
staticint nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
{ struct nbd_device *nbd = NULL; struct nbd_config *config; int index; int ret = 0; bool put_dev = false;
if (!netlink_capable(skb, CAP_SYS_ADMIN)) return -EPERM;
if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_INDEX)) {
pr_err("must specify a device to reconfigure\n"); return -EINVAL;
}
index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
mutex_lock(&nbd_index_mutex);
nbd = idr_find(&nbd_index_idr, index); if (!nbd) {
mutex_unlock(&nbd_index_mutex);
pr_err("couldn't find a device at index %d\n", index); return -EINVAL;
} if (nbd->backend) { if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) { if (nla_strcmp(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
nbd->backend)) {
mutex_unlock(&nbd_index_mutex);
dev_err(nbd_to_dev(nbd), "backend image doesn't match with %s\n",
nbd->backend); return -EINVAL;
}
} else {
mutex_unlock(&nbd_index_mutex);
dev_err(nbd_to_dev(nbd), "must specify backend\n"); return -EINVAL;
}
} if (!refcount_inc_not_zero(&nbd->refs)) {
mutex_unlock(&nbd_index_mutex);
pr_err("device at index %d is going down\n", index); return -EINVAL;
}
mutex_unlock(&nbd_index_mutex);
/* This is a little racey, but for status it's ok. The * reason we don't take a ref here is because we can't * take a ref in the index == -1 case as we would need * to put under the nbd_index_mutex, which could * deadlock if we are configured to remove ourselves * once we're disconnected.
*/ if (refcount_read(&nbd->config_refs))
connected = 1;
dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM); if (!dev_opt) return -EMSGSIZE;
ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index); if (ret) return -EMSGSIZE;
ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
connected); if (ret) return -EMSGSIZE;
nla_nest_end(reply, dev_opt); return 0;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.