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