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