kpartx: Add option '-f' to force devmap creation
[multipath-tools/.git] / kpartx / kpartx.c
1 /*
2  * Source: copy of util-linux' partx partx.c
3  *
4  * Copyrights of the original file applies
5  * Copyright (c) 2004, 2005 Christophe Varoqui
6  * Copyright (c) 2005 Kiyoshi Ueda
7  * Copyright (c) 2005 Lars Soltau
8  */
9
10 /*
11  * Given a block device and a partition table type,
12  * try to parse the partition table, and list the
13  * contents. Optionally add or remove partitions.
14  *
15  * Read wholedisk and add all partitions:
16  *      kpartx [-a|-d|-l] [-v] wholedisk
17  *
18  * aeb, 2000-03-21
19  * cva, 2002-10-26
20  */
21
22 #include <stdio.h>
23 #include <fcntl.h>
24 #include <errno.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <stdint.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <ctype.h>
32 #include <libdevmapper.h>
33
34 #include "devmapper.h"
35 #include "crc32.h"
36 #include "lopart.h"
37 #include "kpartx.h"
38
39 #define SIZE(a) (sizeof(a)/sizeof((a)[0]))
40
41 #define READ_SIZE       1024
42 #define MAXTYPES        64
43 #define MAXSLICES       256
44 #define DM_TARGET       "linear"
45 #define LO_NAME_SIZE    64
46 #define PARTNAME_SIZE   128
47 #define DELIM_SIZE      8
48
49 struct slice slices[MAXSLICES];
50
51 enum action { LIST, ADD, DELETE, UPDATE };
52
53 struct pt {
54         char *type;
55         ptreader *fn;
56 } pts[MAXTYPES];
57
58 int ptct = 0;
59
60 static void
61 addpts(char *t, ptreader f)
62 {
63         if (ptct >= MAXTYPES) {
64                 fprintf(stderr, "addpts: too many types\n");
65                 exit(1);
66         }
67         pts[ptct].type = t;
68         pts[ptct].fn = f;
69         ptct++;
70 }
71
72 static void
73 initpts(void)
74 {
75         addpts("gpt", read_gpt_pt);
76         addpts("dos", read_dos_pt);
77         addpts("bsd", read_bsd_pt);
78         addpts("solaris", read_solaris_pt);
79         addpts("unixware", read_unixware_pt);
80         addpts("dasd", read_dasd_pt);
81         addpts("mac", read_mac_pt);
82         addpts("sun", read_sun_pt);
83 }
84
85 static char short_opts[] = "rladfgvp:t:su";
86
87 /* Used in gpt.c */
88 int force_gpt=0;
89
90 int force_devmap=0;
91
92 static int
93 usage(void) {
94         printf("usage : kpartx [-a|-d|-l] [-f] [-v] wholedisk\n");
95         printf("\t-a add partition devmappings\n");
96         printf("\t-r devmappings will be readonly\n");
97         printf("\t-d del partition devmappings\n");
98         printf("\t-u update partition devmappings\n");
99         printf("\t-l list partitions devmappings that would be added by -a\n");
100         printf("\t-p set device name-partition number delimiter\n");
101         printf("\t-g force GUID partition table (GPT)\n");
102         printf("\t-f force devmap create\n");
103         printf("\t-v verbose\n");
104         printf("\t-s sync mode. Don't return until the partitions are created\n");
105         return 1;
106 }
107
108 static void
109 set_delimiter (char * device, char * delimiter)
110 {
111         char * p = device;
112
113         while (*(p++) != 0x0)
114                 continue;
115
116         if (isdigit(*(p - 2)))
117                 *delimiter = 'p';
118 }
119
120 static void
121 strip_slash (char * device)
122 {
123         char * p = device;
124
125         while (*(p++) != 0x0) {
126
127                 if (*p == '/')
128                         *p = '!';
129         }
130 }
131
132 static int
133 find_devname_offset (char * device)
134 {
135         char *p, *q = NULL;
136
137         p = device;
138
139         while (*p++)
140                 if (*p == '/')
141                         q = p;
142
143         return (int)(q - device) + 1;
144 }
145
146 static char *
147 get_hotplug_device(void)
148 {
149         unsigned int major, minor, off, len;
150         const char *mapname;
151         char *devname = NULL;
152         char *device = NULL;
153         char *var = NULL;
154         struct stat buf;
155
156         var = getenv("ACTION");
157
158         if (!var || strcmp(var, "add"))
159                 return NULL;
160
161         /* Get dm mapname for hotpluged device. */
162         if (!(devname = getenv("DEVNAME")))
163                 return NULL;
164
165         if (stat(devname, &buf))
166                 return NULL;
167
168         major = (unsigned int)MAJOR(buf.st_rdev);
169         minor = (unsigned int)MINOR(buf.st_rdev);
170
171         if (!(mapname = dm_mapname(major, minor))) /* Not dm device. */
172                 return NULL;
173
174         off = find_devname_offset(devname);
175         len = strlen(mapname);
176
177         /* Dirname + mapname + \0 */
178         if (!(device = (char *)malloc(sizeof(char) * (off + len + 1))))
179                 return NULL;
180
181         /* Create new device name. */
182         snprintf(device, off + 1, "%s", devname);
183         snprintf(device + off, len + 1, "%s", mapname);
184
185         if (strlen(device) != (off + len))
186                 return NULL;
187
188         return device;
189 }
190
191 int
192 main(int argc, char **argv){
193         int i, j, m, n, op, off, arg, c, d, ro=0;
194         int fd = -1;
195         struct slice all;
196         struct pt *ptp;
197         enum action what = LIST;
198         char *type, *diskdevice, *device, *progname;
199         int verbose = 0;
200         char partname[PARTNAME_SIZE], params[PARTNAME_SIZE + 16];
201         char * loopdev = NULL;
202         char * delim = NULL;
203         char *uuid = NULL;
204         char *mapname = NULL;
205         int loopro = 0;
206         int hotplug = 0;
207         int loopcreated = 0;
208         int sync = 0;
209         struct stat buf;
210         uint32_t cookie = 0;
211
212         initpts();
213         init_crc32();
214
215         type = device = diskdevice = NULL;
216         memset(&all, 0, sizeof(all));
217         memset(&partname, 0, sizeof(partname));
218
219         /* Check whether hotplug mode. */
220         progname = strrchr(argv[0], '/');
221
222         if (!progname)
223                 progname = argv[0];
224         else
225                 progname++;
226
227         if (!strcmp(progname, "kpartx.dev")) { /* Hotplug mode */
228                 hotplug = 1;
229
230                 /* Setup for original kpartx variables */
231                 if (!(device = get_hotplug_device()))
232                         exit(1);
233
234                 diskdevice = device;
235                 what = ADD;
236         } else if (argc < 2) {
237                 usage();
238                 exit(1);
239         }
240
241         while ((arg = getopt(argc, argv, short_opts)) != EOF) switch(arg) {
242                 case 'r':
243                         ro=1;
244                 case 'f':
245                         force_devmap=1;
246                         break;
247                 case 'g':
248                         force_gpt=1;
249                         break;
250                 case 't':
251                         type = optarg;
252                         break;
253                 case 'v':
254                         verbose = 1;
255                         break;
256                 case 'p':
257                         delim = optarg;
258                         break;
259                 case 'l':
260                         what = LIST;
261                         break;
262                 case 'a':
263                         what = ADD;
264                         break;
265                 case 'd':
266                         what = DELETE;
267                         break;
268                 case 's':
269                         sync = 1;
270                 case 'u':
271                         what = UPDATE;
272                         break;
273                 default:
274                         usage();
275                         exit(1);
276         }
277
278 #ifdef LIBDM_API_COOKIE
279         if (!sync)
280                 dm_udev_set_sync_support(0);
281 #endif
282
283         if (dm_prereq(DM_TARGET, 0, 0, 0) && (what == ADD || what == DELETE || what == UPDATE)) {
284                 fprintf(stderr, "device mapper prerequisites not met\n");
285                 exit(1);
286         }
287
288         if (hotplug) {
289                 /* already got [disk]device */
290         } else if (optind == argc-2) {
291                 device = argv[optind];
292                 diskdevice = argv[optind+1];
293         } else if (optind == argc-1) {
294                 diskdevice = device = argv[optind];
295         } else {
296                 usage();
297                 exit(1);
298         }
299
300         if (stat(device, &buf)) {
301                 printf("failed to stat() %s\n", device);
302                 exit (1);
303         }
304
305         if (S_ISREG (buf.st_mode)) {
306                 /* already looped file ? */
307                 loopdev = find_loop_by_file(device);
308
309                 if (!loopdev && what == DELETE)
310                         exit (0);
311
312                 if (!loopdev) {
313                         loopdev = find_unused_loop_device();
314
315                         if (set_loop(loopdev, device, 0, &loopro)) {
316                                 fprintf(stderr, "can't set up loop\n");
317                                 exit (1);
318                         }
319                         loopcreated = 1;
320                 }
321                 device = loopdev;
322         }
323
324         if (delim == NULL) {
325                 delim = malloc(DELIM_SIZE);
326                 memset(delim, 0, DELIM_SIZE);
327                 set_delimiter(device, delim);
328         }
329
330         off = find_devname_offset(device);
331
332         if (!loopdev) {
333                 uuid = dm_mapuuid((unsigned int)MAJOR(buf.st_rdev),
334                                   (unsigned int)MINOR(buf.st_rdev));
335                 mapname = dm_mapname((unsigned int)MAJOR(buf.st_rdev),
336                                      (unsigned int)MINOR(buf.st_rdev));
337         }
338
339         if (!uuid)
340                 uuid = device + off;
341
342         if (!mapname)
343                 mapname = device + off;
344         else if (!force_devmap &&
345                  dm_no_partitions((unsigned int)MAJOR(buf.st_rdev),
346                                   (unsigned int)MINOR(buf.st_rdev))) {
347                 /* Feature 'no_partitions' is set, return */
348                 return 0;
349         }
350
351         fd = open(device, O_RDONLY);
352
353         if (fd == -1) {
354                 perror(device);
355                 exit(1);
356         }
357
358         /* add/remove partitions to the kernel devmapper tables */
359         int r = 0;
360         for (i = 0; i < ptct; i++) {
361                 ptp = &pts[i];
362
363                 if (type && strcmp(type, ptp->type))
364                         continue;
365
366                 /* here we get partitions */
367                 n = ptp->fn(fd, all, slices, SIZE(slices));
368
369 #ifdef DEBUG
370                 if (n >= 0)
371                         printf("%s: %d slices\n", ptp->type, n);
372 #endif
373
374                 if (n > 0) {
375                         close(fd);
376                         fd = -1;
377                 }
378                 else
379                         continue;
380
381                 switch(what) {
382                 case LIST:
383                         for (j = 0, c = 0, m = 0; j < n; j++) {
384                                 if (slices[j].size == 0)
385                                         continue;
386                                 if (slices[j].container > 0) {
387                                         c++;
388                                         continue;
389                                 }
390
391                                 slices[j].minor = m++;
392
393                                 printf("%s%s%d : 0 %" PRIu64 " %s %" PRIu64"\n",
394                                        mapname, delim, j+1,
395                                        slices[j].size, device,
396                                        slices[j].start);
397                         }
398                         /* Loop to resolve contained slices */
399                         d = c;
400                         while (c) {
401                                 for (j = 0; j < n; j++) {
402                                         uint64_t start;
403                                         int k = slices[j].container - 1;
404
405                                         if (slices[j].size == 0)
406                                                 continue;
407                                         if (slices[j].minor > 0)
408                                                 continue;
409                                         if (slices[j].container == 0)
410                                                 continue;
411                                         slices[j].minor = m++;
412
413                                         start = slices[j].start - slices[k].start;
414                                         printf("%s%s%d : 0 %" PRIu64 " /dev/dm-%d %" PRIu64 "\n",
415                                                mapname, delim, j+1,
416                                                slices[j].size,
417                                                slices[k].minor, start);
418                                         c--;
419                                 }
420                                 /* Terminate loop if nothing more to resolve */
421                                 if (d == c)
422                                         break;
423                         }
424
425                         break;
426
427                 case DELETE:
428                         for (j = n-1; j >= 0; j--) {
429                                 if (safe_sprintf(partname, "%s%s%d",
430                                              mapname, delim, j+1)) {
431                                         fprintf(stderr, "partname too small\n");
432                                         exit(1);
433                                 }
434                                 strip_slash(partname);
435
436                                 if (!slices[j].size || !dm_map_present(partname))
437                                         continue;
438
439                                 if (!dm_simplecmd(DM_DEVICE_REMOVE, partname,
440                                                   0, &cookie)) {
441                                         r++;
442                                         continue;
443                                 }
444                                 if (verbose)
445                                         printf("del devmap : %s\n", partname);
446                         }
447
448                         if (S_ISREG (buf.st_mode)) {
449                                 if (del_loop(device)) {
450                                         if (verbose)
451                                                 printf("can't del loop : %s\n",
452                                                         device);
453                                         exit(1);
454                                 }
455                                 printf("loop deleted : %s\n", device);
456                         }
457                         break;
458
459                 case ADD:
460                 case UPDATE:
461                         /* ADD and UPDATE share the same code that adds new partitions. */
462                         for (j = 0, c = 0; j < n; j++) {
463                                 if (slices[j].size == 0)
464                                         continue;
465
466                                 /* Skip all contained slices */
467                                 if (slices[j].container > 0) {
468                                         c++;
469                                         continue;
470                                 }
471
472                                 if (safe_sprintf(partname, "%s%s%d",
473                                              mapname, delim, j+1)) {
474                                         fprintf(stderr, "partname too small\n");
475                                         exit(1);
476                                 }
477                                 strip_slash(partname);
478
479                                 if (safe_sprintf(params, "%s %" PRIu64 ,
480                                                  device, slices[j].start)) {
481                                         fprintf(stderr, "params too small\n");
482                                         exit(1);
483                                 }
484
485                                 op = (dm_map_present(partname) ?
486                                         DM_DEVICE_RELOAD : DM_DEVICE_CREATE);
487
488                                 if (!dm_addmap(op, partname, DM_TARGET, params,
489                                                slices[j].size, ro, uuid, j+1,
490                                                buf.st_mode & 0777, buf.st_uid,
491                                                buf.st_gid, &cookie)) {
492                                         fprintf(stderr, "create/reload failed on %s\n",
493                                                 partname);
494                                         r++;
495                                 }
496                                 if (op == DM_DEVICE_RELOAD &&
497                                     !dm_simplecmd(DM_DEVICE_RESUME, partname,
498                                                   1, &cookie)) {
499                                         fprintf(stderr, "resume failed on %s\n",
500                                                 partname);
501                                         r++;
502                                 }
503                                 dm_devn(partname, &slices[j].major,
504                                         &slices[j].minor);
505
506                                 if (verbose)
507                                         printf("add map %s (%d:%d): 0 %" PRIu64 " %s %s\n",
508                                                partname, slices[j].major,
509                                                slices[j].minor, slices[j].size,
510                                                DM_TARGET, params);
511                         }
512                         /* Loop to resolve contained slices */
513                         d = c;
514                         while (c) {
515                                 for (j = 0; j < n; j++) {
516                                         uint64_t start;
517                                         int k = slices[j].container - 1;
518
519                                         if (slices[j].size == 0)
520                                                 continue;
521
522                                         /* Skip all existing slices */
523                                         if (slices[j].minor > 0)
524                                                 continue;
525
526                                         /* Skip all simple slices */
527                                         if (slices[j].container == 0)
528                                                 continue;
529
530                                         /* Check container slice */
531                                         if (slices[k].size == 0)
532                                                 fprintf(stderr, "Invalid slice %d\n",
533                                                         k);
534
535                                         if (safe_sprintf(partname, "%s%s%d",
536                                                          mapname, delim, j+1)) {
537                                                 fprintf(stderr, "partname too small\n");
538                                                 exit(1);
539                                         }
540                                         strip_slash(partname);
541
542                                         start = slices[j].start - slices[k].start;
543                                         if (safe_sprintf(params, "%d:%d %" PRIu64,
544                                                          slices[k].major,
545                                                          slices[k].minor,
546                                                          start)) {
547                                                 fprintf(stderr, "params too small\n");
548                                                 exit(1);
549                                         }
550
551                                         op = (dm_map_present(partname) ?
552                                               DM_DEVICE_RELOAD : DM_DEVICE_CREATE);
553
554                                         dm_addmap(op, partname, DM_TARGET, params,
555                                                   slices[j].size, ro, uuid, j+1,
556                                                   buf.st_mode & 0777,
557                                                   buf.st_uid, buf.st_gid,
558                                                   &cookie);
559
560                                         if (op == DM_DEVICE_RELOAD)
561                                                 dm_simplecmd(DM_DEVICE_RESUME,
562                                                              partname, 1,
563                                                              &cookie);
564
565                                         dm_devn(partname, &slices[j].major,
566                                                 &slices[j].minor);
567
568                                         if (verbose)
569                                                 printf("add map %s : 0 %" PRIu64 " %s %s\n",
570                                                        partname, slices[j].size,
571                                                        DM_TARGET, params);
572                                         c--;
573                                 }
574                                 /* Terminate loop */
575                                 if (d == c)
576                                         break;
577                         }
578
579                         if (what == ADD) {
580                                 /* Skip code that removes devmappings for deleted partitions */
581                                 break;
582                         }
583
584                         for (j = MAXSLICES-1; j >= 0; j--) {
585                                 if (safe_sprintf(partname, "%s%s%d",
586                                              mapname, delim, j+1)) {
587                                         fprintf(stderr, "partname too small\n");
588                                         exit(1);
589                                 }
590                                 strip_slash(partname);
591
592                                 if (slices[j].size || !dm_map_present(partname))
593                                         continue;
594
595                                 if (!dm_simplecmd(DM_DEVICE_REMOVE,
596                                                   partname, 1, &cookie)) {
597                                         r++;
598                                         continue;
599                                 }
600                                 if (verbose)
601                                         printf("del devmap : %s\n", partname);
602                         }
603
604                 default:
605                         break;
606
607                 }
608                 if (n > 0)
609                         break;
610         }
611         if (what == LIST && loopcreated && S_ISREG (buf.st_mode)) {
612                 if (fd != -1)
613                         close(fd);
614                 if (del_loop(device)) {
615                         if (verbose)
616                                 printf("can't del loop : %s\n",
617                                         device);
618                         exit(1);
619                 }
620                 printf("loop deleted : %s\n", device);
621         }
622 #ifdef LIBDM_API_COOKIE
623         dm_udev_wait(cookie);
624 #endif
625         dm_lib_release();
626         dm_lib_exit();
627
628         return r;
629 }
630
631 void *
632 xmalloc (size_t size) {
633         void *t;
634
635         if (size == 0)
636                 return NULL;
637
638         t = malloc (size);
639
640         if (t == NULL) {
641                 fprintf(stderr, "Out of memory\n");
642                 exit(1);
643         }
644
645         return t;
646 }
647
648 /*
649  * sseek: seek to specified sector
650  */
651
652 static int
653 sseek(int fd, unsigned int secnr) {
654         off64_t in, out;
655         in = ((off64_t) secnr << 9);
656         out = 1;
657
658         if ((out = lseek64(fd, in, SEEK_SET)) != in)
659         {
660                 fprintf(stderr, "llseek error\n");
661                 return -1;
662         }
663         return 0;
664 }
665
666 static
667 struct block {
668         unsigned int secnr;
669         char *block;
670         struct block *next;
671 } *blockhead;
672
673 char *
674 getblock (int fd, unsigned int secnr) {
675         struct block *bp;
676
677         for (bp = blockhead; bp; bp = bp->next)
678
679                 if (bp->secnr == secnr)
680                         return bp->block;
681
682         if (sseek(fd, secnr))
683                 return NULL;
684
685         bp = xmalloc(sizeof(struct block));
686         bp->secnr = secnr;
687         bp->next = blockhead;
688         blockhead = bp;
689         bp->block = (char *) xmalloc(READ_SIZE);
690
691         if (read(fd, bp->block, READ_SIZE) != READ_SIZE) {
692                 fprintf(stderr, "read error, sector %d\n", secnr);
693                 bp->block = NULL;
694         }
695
696         return bp->block;
697 }