525c34893e8d4020b6f9c87bdcae7276607cdf88
[multipath-tools/.git] / devmap_name / devmap_name.c
1 /*
2  * Copyright (c) 2004, 2005 Christophe Varoqui
3  */
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <ctype.h>
8 #include <unistd.h>
9 #include <linux/kdev_t.h>
10 #include <libdevmapper.h>
11
12 static void usage(char * progname) {
13         fprintf(stderr, "usage : %s [-t target type] dev_t\n", progname);
14         fprintf(stderr, "where dev_t is either 'major minor' or 'major:minor'\n");
15         exit(1);
16 }
17
18 int dm_target_type(int major, int minor, char *type)
19 {
20         struct dm_task *dmt;
21         void *next = NULL;
22         uint64_t start, length;
23         char *target_type = NULL;
24         char *params;
25         int r = 1;
26
27         if (!(dmt = dm_task_create(DM_DEVICE_STATUS)))
28                 return 1;
29
30         if (!dm_task_set_major(dmt, major) ||
31             !dm_task_set_minor(dmt, minor))
32                 goto bad;
33
34         dm_task_no_open_count(dmt);
35
36         if (!dm_task_run(dmt))
37                 goto bad;
38
39         if (!type)
40                 goto good;
41
42         do {
43                 next = dm_get_next_target(dmt, next, &start, &length,
44                                           &target_type, &params);
45                 if (target_type && strcmp(target_type, type))
46                         goto bad;
47         } while (next);
48
49 good:
50         printf("%s\n", dm_task_get_name(dmt));
51         r = 0;
52 bad:
53         dm_task_destroy(dmt);
54         return r;
55 }
56
57 int main(int argc, char **argv)
58 {
59         int c;
60         int major, minor;
61         char *target_type = NULL;
62
63         while ((c = getopt(argc, argv, "t:")) != -1) {
64                 switch (c) {
65                 case 't':
66                         target_type = optarg;
67                         break;
68                 default:
69                         usage(argv[0]);
70                         return 1;
71                         break;
72                 }
73         }
74
75         /* sanity check */
76         if (optind == argc - 2) {
77                 major = atoi(argv[argc - 2]);
78                 minor = atoi(argv[argc - 1]);
79         } else if (optind != argc - 1 ||
80                    2 != sscanf(argv[argc - 1], "%i:%i", &major, &minor))
81                 usage(argv[0]);
82
83         if (dm_target_type(major, minor, target_type))
84                 return 1;
85                                                                                 
86         return 0;
87 }
88