diff mbox

[v4,3/3] Add -f option to qemu-nbd

Message ID 1322839676-7559-3-git-send-email-cyliu@suse.com
State New
Headers show

Commit Message

Chunyan Liu Dec. 2, 2011, 3:27 p.m. UTC
Add -f option to qemu-nbd so that it can find a free nbd device and connect
disk.img to that device.

Changes to v3:
a. According to Stefan's suggestion, loop over /dev/nbd%d to do "qemu-nbd -f
disk.img", if fails, try next device.
b. syntax "qemu-nbd -f disk.img" only 

Signed-off-by: Chunyan Liu <cyliu@suse.com>
---
 qemu-nbd.c |   25 ++++++++++++++++++++++---
 1 files changed, 22 insertions(+), 3 deletions(-)
diff mbox

Patch

diff --git a/qemu-nbd.c b/qemu-nbd.c
index 83ae30f..431373d 100644
--- a/qemu-nbd.c
+++ b/qemu-nbd.c
@@ -400,7 +400,7 @@  static int nbd_setup(void)
 
 int main(int argc, char **argv)
 {
-    const char *sopt = "hVb:o:p:rsnP:c:dvk:e:t";
+    const char *sopt = "hVb:o:p:rsnP:c:dvk:e:tf";
     struct option lopt[] = {
         { "help", 0, NULL, 'h' },
         { "version", 0, NULL, 'V' },
@@ -417,12 +417,14 @@  int main(int argc, char **argv)
         { "shared", 1, NULL, 'e' },
         { "persistent", 0, NULL, 't' },
         { "verbose", 0, NULL, 'v' },
+        { "find", 0, NULL, 'f' },
         { NULL, 0, NULL, 0 }
     };
     int ch;
     int opt_ind = 0;
     char *end;
     int ret = 0;
+    int find = 0;
 
     /* The client thread uses SIGTERM to interrupt the server.  A signal
      * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
@@ -491,6 +493,9 @@  int main(int argc, char **argv)
         case 'c':
             device = optarg;
             break;
+        case 'f':
+            find = 1;
+            break;
         case 'e':
             shared = strtol(optarg, &end, 0);
             if (*end) {
@@ -541,7 +546,7 @@  int main(int argc, char **argv)
 	return 0;
     }
 
-    if (device && !verbose) {
+    if ((device || find) && !verbose) {
         int stderr_fd[2];
         pid_t pid;
 
@@ -596,7 +601,21 @@  int main(int argc, char **argv)
     atexit(bdrv_close_all);
     srcpath = argv[optind];
 
-    ret = nbd_setup();
+    if (!find) {
+        ret = nbd_setup();
+    } else {
+        int max_nbd = 16;
+        int i;
+        for (i = 0; i < max_nbd; i++) {
+            if (!asprintf(&device, "/dev/nbd%d", i))
+                continue;
+            ret = nbd_setup();
+            if (ret != EXIT_SUCCESS) {
+                free(device);
+                continue;
+            }
+        }
+    }
 
     exit(ret);
 }