nbd: add a flag to destroy an nbd device on disconnect
[GitHub/LineageOS/android_kernel_motorola_exynos9610.git] / drivers / block / nbd.c
1 /*
2 * Network block device - make block devices work over TCP
3 *
4 * Note that you can not swap over this thing, yet. Seems to work but
5 * deadlocks sometimes - you can not swap over TCP in general.
6 *
7 * Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz>
8 * Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com>
9 *
10 * This file is released under GPLv2 or later.
11 *
12 * (part of code stolen from loop.c)
13 */
14
15 #include <linux/major.h>
16
17 #include <linux/blkdev.h>
18 #include <linux/module.h>
19 #include <linux/init.h>
20 #include <linux/sched.h>
21 #include <linux/fs.h>
22 #include <linux/bio.h>
23 #include <linux/stat.h>
24 #include <linux/errno.h>
25 #include <linux/file.h>
26 #include <linux/ioctl.h>
27 #include <linux/mutex.h>
28 #include <linux/compiler.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/slab.h>
32 #include <net/sock.h>
33 #include <linux/net.h>
34 #include <linux/kthread.h>
35 #include <linux/types.h>
36 #include <linux/debugfs.h>
37 #include <linux/blk-mq.h>
38
39 #include <linux/uaccess.h>
40 #include <asm/types.h>
41
42 #include <linux/nbd.h>
43 #include <linux/nbd-netlink.h>
44 #include <net/genetlink.h>
45
46 static DEFINE_IDR(nbd_index_idr);
47 static DEFINE_MUTEX(nbd_index_mutex);
48 static int nbd_total_devices = 0;
49
50 struct nbd_sock {
51 struct socket *sock;
52 struct mutex tx_lock;
53 struct request *pending;
54 int sent;
55 bool dead;
56 int fallback_index;
57 int cookie;
58 };
59
60 struct recv_thread_args {
61 struct work_struct work;
62 struct nbd_device *nbd;
63 int index;
64 };
65
66 struct link_dead_args {
67 struct work_struct work;
68 int index;
69 };
70
71 #define NBD_TIMEDOUT 0
72 #define NBD_DISCONNECT_REQUESTED 1
73 #define NBD_DISCONNECTED 2
74 #define NBD_HAS_PID_FILE 3
75 #define NBD_HAS_CONFIG_REF 4
76 #define NBD_BOUND 5
77 #define NBD_DESTROY_ON_DISCONNECT 6
78
79 struct nbd_config {
80 u32 flags;
81 unsigned long runtime_flags;
82 u64 dead_conn_timeout;
83
84 struct nbd_sock **socks;
85 int num_connections;
86 atomic_t live_connections;
87 wait_queue_head_t conn_wait;
88
89 atomic_t recv_threads;
90 wait_queue_head_t recv_wq;
91 loff_t blksize;
92 loff_t bytesize;
93 #if IS_ENABLED(CONFIG_DEBUG_FS)
94 struct dentry *dbg_dir;
95 #endif
96 };
97
98 struct nbd_device {
99 struct blk_mq_tag_set tag_set;
100
101 int index;
102 refcount_t config_refs;
103 refcount_t refs;
104 struct nbd_config *config;
105 struct mutex config_lock;
106 struct gendisk *disk;
107
108 struct list_head list;
109 struct task_struct *task_recv;
110 struct task_struct *task_setup;
111 };
112
113 struct nbd_cmd {
114 struct nbd_device *nbd;
115 int index;
116 int cookie;
117 struct completion send_complete;
118 };
119
120 #if IS_ENABLED(CONFIG_DEBUG_FS)
121 static struct dentry *nbd_dbg_dir;
122 #endif
123
124 #define nbd_name(nbd) ((nbd)->disk->disk_name)
125
126 #define NBD_MAGIC 0x68797548
127
128 static unsigned int nbds_max = 16;
129 static int max_part;
130 static struct workqueue_struct *recv_workqueue;
131 static int part_shift;
132
133 static int nbd_dev_dbg_init(struct nbd_device *nbd);
134 static void nbd_dev_dbg_close(struct nbd_device *nbd);
135 static void nbd_config_put(struct nbd_device *nbd);
136 static void nbd_connect_reply(struct genl_info *info, int index);
137 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
138 static void nbd_dead_link_work(struct work_struct *work);
139
140 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
141 {
142 return disk_to_dev(nbd->disk);
143 }
144
145 static const char *nbdcmd_to_ascii(int cmd)
146 {
147 switch (cmd) {
148 case NBD_CMD_READ: return "read";
149 case NBD_CMD_WRITE: return "write";
150 case NBD_CMD_DISC: return "disconnect";
151 case NBD_CMD_FLUSH: return "flush";
152 case NBD_CMD_TRIM: return "trim/discard";
153 }
154 return "invalid";
155 }
156
157 static ssize_t pid_show(struct device *dev,
158 struct device_attribute *attr, char *buf)
159 {
160 struct gendisk *disk = dev_to_disk(dev);
161 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
162
163 return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
164 }
165
166 static struct device_attribute pid_attr = {
167 .attr = { .name = "pid", .mode = S_IRUGO},
168 .show = pid_show,
169 };
170
171 static void nbd_dev_remove(struct nbd_device *nbd)
172 {
173 struct gendisk *disk = nbd->disk;
174 if (disk) {
175 del_gendisk(disk);
176 blk_cleanup_queue(disk->queue);
177 blk_mq_free_tag_set(&nbd->tag_set);
178 disk->private_data = NULL;
179 put_disk(disk);
180 }
181 kfree(nbd);
182 }
183
184 static void nbd_put(struct nbd_device *nbd)
185 {
186 if (refcount_dec_and_mutex_lock(&nbd->refs,
187 &nbd_index_mutex)) {
188 idr_remove(&nbd_index_idr, nbd->index);
189 mutex_unlock(&nbd_index_mutex);
190 nbd_dev_remove(nbd);
191 }
192 }
193
194 static int nbd_disconnected(struct nbd_config *config)
195 {
196 return test_bit(NBD_DISCONNECTED, &config->runtime_flags) ||
197 test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
198 }
199
200 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
201 int notify)
202 {
203 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
204 struct link_dead_args *args;
205 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
206 if (args) {
207 INIT_WORK(&args->work, nbd_dead_link_work);
208 args->index = nbd->index;
209 queue_work(system_wq, &args->work);
210 }
211 }
212 if (!nsock->dead) {
213 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
214 atomic_dec(&nbd->config->live_connections);
215 }
216 nsock->dead = true;
217 nsock->pending = NULL;
218 nsock->sent = 0;
219 }
220
221 static void nbd_size_clear(struct nbd_device *nbd)
222 {
223 if (nbd->config->bytesize) {
224 set_capacity(nbd->disk, 0);
225 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
226 }
227 }
228
229 static void nbd_size_update(struct nbd_device *nbd)
230 {
231 struct nbd_config *config = nbd->config;
232 blk_queue_logical_block_size(nbd->disk->queue, config->blksize);
233 blk_queue_physical_block_size(nbd->disk->queue, config->blksize);
234 set_capacity(nbd->disk, config->bytesize >> 9);
235 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
236 }
237
238 static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
239 loff_t nr_blocks)
240 {
241 struct nbd_config *config = nbd->config;
242 config->blksize = blocksize;
243 config->bytesize = blocksize * nr_blocks;
244 nbd_size_update(nbd);
245 }
246
247 static void nbd_end_request(struct nbd_cmd *cmd)
248 {
249 struct nbd_device *nbd = cmd->nbd;
250 struct request *req = blk_mq_rq_from_pdu(cmd);
251 int error = req->errors ? -EIO : 0;
252
253 dev_dbg(nbd_to_dev(nbd), "request %p: %s\n", cmd,
254 error ? "failed" : "done");
255
256 blk_mq_complete_request(req, error);
257 }
258
259 /*
260 * Forcibly shutdown the socket causing all listeners to error
261 */
262 static void sock_shutdown(struct nbd_device *nbd)
263 {
264 struct nbd_config *config = nbd->config;
265 int i;
266
267 if (config->num_connections == 0)
268 return;
269 if (test_and_set_bit(NBD_DISCONNECTED, &config->runtime_flags))
270 return;
271
272 for (i = 0; i < config->num_connections; i++) {
273 struct nbd_sock *nsock = config->socks[i];
274 mutex_lock(&nsock->tx_lock);
275 nbd_mark_nsock_dead(nbd, nsock, 0);
276 mutex_unlock(&nsock->tx_lock);
277 }
278 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
279 }
280
281 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
282 bool reserved)
283 {
284 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
285 struct nbd_device *nbd = cmd->nbd;
286 struct nbd_config *config;
287
288 if (!refcount_inc_not_zero(&nbd->config_refs)) {
289 req->errors = -EIO;
290 return BLK_EH_HANDLED;
291 }
292
293 /* If we are waiting on our dead timer then we could get timeout
294 * callbacks for our request. For this we just want to reset the timer
295 * and let the queue side take care of everything.
296 */
297 if (!completion_done(&cmd->send_complete)) {
298 nbd_config_put(nbd);
299 return BLK_EH_RESET_TIMER;
300 }
301 config = nbd->config;
302
303 if (config->num_connections > 1) {
304 dev_err_ratelimited(nbd_to_dev(nbd),
305 "Connection timed out, retrying\n");
306 /*
307 * Hooray we have more connections, requeue this IO, the submit
308 * path will put it on a real connection.
309 */
310 if (config->socks && config->num_connections > 1) {
311 if (cmd->index < config->num_connections) {
312 struct nbd_sock *nsock =
313 config->socks[cmd->index];
314 mutex_lock(&nsock->tx_lock);
315 /* We can have multiple outstanding requests, so
316 * we don't want to mark the nsock dead if we've
317 * already reconnected with a new socket, so
318 * only mark it dead if its the same socket we
319 * were sent out on.
320 */
321 if (cmd->cookie == nsock->cookie)
322 nbd_mark_nsock_dead(nbd, nsock, 1);
323 mutex_unlock(&nsock->tx_lock);
324 }
325 blk_mq_requeue_request(req, true);
326 nbd_config_put(nbd);
327 return BLK_EH_NOT_HANDLED;
328 }
329 } else {
330 dev_err_ratelimited(nbd_to_dev(nbd),
331 "Connection timed out\n");
332 }
333 set_bit(NBD_TIMEDOUT, &config->runtime_flags);
334 req->errors = -EIO;
335 sock_shutdown(nbd);
336 nbd_config_put(nbd);
337
338 return BLK_EH_HANDLED;
339 }
340
341 /*
342 * Send or receive packet.
343 */
344 static int sock_xmit(struct nbd_device *nbd, int index, int send,
345 struct iov_iter *iter, int msg_flags, int *sent)
346 {
347 struct nbd_config *config = nbd->config;
348 struct socket *sock = config->socks[index]->sock;
349 int result;
350 struct msghdr msg;
351 unsigned long pflags = current->flags;
352
353 if (unlikely(!sock)) {
354 dev_err_ratelimited(disk_to_dev(nbd->disk),
355 "Attempted %s on closed socket in sock_xmit\n",
356 (send ? "send" : "recv"));
357 return -EINVAL;
358 }
359
360 msg.msg_iter = *iter;
361
362 current->flags |= PF_MEMALLOC;
363 do {
364 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
365 msg.msg_name = NULL;
366 msg.msg_namelen = 0;
367 msg.msg_control = NULL;
368 msg.msg_controllen = 0;
369 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
370
371 if (send)
372 result = sock_sendmsg(sock, &msg);
373 else
374 result = sock_recvmsg(sock, &msg, msg.msg_flags);
375
376 if (result <= 0) {
377 if (result == 0)
378 result = -EPIPE; /* short read */
379 break;
380 }
381 if (sent)
382 *sent += result;
383 } while (msg_data_left(&msg));
384
385 tsk_restore_flags(current, pflags, PF_MEMALLOC);
386
387 return result;
388 }
389
390 /* always call with the tx_lock held */
391 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
392 {
393 struct request *req = blk_mq_rq_from_pdu(cmd);
394 struct nbd_config *config = nbd->config;
395 struct nbd_sock *nsock = config->socks[index];
396 int result;
397 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
398 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
399 struct iov_iter from;
400 unsigned long size = blk_rq_bytes(req);
401 struct bio *bio;
402 u32 type;
403 u32 tag = blk_mq_unique_tag(req);
404 int sent = nsock->sent, skip = 0;
405
406 iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
407
408 switch (req_op(req)) {
409 case REQ_OP_DISCARD:
410 type = NBD_CMD_TRIM;
411 break;
412 case REQ_OP_FLUSH:
413 type = NBD_CMD_FLUSH;
414 break;
415 case REQ_OP_WRITE:
416 type = NBD_CMD_WRITE;
417 break;
418 case REQ_OP_READ:
419 type = NBD_CMD_READ;
420 break;
421 default:
422 return -EIO;
423 }
424
425 if (rq_data_dir(req) == WRITE &&
426 (config->flags & NBD_FLAG_READ_ONLY)) {
427 dev_err_ratelimited(disk_to_dev(nbd->disk),
428 "Write on read-only\n");
429 return -EIO;
430 }
431
432 /* We did a partial send previously, and we at least sent the whole
433 * request struct, so just go and send the rest of the pages in the
434 * request.
435 */
436 if (sent) {
437 if (sent >= sizeof(request)) {
438 skip = sent - sizeof(request);
439 goto send_pages;
440 }
441 iov_iter_advance(&from, sent);
442 }
443 cmd->index = index;
444 cmd->cookie = nsock->cookie;
445 request.type = htonl(type);
446 if (type != NBD_CMD_FLUSH) {
447 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
448 request.len = htonl(size);
449 }
450 memcpy(request.handle, &tag, sizeof(tag));
451
452 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
453 cmd, nbdcmd_to_ascii(type),
454 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
455 result = sock_xmit(nbd, index, 1, &from,
456 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
457 if (result <= 0) {
458 if (result == -ERESTARTSYS) {
459 /* If we havne't sent anything we can just return BUSY,
460 * however if we have sent something we need to make
461 * sure we only allow this req to be sent until we are
462 * completely done.
463 */
464 if (sent) {
465 nsock->pending = req;
466 nsock->sent = sent;
467 }
468 return BLK_MQ_RQ_QUEUE_BUSY;
469 }
470 dev_err_ratelimited(disk_to_dev(nbd->disk),
471 "Send control failed (result %d)\n", result);
472 return -EAGAIN;
473 }
474 send_pages:
475 if (type != NBD_CMD_WRITE)
476 goto out;
477
478 bio = req->bio;
479 while (bio) {
480 struct bio *next = bio->bi_next;
481 struct bvec_iter iter;
482 struct bio_vec bvec;
483
484 bio_for_each_segment(bvec, bio, iter) {
485 bool is_last = !next && bio_iter_last(bvec, iter);
486 int flags = is_last ? 0 : MSG_MORE;
487
488 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
489 cmd, bvec.bv_len);
490 iov_iter_bvec(&from, ITER_BVEC | WRITE,
491 &bvec, 1, bvec.bv_len);
492 if (skip) {
493 if (skip >= iov_iter_count(&from)) {
494 skip -= iov_iter_count(&from);
495 continue;
496 }
497 iov_iter_advance(&from, skip);
498 skip = 0;
499 }
500 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
501 if (result <= 0) {
502 if (result == -ERESTARTSYS) {
503 /* We've already sent the header, we
504 * have no choice but to set pending and
505 * return BUSY.
506 */
507 nsock->pending = req;
508 nsock->sent = sent;
509 return BLK_MQ_RQ_QUEUE_BUSY;
510 }
511 dev_err(disk_to_dev(nbd->disk),
512 "Send data failed (result %d)\n",
513 result);
514 return -EAGAIN;
515 }
516 /*
517 * The completion might already have come in,
518 * so break for the last one instead of letting
519 * the iterator do it. This prevents use-after-free
520 * of the bio.
521 */
522 if (is_last)
523 break;
524 }
525 bio = next;
526 }
527 out:
528 nsock->pending = NULL;
529 nsock->sent = 0;
530 return 0;
531 }
532
533 /* NULL returned = something went wrong, inform userspace */
534 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
535 {
536 struct nbd_config *config = nbd->config;
537 int result;
538 struct nbd_reply reply;
539 struct nbd_cmd *cmd;
540 struct request *req = NULL;
541 u16 hwq;
542 u32 tag;
543 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
544 struct iov_iter to;
545
546 reply.magic = 0;
547 iov_iter_kvec(&to, READ | ITER_KVEC, &iov, 1, sizeof(reply));
548 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
549 if (result <= 0) {
550 if (!nbd_disconnected(config))
551 dev_err(disk_to_dev(nbd->disk),
552 "Receive control failed (result %d)\n", result);
553 return ERR_PTR(result);
554 }
555
556 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
557 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
558 (unsigned long)ntohl(reply.magic));
559 return ERR_PTR(-EPROTO);
560 }
561
562 memcpy(&tag, reply.handle, sizeof(u32));
563
564 hwq = blk_mq_unique_tag_to_hwq(tag);
565 if (hwq < nbd->tag_set.nr_hw_queues)
566 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
567 blk_mq_unique_tag_to_tag(tag));
568 if (!req || !blk_mq_request_started(req)) {
569 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
570 tag, req);
571 return ERR_PTR(-ENOENT);
572 }
573 cmd = blk_mq_rq_to_pdu(req);
574 if (ntohl(reply.error)) {
575 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
576 ntohl(reply.error));
577 req->errors = -EIO;
578 return cmd;
579 }
580
581 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", cmd);
582 if (rq_data_dir(req) != WRITE) {
583 struct req_iterator iter;
584 struct bio_vec bvec;
585
586 rq_for_each_segment(bvec, req, iter) {
587 iov_iter_bvec(&to, ITER_BVEC | READ,
588 &bvec, 1, bvec.bv_len);
589 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
590 if (result <= 0) {
591 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
592 result);
593 /*
594 * If we've disconnected or we only have 1
595 * connection then we need to make sure we
596 * complete this request, otherwise error out
597 * and let the timeout stuff handle resubmitting
598 * this request onto another connection.
599 */
600 if (nbd_disconnected(config) ||
601 config->num_connections <= 1) {
602 req->errors = -EIO;
603 return cmd;
604 }
605 return ERR_PTR(-EIO);
606 }
607 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
608 cmd, bvec.bv_len);
609 }
610 } else {
611 /* See the comment in nbd_queue_rq. */
612 wait_for_completion(&cmd->send_complete);
613 }
614 return cmd;
615 }
616
617 static void recv_work(struct work_struct *work)
618 {
619 struct recv_thread_args *args = container_of(work,
620 struct recv_thread_args,
621 work);
622 struct nbd_device *nbd = args->nbd;
623 struct nbd_config *config = nbd->config;
624 struct nbd_cmd *cmd;
625 int ret = 0;
626
627 while (1) {
628 cmd = nbd_read_stat(nbd, args->index);
629 if (IS_ERR(cmd)) {
630 struct nbd_sock *nsock = config->socks[args->index];
631
632 mutex_lock(&nsock->tx_lock);
633 nbd_mark_nsock_dead(nbd, nsock, 1);
634 mutex_unlock(&nsock->tx_lock);
635 ret = PTR_ERR(cmd);
636 break;
637 }
638
639 nbd_end_request(cmd);
640 }
641 atomic_dec(&config->recv_threads);
642 wake_up(&config->recv_wq);
643 nbd_config_put(nbd);
644 kfree(args);
645 }
646
647 static void nbd_clear_req(struct request *req, void *data, bool reserved)
648 {
649 struct nbd_cmd *cmd;
650
651 if (!blk_mq_request_started(req))
652 return;
653 cmd = blk_mq_rq_to_pdu(req);
654 req->errors = -EIO;
655 nbd_end_request(cmd);
656 }
657
658 static void nbd_clear_que(struct nbd_device *nbd)
659 {
660 blk_mq_stop_hw_queues(nbd->disk->queue);
661 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
662 blk_mq_start_hw_queues(nbd->disk->queue);
663 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
664 }
665
666 static int find_fallback(struct nbd_device *nbd, int index)
667 {
668 struct nbd_config *config = nbd->config;
669 int new_index = -1;
670 struct nbd_sock *nsock = config->socks[index];
671 int fallback = nsock->fallback_index;
672
673 if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
674 return new_index;
675
676 if (config->num_connections <= 1) {
677 dev_err_ratelimited(disk_to_dev(nbd->disk),
678 "Attempted send on invalid socket\n");
679 return new_index;
680 }
681
682 if (fallback >= 0 && fallback < config->num_connections &&
683 !config->socks[fallback]->dead)
684 return fallback;
685
686 if (nsock->fallback_index < 0 ||
687 nsock->fallback_index >= config->num_connections ||
688 config->socks[nsock->fallback_index]->dead) {
689 int i;
690 for (i = 0; i < config->num_connections; i++) {
691 if (i == index)
692 continue;
693 if (!config->socks[i]->dead) {
694 new_index = i;
695 break;
696 }
697 }
698 nsock->fallback_index = new_index;
699 if (new_index < 0) {
700 dev_err_ratelimited(disk_to_dev(nbd->disk),
701 "Dead connection, failed to find a fallback\n");
702 return new_index;
703 }
704 }
705 new_index = nsock->fallback_index;
706 return new_index;
707 }
708
709 static int wait_for_reconnect(struct nbd_device *nbd)
710 {
711 struct nbd_config *config = nbd->config;
712 if (!config->dead_conn_timeout)
713 return 0;
714 if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
715 return 0;
716 wait_event_interruptible_timeout(config->conn_wait,
717 atomic_read(&config->live_connections),
718 config->dead_conn_timeout);
719 return atomic_read(&config->live_connections);
720 }
721
722 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
723 {
724 struct request *req = blk_mq_rq_from_pdu(cmd);
725 struct nbd_device *nbd = cmd->nbd;
726 struct nbd_config *config;
727 struct nbd_sock *nsock;
728 int ret;
729
730 if (!refcount_inc_not_zero(&nbd->config_refs)) {
731 dev_err_ratelimited(disk_to_dev(nbd->disk),
732 "Socks array is empty\n");
733 return -EINVAL;
734 }
735 config = nbd->config;
736
737 if (index >= config->num_connections) {
738 dev_err_ratelimited(disk_to_dev(nbd->disk),
739 "Attempted send on invalid socket\n");
740 nbd_config_put(nbd);
741 return -EINVAL;
742 }
743 req->errors = 0;
744 again:
745 nsock = config->socks[index];
746 mutex_lock(&nsock->tx_lock);
747 if (nsock->dead) {
748 int old_index = index;
749 index = find_fallback(nbd, index);
750 mutex_unlock(&nsock->tx_lock);
751 if (index < 0) {
752 if (wait_for_reconnect(nbd)) {
753 index = old_index;
754 goto again;
755 }
756 /* All the sockets should already be down at this point,
757 * we just want to make sure that DISCONNECTED is set so
758 * any requests that come in that were queue'ed waiting
759 * for the reconnect timer don't trigger the timer again
760 * and instead just error out.
761 */
762 sock_shutdown(nbd);
763 nbd_config_put(nbd);
764 return -EIO;
765 }
766 goto again;
767 }
768
769 /* Handle the case that we have a pending request that was partially
770 * transmitted that _has_ to be serviced first. We need to call requeue
771 * here so that it gets put _after_ the request that is already on the
772 * dispatch list.
773 */
774 if (unlikely(nsock->pending && nsock->pending != req)) {
775 blk_mq_requeue_request(req, true);
776 ret = 0;
777 goto out;
778 }
779 /*
780 * Some failures are related to the link going down, so anything that
781 * returns EAGAIN can be retried on a different socket.
782 */
783 ret = nbd_send_cmd(nbd, cmd, index);
784 if (ret == -EAGAIN) {
785 dev_err_ratelimited(disk_to_dev(nbd->disk),
786 "Request send failed trying another connection\n");
787 nbd_mark_nsock_dead(nbd, nsock, 1);
788 mutex_unlock(&nsock->tx_lock);
789 goto again;
790 }
791 out:
792 mutex_unlock(&nsock->tx_lock);
793 nbd_config_put(nbd);
794 return ret;
795 }
796
797 static int nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
798 const struct blk_mq_queue_data *bd)
799 {
800 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
801 int ret;
802
803 /*
804 * Since we look at the bio's to send the request over the network we
805 * need to make sure the completion work doesn't mark this request done
806 * before we are done doing our send. This keeps us from dereferencing
807 * freed data if we have particularly fast completions (ie we get the
808 * completion before we exit sock_xmit on the last bvec) or in the case
809 * that the server is misbehaving (or there was an error) before we're
810 * done sending everything over the wire.
811 */
812 init_completion(&cmd->send_complete);
813 blk_mq_start_request(bd->rq);
814
815 /* We can be called directly from the user space process, which means we
816 * could possibly have signals pending so our sendmsg will fail. In
817 * this case we need to return that we are busy, otherwise error out as
818 * appropriate.
819 */
820 ret = nbd_handle_cmd(cmd, hctx->queue_num);
821 if (ret < 0)
822 ret = BLK_MQ_RQ_QUEUE_ERROR;
823 if (!ret)
824 ret = BLK_MQ_RQ_QUEUE_OK;
825 complete(&cmd->send_complete);
826
827 return ret;
828 }
829
830 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
831 bool netlink)
832 {
833 struct nbd_config *config = nbd->config;
834 struct socket *sock;
835 struct nbd_sock **socks;
836 struct nbd_sock *nsock;
837 int err;
838
839 sock = sockfd_lookup(arg, &err);
840 if (!sock)
841 return err;
842
843 if (!netlink && !nbd->task_setup &&
844 !test_bit(NBD_BOUND, &config->runtime_flags))
845 nbd->task_setup = current;
846
847 if (!netlink &&
848 (nbd->task_setup != current ||
849 test_bit(NBD_BOUND, &config->runtime_flags))) {
850 dev_err(disk_to_dev(nbd->disk),
851 "Device being setup by another task");
852 sockfd_put(sock);
853 return -EBUSY;
854 }
855
856 socks = krealloc(config->socks, (config->num_connections + 1) *
857 sizeof(struct nbd_sock *), GFP_KERNEL);
858 if (!socks) {
859 sockfd_put(sock);
860 return -ENOMEM;
861 }
862 nsock = kzalloc(sizeof(struct nbd_sock), GFP_KERNEL);
863 if (!nsock) {
864 sockfd_put(sock);
865 return -ENOMEM;
866 }
867
868 config->socks = socks;
869
870 nsock->fallback_index = -1;
871 nsock->dead = false;
872 mutex_init(&nsock->tx_lock);
873 nsock->sock = sock;
874 nsock->pending = NULL;
875 nsock->sent = 0;
876 nsock->cookie = 0;
877 socks[config->num_connections++] = nsock;
878 atomic_inc(&config->live_connections);
879
880 return 0;
881 }
882
883 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
884 {
885 struct nbd_config *config = nbd->config;
886 struct socket *sock, *old;
887 struct recv_thread_args *args;
888 int i;
889 int err;
890
891 sock = sockfd_lookup(arg, &err);
892 if (!sock)
893 return err;
894
895 args = kzalloc(sizeof(*args), GFP_KERNEL);
896 if (!args) {
897 sockfd_put(sock);
898 return -ENOMEM;
899 }
900
901 for (i = 0; i < config->num_connections; i++) {
902 struct nbd_sock *nsock = config->socks[i];
903
904 if (!nsock->dead)
905 continue;
906
907 mutex_lock(&nsock->tx_lock);
908 if (!nsock->dead) {
909 mutex_unlock(&nsock->tx_lock);
910 continue;
911 }
912 sk_set_memalloc(sock->sk);
913 atomic_inc(&config->recv_threads);
914 refcount_inc(&nbd->config_refs);
915 old = nsock->sock;
916 nsock->fallback_index = -1;
917 nsock->sock = sock;
918 nsock->dead = false;
919 INIT_WORK(&args->work, recv_work);
920 args->index = i;
921 args->nbd = nbd;
922 nsock->cookie++;
923 mutex_unlock(&nsock->tx_lock);
924 sockfd_put(old);
925
926 /* We take the tx_mutex in an error path in the recv_work, so we
927 * need to queue_work outside of the tx_mutex.
928 */
929 queue_work(recv_workqueue, &args->work);
930
931 atomic_inc(&config->live_connections);
932 wake_up(&config->conn_wait);
933 return 0;
934 }
935 sockfd_put(sock);
936 kfree(args);
937 return -ENOSPC;
938 }
939
940 /* Reset all properties of an NBD device */
941 static void nbd_reset(struct nbd_device *nbd)
942 {
943 nbd->config = NULL;
944 nbd->tag_set.timeout = 0;
945 queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, nbd->disk->queue);
946 }
947
948 static void nbd_bdev_reset(struct block_device *bdev)
949 {
950 if (bdev->bd_openers > 1)
951 return;
952 bd_set_size(bdev, 0);
953 if (max_part > 0) {
954 blkdev_reread_part(bdev);
955 bdev->bd_invalidated = 1;
956 }
957 }
958
959 static void nbd_parse_flags(struct nbd_device *nbd)
960 {
961 struct nbd_config *config = nbd->config;
962 if (config->flags & NBD_FLAG_READ_ONLY)
963 set_disk_ro(nbd->disk, true);
964 else
965 set_disk_ro(nbd->disk, false);
966 if (config->flags & NBD_FLAG_SEND_TRIM)
967 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, nbd->disk->queue);
968 if (config->flags & NBD_FLAG_SEND_FLUSH)
969 blk_queue_write_cache(nbd->disk->queue, true, false);
970 else
971 blk_queue_write_cache(nbd->disk->queue, false, false);
972 }
973
974 static void send_disconnects(struct nbd_device *nbd)
975 {
976 struct nbd_config *config = nbd->config;
977 struct nbd_request request = {
978 .magic = htonl(NBD_REQUEST_MAGIC),
979 .type = htonl(NBD_CMD_DISC),
980 };
981 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
982 struct iov_iter from;
983 int i, ret;
984
985 for (i = 0; i < config->num_connections; i++) {
986 iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
987 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
988 if (ret <= 0)
989 dev_err(disk_to_dev(nbd->disk),
990 "Send disconnect failed %d\n", ret);
991 }
992 }
993
994 static int nbd_disconnect(struct nbd_device *nbd)
995 {
996 struct nbd_config *config = nbd->config;
997
998 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
999 if (!test_and_set_bit(NBD_DISCONNECT_REQUESTED,
1000 &config->runtime_flags))
1001 send_disconnects(nbd);
1002 return 0;
1003 }
1004
1005 static void nbd_clear_sock(struct nbd_device *nbd)
1006 {
1007 sock_shutdown(nbd);
1008 nbd_clear_que(nbd);
1009 nbd->task_setup = NULL;
1010 }
1011
1012 static void nbd_config_put(struct nbd_device *nbd)
1013 {
1014 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1015 &nbd->config_lock)) {
1016 struct nbd_config *config = nbd->config;
1017 nbd_dev_dbg_close(nbd);
1018 nbd_size_clear(nbd);
1019 if (test_and_clear_bit(NBD_HAS_PID_FILE,
1020 &config->runtime_flags))
1021 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1022 nbd->task_recv = NULL;
1023 nbd_clear_sock(nbd);
1024 if (config->num_connections) {
1025 int i;
1026 for (i = 0; i < config->num_connections; i++) {
1027 sockfd_put(config->socks[i]->sock);
1028 kfree(config->socks[i]);
1029 }
1030 kfree(config->socks);
1031 }
1032 nbd_reset(nbd);
1033
1034 mutex_unlock(&nbd->config_lock);
1035 nbd_put(nbd);
1036 module_put(THIS_MODULE);
1037 }
1038 }
1039
1040 static int nbd_start_device(struct nbd_device *nbd)
1041 {
1042 struct nbd_config *config = nbd->config;
1043 int num_connections = config->num_connections;
1044 int error = 0, i;
1045
1046 if (nbd->task_recv)
1047 return -EBUSY;
1048 if (!config->socks)
1049 return -EINVAL;
1050 if (num_connections > 1 &&
1051 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1052 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1053 return -EINVAL;
1054 }
1055
1056 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1057 nbd->task_recv = current;
1058
1059 nbd_parse_flags(nbd);
1060
1061 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1062 if (error) {
1063 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
1064 return error;
1065 }
1066 set_bit(NBD_HAS_PID_FILE, &config->runtime_flags);
1067
1068 nbd_dev_dbg_init(nbd);
1069 for (i = 0; i < num_connections; i++) {
1070 struct recv_thread_args *args;
1071
1072 args = kzalloc(sizeof(*args), GFP_KERNEL);
1073 if (!args) {
1074 sock_shutdown(nbd);
1075 return -ENOMEM;
1076 }
1077 sk_set_memalloc(config->socks[i]->sock->sk);
1078 atomic_inc(&config->recv_threads);
1079 refcount_inc(&nbd->config_refs);
1080 INIT_WORK(&args->work, recv_work);
1081 args->nbd = nbd;
1082 args->index = i;
1083 queue_work(recv_workqueue, &args->work);
1084 }
1085 return error;
1086 }
1087
1088 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1089 {
1090 struct nbd_config *config = nbd->config;
1091 int ret;
1092
1093 ret = nbd_start_device(nbd);
1094 if (ret)
1095 return ret;
1096
1097 bd_set_size(bdev, config->bytesize);
1098 if (max_part)
1099 bdev->bd_invalidated = 1;
1100 mutex_unlock(&nbd->config_lock);
1101 ret = wait_event_interruptible(config->recv_wq,
1102 atomic_read(&config->recv_threads) == 0);
1103 if (ret)
1104 sock_shutdown(nbd);
1105 mutex_lock(&nbd->config_lock);
1106 bd_set_size(bdev, 0);
1107 /* user requested, ignore socket errors */
1108 if (test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags))
1109 ret = 0;
1110 if (test_bit(NBD_TIMEDOUT, &config->runtime_flags))
1111 ret = -ETIMEDOUT;
1112 return ret;
1113 }
1114
1115 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1116 struct block_device *bdev)
1117 {
1118 sock_shutdown(nbd);
1119 kill_bdev(bdev);
1120 nbd_bdev_reset(bdev);
1121 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1122 &nbd->config->runtime_flags))
1123 nbd_config_put(nbd);
1124 }
1125
1126 /* Must be called with config_lock held */
1127 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1128 unsigned int cmd, unsigned long arg)
1129 {
1130 struct nbd_config *config = nbd->config;
1131
1132 switch (cmd) {
1133 case NBD_DISCONNECT:
1134 return nbd_disconnect(nbd);
1135 case NBD_CLEAR_SOCK:
1136 nbd_clear_sock_ioctl(nbd, bdev);
1137 return 0;
1138 case NBD_SET_SOCK:
1139 return nbd_add_socket(nbd, arg, false);
1140 case NBD_SET_BLKSIZE:
1141 nbd_size_set(nbd, arg,
1142 div_s64(config->bytesize, arg));
1143 return 0;
1144 case NBD_SET_SIZE:
1145 nbd_size_set(nbd, config->blksize,
1146 div_s64(arg, config->blksize));
1147 return 0;
1148 case NBD_SET_SIZE_BLOCKS:
1149 nbd_size_set(nbd, config->blksize, arg);
1150 return 0;
1151 case NBD_SET_TIMEOUT:
1152 if (arg) {
1153 nbd->tag_set.timeout = arg * HZ;
1154 blk_queue_rq_timeout(nbd->disk->queue, arg * HZ);
1155 }
1156 return 0;
1157
1158 case NBD_SET_FLAGS:
1159 config->flags = arg;
1160 return 0;
1161 case NBD_DO_IT:
1162 return nbd_start_device_ioctl(nbd, bdev);
1163 case NBD_CLEAR_QUE:
1164 /*
1165 * This is for compatibility only. The queue is always cleared
1166 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1167 */
1168 return 0;
1169 case NBD_PRINT_DEBUG:
1170 /*
1171 * For compatibility only, we no longer keep a list of
1172 * outstanding requests.
1173 */
1174 return 0;
1175 }
1176 return -ENOTTY;
1177 }
1178
1179 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1180 unsigned int cmd, unsigned long arg)
1181 {
1182 struct nbd_device *nbd = bdev->bd_disk->private_data;
1183 struct nbd_config *config = nbd->config;
1184 int error = -EINVAL;
1185
1186 if (!capable(CAP_SYS_ADMIN))
1187 return -EPERM;
1188
1189 mutex_lock(&nbd->config_lock);
1190
1191 /* Don't allow ioctl operations on a nbd device that was created with
1192 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1193 */
1194 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1195 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1196 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1197 else
1198 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1199 mutex_unlock(&nbd->config_lock);
1200 return error;
1201 }
1202
1203 static struct nbd_config *nbd_alloc_config(void)
1204 {
1205 struct nbd_config *config;
1206
1207 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1208 if (!config)
1209 return NULL;
1210 atomic_set(&config->recv_threads, 0);
1211 init_waitqueue_head(&config->recv_wq);
1212 init_waitqueue_head(&config->conn_wait);
1213 config->blksize = 1024;
1214 atomic_set(&config->live_connections, 0);
1215 try_module_get(THIS_MODULE);
1216 return config;
1217 }
1218
1219 static int nbd_open(struct block_device *bdev, fmode_t mode)
1220 {
1221 struct nbd_device *nbd;
1222 int ret = 0;
1223
1224 mutex_lock(&nbd_index_mutex);
1225 nbd = bdev->bd_disk->private_data;
1226 if (!nbd) {
1227 ret = -ENXIO;
1228 goto out;
1229 }
1230 if (!refcount_inc_not_zero(&nbd->refs)) {
1231 ret = -ENXIO;
1232 goto out;
1233 }
1234 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1235 struct nbd_config *config;
1236
1237 mutex_lock(&nbd->config_lock);
1238 if (refcount_inc_not_zero(&nbd->config_refs)) {
1239 mutex_unlock(&nbd->config_lock);
1240 goto out;
1241 }
1242 config = nbd->config = nbd_alloc_config();
1243 if (!config) {
1244 ret = -ENOMEM;
1245 mutex_unlock(&nbd->config_lock);
1246 goto out;
1247 }
1248 refcount_set(&nbd->config_refs, 1);
1249 refcount_inc(&nbd->refs);
1250 mutex_unlock(&nbd->config_lock);
1251 }
1252 out:
1253 mutex_unlock(&nbd_index_mutex);
1254 return ret;
1255 }
1256
1257 static void nbd_release(struct gendisk *disk, fmode_t mode)
1258 {
1259 struct nbd_device *nbd = disk->private_data;
1260 nbd_config_put(nbd);
1261 nbd_put(nbd);
1262 }
1263
1264 static const struct block_device_operations nbd_fops =
1265 {
1266 .owner = THIS_MODULE,
1267 .open = nbd_open,
1268 .release = nbd_release,
1269 .ioctl = nbd_ioctl,
1270 .compat_ioctl = nbd_ioctl,
1271 };
1272
1273 #if IS_ENABLED(CONFIG_DEBUG_FS)
1274
1275 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1276 {
1277 struct nbd_device *nbd = s->private;
1278
1279 if (nbd->task_recv)
1280 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1281
1282 return 0;
1283 }
1284
1285 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1286 {
1287 return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1288 }
1289
1290 static const struct file_operations nbd_dbg_tasks_ops = {
1291 .open = nbd_dbg_tasks_open,
1292 .read = seq_read,
1293 .llseek = seq_lseek,
1294 .release = single_release,
1295 };
1296
1297 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1298 {
1299 struct nbd_device *nbd = s->private;
1300 u32 flags = nbd->config->flags;
1301
1302 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1303
1304 seq_puts(s, "Known flags:\n");
1305
1306 if (flags & NBD_FLAG_HAS_FLAGS)
1307 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1308 if (flags & NBD_FLAG_READ_ONLY)
1309 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1310 if (flags & NBD_FLAG_SEND_FLUSH)
1311 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1312 if (flags & NBD_FLAG_SEND_TRIM)
1313 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1314
1315 return 0;
1316 }
1317
1318 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1319 {
1320 return single_open(file, nbd_dbg_flags_show, inode->i_private);
1321 }
1322
1323 static const struct file_operations nbd_dbg_flags_ops = {
1324 .open = nbd_dbg_flags_open,
1325 .read = seq_read,
1326 .llseek = seq_lseek,
1327 .release = single_release,
1328 };
1329
1330 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1331 {
1332 struct dentry *dir;
1333 struct nbd_config *config = nbd->config;
1334
1335 if (!nbd_dbg_dir)
1336 return -EIO;
1337
1338 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1339 if (!dir) {
1340 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1341 nbd_name(nbd));
1342 return -EIO;
1343 }
1344 config->dbg_dir = dir;
1345
1346 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
1347 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1348 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1349 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1350 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
1351
1352 return 0;
1353 }
1354
1355 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1356 {
1357 debugfs_remove_recursive(nbd->config->dbg_dir);
1358 }
1359
1360 static int nbd_dbg_init(void)
1361 {
1362 struct dentry *dbg_dir;
1363
1364 dbg_dir = debugfs_create_dir("nbd", NULL);
1365 if (!dbg_dir)
1366 return -EIO;
1367
1368 nbd_dbg_dir = dbg_dir;
1369
1370 return 0;
1371 }
1372
1373 static void nbd_dbg_close(void)
1374 {
1375 debugfs_remove_recursive(nbd_dbg_dir);
1376 }
1377
1378 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1379
1380 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1381 {
1382 return 0;
1383 }
1384
1385 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1386 {
1387 }
1388
1389 static int nbd_dbg_init(void)
1390 {
1391 return 0;
1392 }
1393
1394 static void nbd_dbg_close(void)
1395 {
1396 }
1397
1398 #endif
1399
1400 static int nbd_init_request(void *data, struct request *rq,
1401 unsigned int hctx_idx, unsigned int request_idx,
1402 unsigned int numa_node)
1403 {
1404 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1405 cmd->nbd = data;
1406 return 0;
1407 }
1408
1409 static const struct blk_mq_ops nbd_mq_ops = {
1410 .queue_rq = nbd_queue_rq,
1411 .init_request = nbd_init_request,
1412 .timeout = nbd_xmit_timeout,
1413 };
1414
1415 static int nbd_dev_add(int index)
1416 {
1417 struct nbd_device *nbd;
1418 struct gendisk *disk;
1419 struct request_queue *q;
1420 int err = -ENOMEM;
1421
1422 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1423 if (!nbd)
1424 goto out;
1425
1426 disk = alloc_disk(1 << part_shift);
1427 if (!disk)
1428 goto out_free_nbd;
1429
1430 if (index >= 0) {
1431 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1432 GFP_KERNEL);
1433 if (err == -ENOSPC)
1434 err = -EEXIST;
1435 } else {
1436 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1437 if (err >= 0)
1438 index = err;
1439 }
1440 if (err < 0)
1441 goto out_free_disk;
1442
1443 nbd->index = index;
1444 nbd->disk = disk;
1445 nbd->tag_set.ops = &nbd_mq_ops;
1446 nbd->tag_set.nr_hw_queues = 1;
1447 nbd->tag_set.queue_depth = 128;
1448 nbd->tag_set.numa_node = NUMA_NO_NODE;
1449 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1450 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1451 BLK_MQ_F_SG_MERGE | BLK_MQ_F_BLOCKING;
1452 nbd->tag_set.driver_data = nbd;
1453
1454 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1455 if (err)
1456 goto out_free_idr;
1457
1458 q = blk_mq_init_queue(&nbd->tag_set);
1459 if (IS_ERR(q)) {
1460 err = PTR_ERR(q);
1461 goto out_free_tags;
1462 }
1463 disk->queue = q;
1464
1465 /*
1466 * Tell the block layer that we are not a rotational device
1467 */
1468 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, disk->queue);
1469 queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1470 disk->queue->limits.discard_granularity = 512;
1471 blk_queue_max_discard_sectors(disk->queue, UINT_MAX);
1472 blk_queue_max_hw_sectors(disk->queue, 65536);
1473 disk->queue->limits.max_sectors = 256;
1474
1475 mutex_init(&nbd->config_lock);
1476 refcount_set(&nbd->config_refs, 0);
1477 refcount_set(&nbd->refs, 1);
1478 INIT_LIST_HEAD(&nbd->list);
1479 disk->major = NBD_MAJOR;
1480 disk->first_minor = index << part_shift;
1481 disk->fops = &nbd_fops;
1482 disk->private_data = nbd;
1483 sprintf(disk->disk_name, "nbd%d", index);
1484 nbd_reset(nbd);
1485 add_disk(disk);
1486 nbd_total_devices++;
1487 return index;
1488
1489 out_free_tags:
1490 blk_mq_free_tag_set(&nbd->tag_set);
1491 out_free_idr:
1492 idr_remove(&nbd_index_idr, index);
1493 out_free_disk:
1494 put_disk(disk);
1495 out_free_nbd:
1496 kfree(nbd);
1497 out:
1498 return err;
1499 }
1500
1501 static int find_free_cb(int id, void *ptr, void *data)
1502 {
1503 struct nbd_device *nbd = ptr;
1504 struct nbd_device **found = data;
1505
1506 if (!refcount_read(&nbd->config_refs)) {
1507 *found = nbd;
1508 return 1;
1509 }
1510 return 0;
1511 }
1512
1513 /* Netlink interface. */
1514 static struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1515 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1516 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1517 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1518 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1519 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1520 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1521 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1522 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1523 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1524 };
1525
1526 static struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1527 [NBD_SOCK_FD] = { .type = NLA_U32 },
1528 };
1529
1530 /* We don't use this right now since we don't parse the incoming list, but we
1531 * still want it here so userspace knows what to expect.
1532 */
1533 static struct nla_policy __attribute__((unused))
1534 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1535 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1536 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1537 };
1538
1539 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1540 {
1541 struct nbd_device *nbd = NULL;
1542 struct nbd_config *config;
1543 int index = -1;
1544 int ret;
1545 bool put_dev = false;
1546
1547 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1548 return -EPERM;
1549
1550 if (info->attrs[NBD_ATTR_INDEX])
1551 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1552 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1553 printk(KERN_ERR "nbd: must specify at least one socket\n");
1554 return -EINVAL;
1555 }
1556 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1557 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1558 return -EINVAL;
1559 }
1560 again:
1561 mutex_lock(&nbd_index_mutex);
1562 if (index == -1) {
1563 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1564 if (ret == 0) {
1565 int new_index;
1566 new_index = nbd_dev_add(-1);
1567 if (new_index < 0) {
1568 mutex_unlock(&nbd_index_mutex);
1569 printk(KERN_ERR "nbd: failed to add new device\n");
1570 return ret;
1571 }
1572 nbd = idr_find(&nbd_index_idr, new_index);
1573 }
1574 } else {
1575 nbd = idr_find(&nbd_index_idr, index);
1576 }
1577 if (!nbd) {
1578 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1579 index);
1580 mutex_unlock(&nbd_index_mutex);
1581 return -EINVAL;
1582 }
1583 if (!refcount_inc_not_zero(&nbd->refs)) {
1584 mutex_unlock(&nbd_index_mutex);
1585 if (index == -1)
1586 goto again;
1587 printk(KERN_ERR "nbd: device at index %d is going down\n",
1588 index);
1589 return -EINVAL;
1590 }
1591 mutex_unlock(&nbd_index_mutex);
1592
1593 mutex_lock(&nbd->config_lock);
1594 if (refcount_read(&nbd->config_refs)) {
1595 mutex_unlock(&nbd->config_lock);
1596 nbd_put(nbd);
1597 if (index == -1)
1598 goto again;
1599 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1600 return -EBUSY;
1601 }
1602 if (WARN_ON(nbd->config)) {
1603 mutex_unlock(&nbd->config_lock);
1604 nbd_put(nbd);
1605 return -EINVAL;
1606 }
1607 config = nbd->config = nbd_alloc_config();
1608 if (!nbd->config) {
1609 mutex_unlock(&nbd->config_lock);
1610 nbd_put(nbd);
1611 printk(KERN_ERR "nbd: couldn't allocate config\n");
1612 return -ENOMEM;
1613 }
1614 refcount_set(&nbd->config_refs, 1);
1615 set_bit(NBD_BOUND, &config->runtime_flags);
1616
1617 if (info->attrs[NBD_ATTR_SIZE_BYTES]) {
1618 u64 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1619 nbd_size_set(nbd, config->blksize,
1620 div64_u64(bytes, config->blksize));
1621 }
1622 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1623 u64 bsize =
1624 nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1625 nbd_size_set(nbd, bsize, div64_u64(config->bytesize, bsize));
1626 }
1627 if (info->attrs[NBD_ATTR_TIMEOUT]) {
1628 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1629 nbd->tag_set.timeout = timeout * HZ;
1630 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1631 }
1632 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1633 config->dead_conn_timeout =
1634 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1635 config->dead_conn_timeout *= HZ;
1636 }
1637 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1638 config->flags =
1639 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1640 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1641 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1642 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1643 set_bit(NBD_DESTROY_ON_DISCONNECT,
1644 &config->runtime_flags);
1645 put_dev = true;
1646 }
1647 }
1648
1649 if (info->attrs[NBD_ATTR_SOCKETS]) {
1650 struct nlattr *attr;
1651 int rem, fd;
1652
1653 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1654 rem) {
1655 struct nlattr *socks[NBD_SOCK_MAX+1];
1656
1657 if (nla_type(attr) != NBD_SOCK_ITEM) {
1658 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1659 ret = -EINVAL;
1660 goto out;
1661 }
1662 ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
1663 nbd_sock_policy);
1664 if (ret != 0) {
1665 printk(KERN_ERR "nbd: error processing sock list\n");
1666 ret = -EINVAL;
1667 goto out;
1668 }
1669 if (!socks[NBD_SOCK_FD])
1670 continue;
1671 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1672 ret = nbd_add_socket(nbd, fd, true);
1673 if (ret)
1674 goto out;
1675 }
1676 }
1677 ret = nbd_start_device(nbd);
1678 out:
1679 mutex_unlock(&nbd->config_lock);
1680 if (!ret) {
1681 set_bit(NBD_HAS_CONFIG_REF, &config->runtime_flags);
1682 refcount_inc(&nbd->config_refs);
1683 nbd_connect_reply(info, nbd->index);
1684 }
1685 nbd_config_put(nbd);
1686 if (put_dev)
1687 nbd_put(nbd);
1688 return ret;
1689 }
1690
1691 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
1692 {
1693 struct nbd_device *nbd;
1694 int index;
1695
1696 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1697 return -EPERM;
1698
1699 if (!info->attrs[NBD_ATTR_INDEX]) {
1700 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
1701 return -EINVAL;
1702 }
1703 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1704 mutex_lock(&nbd_index_mutex);
1705 nbd = idr_find(&nbd_index_idr, index);
1706 if (!nbd) {
1707 mutex_unlock(&nbd_index_mutex);
1708 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1709 index);
1710 return -EINVAL;
1711 }
1712 if (!refcount_inc_not_zero(&nbd->refs)) {
1713 mutex_unlock(&nbd_index_mutex);
1714 printk(KERN_ERR "nbd: device at index %d is going down\n",
1715 index);
1716 return -EINVAL;
1717 }
1718 mutex_unlock(&nbd_index_mutex);
1719 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1720 nbd_put(nbd);
1721 return 0;
1722 }
1723 mutex_lock(&nbd->config_lock);
1724 nbd_disconnect(nbd);
1725 mutex_unlock(&nbd->config_lock);
1726 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1727 &nbd->config->runtime_flags))
1728 nbd_config_put(nbd);
1729 nbd_config_put(nbd);
1730 nbd_put(nbd);
1731 return 0;
1732 }
1733
1734 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
1735 {
1736 struct nbd_device *nbd = NULL;
1737 struct nbd_config *config;
1738 int index;
1739 int ret = -EINVAL;
1740 bool put_dev = false;
1741
1742 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1743 return -EPERM;
1744
1745 if (!info->attrs[NBD_ATTR_INDEX]) {
1746 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
1747 return -EINVAL;
1748 }
1749 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1750 mutex_lock(&nbd_index_mutex);
1751 nbd = idr_find(&nbd_index_idr, index);
1752 if (!nbd) {
1753 mutex_unlock(&nbd_index_mutex);
1754 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
1755 index);
1756 return -EINVAL;
1757 }
1758 if (!refcount_inc_not_zero(&nbd->refs)) {
1759 mutex_unlock(&nbd_index_mutex);
1760 printk(KERN_ERR "nbd: device at index %d is going down\n",
1761 index);
1762 return -EINVAL;
1763 }
1764 mutex_unlock(&nbd_index_mutex);
1765
1766 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1767 dev_err(nbd_to_dev(nbd),
1768 "not configured, cannot reconfigure\n");
1769 nbd_put(nbd);
1770 return -EINVAL;
1771 }
1772
1773 mutex_lock(&nbd->config_lock);
1774 config = nbd->config;
1775 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1776 !nbd->task_recv) {
1777 dev_err(nbd_to_dev(nbd),
1778 "not configured, cannot reconfigure\n");
1779 goto out;
1780 }
1781
1782 if (info->attrs[NBD_ATTR_TIMEOUT]) {
1783 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1784 nbd->tag_set.timeout = timeout * HZ;
1785 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1786 }
1787 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1788 config->dead_conn_timeout =
1789 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1790 config->dead_conn_timeout *= HZ;
1791 }
1792 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1793 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1794 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1795 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
1796 &config->runtime_flags))
1797 put_dev = true;
1798 } else {
1799 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
1800 &config->runtime_flags))
1801 refcount_inc(&nbd->refs);
1802 }
1803 }
1804
1805 if (info->attrs[NBD_ATTR_SOCKETS]) {
1806 struct nlattr *attr;
1807 int rem, fd;
1808
1809 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1810 rem) {
1811 struct nlattr *socks[NBD_SOCK_MAX+1];
1812
1813 if (nla_type(attr) != NBD_SOCK_ITEM) {
1814 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1815 ret = -EINVAL;
1816 goto out;
1817 }
1818 ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
1819 nbd_sock_policy);
1820 if (ret != 0) {
1821 printk(KERN_ERR "nbd: error processing sock list\n");
1822 ret = -EINVAL;
1823 goto out;
1824 }
1825 if (!socks[NBD_SOCK_FD])
1826 continue;
1827 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1828 ret = nbd_reconnect_socket(nbd, fd);
1829 if (ret) {
1830 if (ret == -ENOSPC)
1831 ret = 0;
1832 goto out;
1833 }
1834 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
1835 }
1836 }
1837 out:
1838 mutex_unlock(&nbd->config_lock);
1839 nbd_config_put(nbd);
1840 nbd_put(nbd);
1841 if (put_dev)
1842 nbd_put(nbd);
1843 return ret;
1844 }
1845
1846 static const struct genl_ops nbd_connect_genl_ops[] = {
1847 {
1848 .cmd = NBD_CMD_CONNECT,
1849 .policy = nbd_attr_policy,
1850 .doit = nbd_genl_connect,
1851 },
1852 {
1853 .cmd = NBD_CMD_DISCONNECT,
1854 .policy = nbd_attr_policy,
1855 .doit = nbd_genl_disconnect,
1856 },
1857 {
1858 .cmd = NBD_CMD_RECONFIGURE,
1859 .policy = nbd_attr_policy,
1860 .doit = nbd_genl_reconfigure,
1861 },
1862 {
1863 .cmd = NBD_CMD_STATUS,
1864 .policy = nbd_attr_policy,
1865 .doit = nbd_genl_status,
1866 },
1867 };
1868
1869 static const struct genl_multicast_group nbd_mcast_grps[] = {
1870 { .name = NBD_GENL_MCAST_GROUP_NAME, },
1871 };
1872
1873 static struct genl_family nbd_genl_family __ro_after_init = {
1874 .hdrsize = 0,
1875 .name = NBD_GENL_FAMILY_NAME,
1876 .version = NBD_GENL_VERSION,
1877 .module = THIS_MODULE,
1878 .ops = nbd_connect_genl_ops,
1879 .n_ops = ARRAY_SIZE(nbd_connect_genl_ops),
1880 .maxattr = NBD_ATTR_MAX,
1881 .mcgrps = nbd_mcast_grps,
1882 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
1883 };
1884
1885 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
1886 {
1887 struct nlattr *dev_opt;
1888 u8 connected = 0;
1889 int ret;
1890
1891 /* This is a little racey, but for status it's ok. The
1892 * reason we don't take a ref here is because we can't
1893 * take a ref in the index == -1 case as we would need
1894 * to put under the nbd_index_mutex, which could
1895 * deadlock if we are configured to remove ourselves
1896 * once we're disconnected.
1897 */
1898 if (refcount_read(&nbd->config_refs))
1899 connected = 1;
1900 dev_opt = nla_nest_start(reply, NBD_DEVICE_ITEM);
1901 if (!dev_opt)
1902 return -EMSGSIZE;
1903 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
1904 if (ret)
1905 return -EMSGSIZE;
1906 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
1907 connected);
1908 if (ret)
1909 return -EMSGSIZE;
1910 nla_nest_end(reply, dev_opt);
1911 return 0;
1912 }
1913
1914 static int status_cb(int id, void *ptr, void *data)
1915 {
1916 struct nbd_device *nbd = ptr;
1917 return populate_nbd_status(nbd, (struct sk_buff *)data);
1918 }
1919
1920 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
1921 {
1922 struct nlattr *dev_list;
1923 struct sk_buff *reply;
1924 void *reply_head;
1925 size_t msg_size;
1926 int index = -1;
1927 int ret = -ENOMEM;
1928
1929 if (info->attrs[NBD_ATTR_INDEX])
1930 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1931
1932 mutex_lock(&nbd_index_mutex);
1933
1934 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
1935 nla_attr_size(sizeof(u8)));
1936 msg_size *= (index == -1) ? nbd_total_devices : 1;
1937
1938 reply = genlmsg_new(msg_size, GFP_KERNEL);
1939 if (!reply)
1940 goto out;
1941 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
1942 NBD_CMD_STATUS);
1943 if (!reply_head) {
1944 nlmsg_free(reply);
1945 goto out;
1946 }
1947
1948 dev_list = nla_nest_start(reply, NBD_ATTR_DEVICE_LIST);
1949 if (index == -1) {
1950 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
1951 if (ret) {
1952 nlmsg_free(reply);
1953 goto out;
1954 }
1955 } else {
1956 struct nbd_device *nbd;
1957 nbd = idr_find(&nbd_index_idr, index);
1958 if (nbd) {
1959 ret = populate_nbd_status(nbd, reply);
1960 if (ret) {
1961 nlmsg_free(reply);
1962 goto out;
1963 }
1964 }
1965 }
1966 nla_nest_end(reply, dev_list);
1967 genlmsg_end(reply, reply_head);
1968 genlmsg_reply(reply, info);
1969 ret = 0;
1970 out:
1971 mutex_unlock(&nbd_index_mutex);
1972 return ret;
1973 }
1974
1975 static void nbd_connect_reply(struct genl_info *info, int index)
1976 {
1977 struct sk_buff *skb;
1978 void *msg_head;
1979 int ret;
1980
1981 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
1982 if (!skb)
1983 return;
1984 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
1985 NBD_CMD_CONNECT);
1986 if (!msg_head) {
1987 nlmsg_free(skb);
1988 return;
1989 }
1990 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
1991 if (ret) {
1992 nlmsg_free(skb);
1993 return;
1994 }
1995 genlmsg_end(skb, msg_head);
1996 genlmsg_reply(skb, info);
1997 }
1998
1999 static void nbd_mcast_index(int index)
2000 {
2001 struct sk_buff *skb;
2002 void *msg_head;
2003 int ret;
2004
2005 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2006 if (!skb)
2007 return;
2008 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2009 NBD_CMD_LINK_DEAD);
2010 if (!msg_head) {
2011 nlmsg_free(skb);
2012 return;
2013 }
2014 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2015 if (ret) {
2016 nlmsg_free(skb);
2017 return;
2018 }
2019 genlmsg_end(skb, msg_head);
2020 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2021 }
2022
2023 static void nbd_dead_link_work(struct work_struct *work)
2024 {
2025 struct link_dead_args *args = container_of(work, struct link_dead_args,
2026 work);
2027 nbd_mcast_index(args->index);
2028 kfree(args);
2029 }
2030
2031 static int __init nbd_init(void)
2032 {
2033 int i;
2034
2035 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2036
2037 if (max_part < 0) {
2038 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2039 return -EINVAL;
2040 }
2041
2042 part_shift = 0;
2043 if (max_part > 0) {
2044 part_shift = fls(max_part);
2045
2046 /*
2047 * Adjust max_part according to part_shift as it is exported
2048 * to user space so that user can know the max number of
2049 * partition kernel should be able to manage.
2050 *
2051 * Note that -1 is required because partition 0 is reserved
2052 * for the whole disk.
2053 */
2054 max_part = (1UL << part_shift) - 1;
2055 }
2056
2057 if ((1UL << part_shift) > DISK_MAX_PARTS)
2058 return -EINVAL;
2059
2060 if (nbds_max > 1UL << (MINORBITS - part_shift))
2061 return -EINVAL;
2062 recv_workqueue = alloc_workqueue("knbd-recv",
2063 WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
2064 if (!recv_workqueue)
2065 return -ENOMEM;
2066
2067 if (register_blkdev(NBD_MAJOR, "nbd")) {
2068 destroy_workqueue(recv_workqueue);
2069 return -EIO;
2070 }
2071
2072 if (genl_register_family(&nbd_genl_family)) {
2073 unregister_blkdev(NBD_MAJOR, "nbd");
2074 destroy_workqueue(recv_workqueue);
2075 return -EINVAL;
2076 }
2077 nbd_dbg_init();
2078
2079 mutex_lock(&nbd_index_mutex);
2080 for (i = 0; i < nbds_max; i++)
2081 nbd_dev_add(i);
2082 mutex_unlock(&nbd_index_mutex);
2083 return 0;
2084 }
2085
2086 static int nbd_exit_cb(int id, void *ptr, void *data)
2087 {
2088 struct list_head *list = (struct list_head *)data;
2089 struct nbd_device *nbd = ptr;
2090
2091 refcount_inc(&nbd->refs);
2092 list_add_tail(&nbd->list, list);
2093 return 0;
2094 }
2095
2096 static void __exit nbd_cleanup(void)
2097 {
2098 struct nbd_device *nbd;
2099 LIST_HEAD(del_list);
2100
2101 nbd_dbg_close();
2102
2103 mutex_lock(&nbd_index_mutex);
2104 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2105 mutex_unlock(&nbd_index_mutex);
2106
2107 list_for_each_entry(nbd, &del_list, list) {
2108 if (refcount_read(&nbd->refs) != 2)
2109 printk(KERN_ERR "nbd: possibly leaking a device\n");
2110 nbd_put(nbd);
2111 nbd_put(nbd);
2112 }
2113
2114 idr_destroy(&nbd_index_idr);
2115 genl_unregister_family(&nbd_genl_family);
2116 destroy_workqueue(recv_workqueue);
2117 unregister_blkdev(NBD_MAJOR, "nbd");
2118 }
2119
2120 module_init(nbd_init);
2121 module_exit(nbd_cleanup);
2122
2123 MODULE_DESCRIPTION("Network Block Device");
2124 MODULE_LICENSE("GPL");
2125
2126 module_param(nbds_max, int, 0444);
2127 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2128 module_param(max_part, int, 0444);
2129 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 0)");