2 * partx: tell the kernel about your disk's partitions
3 * [This is not an fdisk - adding and removing partitions
4 * is not a change of the disk, but just telling the kernel
5 * about presence and numbering of on-disk partitions.]
7 * aeb, 2000-03-21 -- sah is 42 now
9 * Copyright (C) 2010 Davidlohr Bueso <dave@gnu.org>
10 * Rewritten to use libblkid for util-linux
11 * based on ideas from Karel Zak <kzak@redhat.com>
26 #include "pathnames.h"
36 #include "closestream.h"
39 /* this is the default upper limit, could be modified by --nr */
40 #define SLICES_MAX 256
42 /* all the columns (-o option) */
56 #define ACT_ERROR "--{add,delete,show,list,raw,pairs}"
72 const char *name
; /* header */
73 double whint
; /* width hint (N < 1 is in percent of termwidth) */
74 int flags
; /* TT_FL_* */
78 /* columns descriptions */
79 struct colinfo infos
[] = {
80 [COL_PARTNO
] = { "NR", 0.25, TT_FL_RIGHT
, N_("partition number") },
81 [COL_START
] = { "START", 0.30, TT_FL_RIGHT
, N_("start of the partition in sectors") },
82 [COL_END
] = { "END", 0.30, TT_FL_RIGHT
, N_("end of the partition in sectors") },
83 [COL_SECTORS
] = { "SECTORS", 0.30, TT_FL_RIGHT
, N_("number of sectors") },
84 [COL_SIZE
] = { "SIZE", 0.30, TT_FL_RIGHT
, N_("human readable size") },
85 [COL_NAME
] = { "NAME", 0.30, TT_FL_TRUNC
, N_("partition name") },
86 [COL_UUID
] = { "UUID", 36, 0, N_("partition UUID")},
87 [COL_SCHEME
] = { "SCHEME", 0.1, TT_FL_TRUNC
, N_("partition table type (dos, gpt, ...)")},
88 [COL_FLAGS
] = { "FLAGS", 0.1, TT_FL_TRUNC
, N_("partition flags")},
89 [COL_TYPE
] = { "TYPE", 1, TT_FL_RIGHT
, N_("partition type hex or uuid")},
92 #define NCOLS ARRAY_SIZE(infos)
94 /* array with IDs of enabled columns */
95 static int columns
[NCOLS
], ncolumns
;
98 static int partx_flags
;
99 static struct loopdev_cxt lc
;
102 static void assoc_loopdev(const char *fname
)
106 if (loopcxt_init(&lc
, 0))
107 err(EXIT_FAILURE
, _("failed to initialize loopcxt"));
109 rc
= loopcxt_find_unused(&lc
);
111 err(EXIT_FAILURE
, _("%s: failed to find unused loop device"),
115 printf(_("Trying to use '%s' for the loop device\n"),
116 loopcxt_get_device(&lc
));
118 if (loopcxt_set_backing_file(&lc
, fname
))
119 err(EXIT_FAILURE
, _("%s: failed to set backing file"), fname
);
121 rc
= loopcxt_setup_device(&lc
);
124 err(EXIT_FAILURE
, _("%s: failed to setup loop device"), fname
);
129 static inline int get_column_id(int num
)
131 assert(ARRAY_SIZE(columns
) == NCOLS
);
132 assert(num
< ncolumns
);
133 assert(columns
[num
] < (int) NCOLS
);
137 static inline struct colinfo
*get_column_info(int num
)
139 return &infos
[ get_column_id(num
) ];
142 static int column_name_to_id(const char *name
, size_t namesz
)
148 for (i
= 0; i
< NCOLS
; i
++) {
149 const char *cn
= infos
[i
].name
;
151 if (!strncasecmp(name
, cn
, namesz
) && !*(cn
+ namesz
))
154 warnx(_("unknown column: %s"), name
);
159 * Given a partition return the corresponding partition number.
161 * Note that this function tries to use sysfs, otherwise it assumes that the
162 * last characters are always numeric (sda1, sdc20, etc).
164 static int get_partno_from_device(char *partition
, dev_t devno
)
168 char *p
, *end
= NULL
;
173 struct sysfs_cxt cxt
;
176 if (sysfs_init(&cxt
, devno
, NULL
))
179 rc
= sysfs_read_int(&cxt
, "partition", &partno
);
186 sz
= strlen(partition
);
187 p
= partition
+ sz
- 1;
189 if (!isdigit((unsigned int) *p
))
192 while (isdigit((unsigned int) *(p
- 1))) p
--;
195 partno
= strtol(p
, &end
, 10);
196 if (errno
|| !end
|| *end
|| p
== end
)
201 errx(EXIT_FAILURE
, _("%s: failed to get partition number"), partition
);
204 static int get_max_partno(const char *disk
, dev_t devno
)
206 char path
[PATH_MAX
], *parent
, *dirname
= NULL
;
212 if (!devno
&& !stat(disk
, &st
))
216 parent
= strrchr(disk
, '/');
221 snprintf(path
, sizeof(path
), _PATH_SYS_DEVBLOCK
"/%d:%d/",
222 major(devno
), minor(devno
));
228 dirname
= xstrdup(path
);
230 while ((d
= readdir(dir
))) {
233 if (!strcmp(d
->d_name
, ".") ||
234 !strcmp(d
->d_name
, ".."))
236 #ifdef _DIRENT_HAVE_D_TYPE
237 if (d
->d_type
!= DT_DIR
)
240 if (strncmp(parent
, d
->d_name
, strlen(parent
)))
242 snprintf(path
, sizeof(path
), "%s/partition", d
->d_name
);
244 fd
= open_at(dirfd(dir
), dirname
, path
, O_RDONLY
);
247 FILE *f
= fdopen(fd
, "r");
249 if (fscanf(f
, "%d", &x
) == 1 && x
> partno
)
263 static void del_parts_warnx(const char *device
, int first
, int last
)
266 warnx(_("%s: error deleting partition %d"), device
, first
);
268 warnx(_("%s: error deleting partitions %d-%d"),
269 device
, first
, last
);
272 static int del_parts(int fd
, const char *device
, dev_t devno
,
273 int lower
, int upper
)
275 int rc
= 0, i
, errfirst
= 0, errlast
= 0;
282 if (!upper
|| lower
< 0 || upper
< 0) {
283 int n
= get_max_partno(device
, devno
);
287 upper
= n
+ upper
+ 1;
289 lower
= n
+ lower
+ 1;
292 warnx(_("specified range <%d:%d> "
293 "does not make sense"), lower
, upper
);
297 for (i
= lower
; i
<= upper
; i
++) {
298 rc
= partx_del_partition(fd
, i
);
301 printf(_("%s: partition #%d removed\n"), device
, i
);
303 } else if (errno
== ENXIO
) {
305 printf(_("%s: partition #%d already doesn't exist\n"), device
, i
);
310 warn(_("%s: deleting partition #%d failed"), device
, i
);
312 errlast
= errfirst
= i
;
313 else if (errlast
+ 1 == i
)
316 del_parts_warnx(device
, errfirst
, errlast
);
317 errlast
= errfirst
= i
;
322 del_parts_warnx(device
, errfirst
, errlast
);
327 static void add_parts_warnx(const char *device
, int first
, int last
)
330 warnx(_("%s: error adding partition %d"), device
, first
);
332 warnx(_("%s: error adding partitions %d-%d"),
333 device
, first
, last
);
336 static int add_parts(int fd
, const char *device
,
337 blkid_partlist ls
, int lower
, int upper
)
339 int i
, nparts
, rc
= 0, errfirst
= 0, errlast
= 0;
345 nparts
= blkid_partlist_numof_partitions(ls
);
347 for (i
= 0; i
< nparts
; i
++) {
348 blkid_partition par
= blkid_partlist_get_partition(ls
, i
);
349 int n
= blkid_partition_get_partno(par
);
350 uintmax_t start
, size
;
352 if (lower
&& n
< lower
)
354 if (upper
&& n
> upper
)
357 start
= blkid_partition_get_start(par
);
358 size
= blkid_partition_get_size(par
);
360 if (blkid_partition_is_extended(par
))
362 * Let's follow the Linux kernel and reduce
363 * DOS extended partition to 1 or 2 sectors.
365 size
= min(size
, (uintmax_t) 2);
367 if (partx_add_partition(fd
, n
, start
, size
) == 0) {
369 printf(_("%s: partition #%d added\n"), device
, n
);
374 warn(_("%s: adding partition #%d failed"), device
, n
);
376 errlast
= errfirst
= n
;
377 else if (errlast
+ 1 == n
)
380 add_parts_warnx(device
, errfirst
, errlast
);
381 errlast
= errfirst
= n
;
386 add_parts_warnx(device
, errfirst
, errlast
);
389 * The kernel with enabled partitions scanner for loop devices add *all*
390 * partitions, so we should delete any extra, unwanted ones, when the -n
393 if (loopdev
&& loopcxt_is_partscan(&lc
) && (lower
|| upper
)) {
394 for (i
= 0; i
< nparts
; i
++) {
395 blkid_partition par
= blkid_partlist_get_partition(ls
, i
);
396 int n
= blkid_partition_get_partno(par
);
398 if (n
< lower
|| n
> upper
)
399 partx_del_partition(fd
, n
);
406 static void upd_parts_warnx(const char *device
, int first
, int last
)
409 warnx(_("%s: error updating partition %d"), device
, first
);
411 warnx(_("%s: error updating partitions %d-%d"),
412 device
, first
, last
);
415 static int upd_parts(int fd
, const char *device
, dev_t devno
,
416 blkid_partlist ls
, int lower
, int upper
)
418 int i
, n
, an
, nparts
, rc
= 0, errfirst
= 0, errlast
= 0, err
;
420 uintmax_t start
, size
;
426 nparts
= blkid_partlist_numof_partitions(ls
);
429 if (!upper
|| lower
< 0 || upper
< 0) {
430 n
= get_max_partno(device
, devno
);
432 upper
= n
> nparts
? n
: nparts
;
434 upper
= n
+ upper
+ 1;
436 lower
= n
+ lower
+ 1;
439 warnx(_("specified range <%d:%d> "
440 "does not make sense"), lower
, upper
);
444 for (i
= 0, n
= lower
; n
<= upper
; n
++) {
445 par
= blkid_partlist_get_partition(ls
, i
);
446 an
= blkid_partition_get_partno(par
);
448 if (lower
&& n
< lower
)
450 if (upper
&& n
> upper
)
453 start
= blkid_partition_get_start(par
);
454 size
= blkid_partition_get_size(par
);
456 if (blkid_partition_is_extended(par
))
458 * Let's follow the Linux kernel and reduce
459 * DOS extended partition to 1 or 2 sectors.
461 size
= min(size
, (uintmax_t) 2);
463 err
= partx_del_partition(fd
, n
);
464 if (err
== -1 && errno
== ENXIO
)
465 err
= 0; /* good, it already doesn't exist */
470 if (err
== -1 && errno
== EBUSY
)
473 err
= partx_resize_partition(fd
, n
, start
, size
);
475 printf(_("%s: partition #%d resized\n"), device
, n
);
479 if (err
== 0 && partx_add_partition(fd
, n
, start
, size
) == 0) {
481 printf(_("%s: partition #%d added\n"), device
, n
);
489 warn(_("%s: updating partition #%d failed"), device
, n
);
491 errlast
= errfirst
= n
;
492 else if (errlast
+ 1 == n
)
495 upd_parts_warnx(device
, errfirst
, errlast
);
496 errlast
= errfirst
= n
;
501 upd_parts_warnx(device
, errfirst
, errlast
);
505 static int list_parts(blkid_partlist ls
, int lower
, int upper
)
511 nparts
= blkid_partlist_numof_partitions(ls
);
513 for (i
= 0; i
< nparts
; i
++) {
514 blkid_partition par
= blkid_partlist_get_partition(ls
, i
);
515 int n
= blkid_partition_get_partno(par
);
516 uintmax_t start
, size
;
518 if (lower
&& n
< lower
)
520 if (upper
&& n
> upper
)
523 start
= blkid_partition_get_start(par
);
524 size
= blkid_partition_get_size(par
);
526 printf(_("#%2d: %9ju-%9ju (%9ju sectors, %6ju MB)\n"),
527 n
, start
, start
+ size
-1,
528 size
, (size
<< 9) / 1000000);
533 static void add_tt_line(struct tt
*tt
, blkid_partition par
)
535 struct tt_line
*line
;
541 line
= tt_add_line(tt
, NULL
);
543 warn(_("failed to add line to output"));
547 for (i
= 0; i
< ncolumns
; i
++) {
550 switch (get_column_id(i
)) {
552 xasprintf(&str
, "%d", blkid_partition_get_partno(par
));
555 xasprintf(&str
, "%ju", blkid_partition_get_start(par
));
558 xasprintf(&str
, "%ju",
559 blkid_partition_get_start(par
) +
560 blkid_partition_get_size(par
) - 1);
563 xasprintf(&str
, "%ju", blkid_partition_get_size(par
));
566 if (partx_flags
& FL_BYTES
)
567 xasprintf(&str
, "%ju", (uintmax_t)
568 blkid_partition_get_size(par
) << 9);
570 str
= size_to_human_string(SIZE_SUFFIX_1LETTER
,
571 blkid_partition_get_size(par
) << 9);
574 str
= (char *) blkid_partition_get_name(par
);
579 str
= (char *) blkid_partition_get_uuid(par
);
584 str
= (char *) blkid_partition_get_type_string(par
);
588 xasprintf(&str
, "0x%x",
589 blkid_partition_get_type(par
));
592 xasprintf(&str
, "0x%llx", blkid_partition_get_flags(par
));
596 blkid_parttable tab
= blkid_partition_get_table(par
);
598 str
= (char *) blkid_parttable_get_type(tab
);
609 tt_line_set_data(line
, i
, str
);
613 static int show_parts(blkid_partlist ls
, int tt_flags
, int lower
, int upper
)
621 nparts
= blkid_partlist_numof_partitions(ls
);
625 tt
= tt_new_table(tt_flags
);
627 warn(_("failed to initialize output table"));
631 for (i
= 0; i
< ncolumns
; i
++) {
632 struct colinfo
*col
= get_column_info(i
);
634 if (!tt_define_column(tt
, col
->name
, col
->whint
, col
->flags
)) {
635 warnx(_("failed to initialize output column"));
640 for (i
= 0; i
< nparts
; i
++) {
641 blkid_partition par
= blkid_partlist_get_partition(ls
, i
);
642 int n
= blkid_partition_get_partno(par
);
644 if (lower
&& n
< lower
)
646 if (upper
&& n
> upper
)
649 add_tt_line(tt
, par
);
659 static blkid_partlist
get_partlist(blkid_probe pr
,
660 const char *device
, char *type
)
669 char *name
[] = { type
, NULL
};
671 if (blkid_probe_filter_partitions_type(pr
,
672 BLKID_FLTR_ONLYIN
, name
)) {
673 warnx(_("failed to initialize blkid "
674 "filter for '%s'"), type
);
679 ls
= blkid_probe_get_partitions(pr
);
681 warnx(_("%s: failed to read partition table"), device
);
685 tab
= blkid_partlist_get_table(ls
);
686 if (verbose
&& tab
) {
687 printf(_("%s: partition table type '%s' detected\n"),
688 device
, blkid_parttable_get_type(tab
));
690 if (!blkid_partlist_numof_partitions(ls
))
691 printf(_("%s: partition table with no partitions"), device
);
697 static void __attribute__((__noreturn__
)) usage(FILE *out
)
701 fputs(USAGE_HEADER
, out
);
703 _(" %s [-a|-d|-s|-u] [--nr <n:m> | <partition>] <disk>\n"),
704 program_invocation_short_name
);
706 fputs(USAGE_OPTIONS
, out
);
707 fputs(_(" -a, --add add specified partitions or all of them\n"), out
);
708 fputs(_(" -d, --delete delete specified partitions or all of them\n"), out
);
709 fputs(_(" -s, --show list partitions\n\n"), out
);
710 fputs(_(" -u, --update update specified partitions or all of them\n"), out
);
711 fputs(_(" -b, --bytes print SIZE in bytes rather than in human readable format\n"), out
);
712 fputs(_(" -g, --noheadings don't print headings for --show\n"), out
);
713 fputs(_(" -n, --nr <n:m> specify the range of partitions (e.g. --nr 2:4)\n"), out
);
714 fputs(_(" -o, --output <type> define which output columns to use\n"), out
);
715 fputs(_(" -P, --pairs use key=\"value\" output format\n"), out
);
716 fputs(_(" -r, --raw use raw output format\n"), out
);
717 fputs(_(" -t, --type <type> specify the partition type (dos, bsd, solaris, etc.)\n"), out
);
718 fputs(_(" -v, --verbose verbose mode\n"), out
);
720 fputs(USAGE_SEPARATOR
, out
);
721 fputs(USAGE_HELP
, out
);
722 fputs(USAGE_VERSION
, out
);
724 fputs(_("\nAvailable columns (for --show, --raw or --pairs):\n"), out
);
726 for (i
= 0; i
< NCOLS
; i
++)
727 fprintf(out
, " %10s %s\n", infos
[i
].name
, _(infos
[i
].help
));
729 fprintf(out
, USAGE_MAN_TAIL("partx(8)"));
731 exit(out
== stderr
? EXIT_FAILURE
: EXIT_SUCCESS
);
734 int main(int argc
, char **argv
)
736 int fd
, c
, what
= ACT_NONE
, lower
= 0, upper
= 0, rc
= 0;
739 char *device
= NULL
; /* pointer to argv[], ie: /dev/sda1 */
740 char *wholedisk
= NULL
; /* allocated, ie: /dev/sda */
742 dev_t disk_devno
= 0, part_devno
= 0;
744 static const struct option long_opts
[] = {
745 { "bytes", no_argument
, NULL
, 'b' },
746 { "noheadings", no_argument
, NULL
, 'g' },
747 { "raw", no_argument
, NULL
, 'r' },
748 { "list", no_argument
, NULL
, 'l' },
749 { "show", no_argument
, NULL
, 's' },
750 { "add", no_argument
, NULL
, 'a' },
751 { "delete", no_argument
, NULL
, 'd' },
752 { "update", no_argument
, NULL
, 'u' },
753 { "type", required_argument
, NULL
, 't' },
754 { "nr", required_argument
, NULL
, 'n' },
755 { "output", required_argument
, NULL
, 'o' },
756 { "pairs", no_argument
, NULL
, 'P' },
757 { "help", no_argument
, NULL
, 'h' },
758 { "version", no_argument
, NULL
, 'V' },
759 { "verbose", no_argument
, NULL
, 'v' },
763 static const ul_excl_t excl
[] = { /* rows and cols in in ASCII order */
764 { 'P','a','d','l','r','s' },
767 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
769 setlocale(LC_ALL
, "");
770 bindtextdomain(PACKAGE
, LOCALEDIR
);
772 atexit(close_stdout
);
774 while ((c
= getopt_long(argc
, argv
,
775 "abdglrsuvn:t:o:PhV", long_opts
, NULL
)) != -1) {
777 err_exclusive_options(c
, long_opts
, excl
, excl_st
);
784 partx_flags
|= FL_BYTES
;
790 tt_flags
|= TT_FL_NOHEADINGS
;
796 if (parse_range(optarg
, &lower
, &upper
, 0))
797 errx(EXIT_FAILURE
, _("failed to parse --nr <M-N> range"));
803 tt_flags
|= TT_FL_EXPORT
;
807 tt_flags
|= TT_FL_RAW
;
825 printf(UTIL_LINUX_VERSION
);
833 if (what
== ACT_NONE
)
836 /* --show default, could by modified by -o */
837 if (what
== ACT_SHOW
&& !ncolumns
) {
838 columns
[ncolumns
++] = COL_PARTNO
;
839 columns
[ncolumns
++] = COL_START
;
840 columns
[ncolumns
++] = COL_END
;
841 columns
[ncolumns
++] = COL_SECTORS
;
842 columns
[ncolumns
++] = COL_SIZE
;
843 columns
[ncolumns
++] = COL_NAME
;
844 columns
[ncolumns
++] = COL_UUID
;
847 if (what
== ACT_SHOW
&& outarg
&&
848 string_add_to_idarray(outarg
, columns
, ARRAY_SIZE(columns
),
849 &ncolumns
, column_name_to_id
) < 0)
853 * Note that 'partx /dev/sda1' == 'partx /dev/sda1 /dev/sda'
854 * so assume that the device and/or disk are always the last
855 * arguments to be passed to partx.
857 if (optind
== argc
- 2) {
858 /* passed 2 arguments:
859 * /dev/sda1 /dev/sda : partition + whole-disk
860 * -- /dev/sda1 : partition that should be used as a whole-disk
862 device
= argv
[optind
];
864 if (strcmp(device
, "-") == 0) {
866 wholedisk
= xstrdup(argv
[optind
+ 1]);
868 device
= argv
[optind
];
869 wholedisk
= xstrdup(argv
[optind
+ 1]);
871 } else if (optind
== argc
- 1) {
872 /* passed only one arg (ie: /dev/sda3 or /dev/sda) */
875 device
= argv
[optind
];
877 if (stat(device
, &sb
))
878 err(EXIT_FAILURE
, _("stat failed %s"), device
);
880 part_devno
= sb
.st_rdev
;
882 if (blkid_devno_to_wholedisk(part_devno
,
883 NULL
, 0, &disk_devno
) == 0 &&
884 part_devno
!= disk_devno
)
885 wholedisk
= blkid_devno_to_devname(disk_devno
);
888 wholedisk
= xstrdup(device
);
889 disk_devno
= part_devno
;
896 if (device
&& (upper
|| lower
))
897 errx(EXIT_FAILURE
, _("--nr and <partition> are mutually exclusive"));
902 /* use partno from given partition instead of --nr range, e.g:
905 * partx -d --nr 3 /dev/sda
909 if (!part_devno
&& !stat(device
, &sb
))
910 part_devno
= sb
.st_rdev
;
912 lower
= upper
= get_partno_from_device(device
, part_devno
);
916 printf(_("partition: %s, disk: %s, lower: %d, upper: %d\n"),
917 device
? device
: "none", wholedisk
, lower
, upper
);
919 if (what
== ACT_ADD
|| what
== ACT_DELETE
) {
922 if (stat(wholedisk
, &x
))
923 errx(EXIT_FAILURE
, "%s", wholedisk
);
925 if (S_ISREG(x
.st_mode
)) {
926 /* not a blkdev, try to associate it to a loop device */
927 if (what
== ACT_DELETE
)
928 errx(EXIT_FAILURE
, _("%s: cannot delete partitions"),
930 if (!loopmod_supports_partscan())
931 errx(EXIT_FAILURE
, _("%s: partitioned loop devices unsupported"),
933 assoc_loopdev(wholedisk
);
934 wholedisk
= xstrdup(lc
.device
);
935 } else if (!S_ISBLK(x
.st_mode
))
936 errx(EXIT_FAILURE
, _("%s: not a block device"), wholedisk
);
938 if ((fd
= open(wholedisk
, O_RDONLY
)) == -1)
939 err(EXIT_FAILURE
, _("cannot open %s"), wholedisk
);
941 if (what
== ACT_DELETE
)
942 rc
= del_parts(fd
, wholedisk
, disk_devno
, lower
, upper
);
944 blkid_probe pr
= blkid_new_probe();
945 blkid_partlist ls
= NULL
;
947 if (!pr
|| blkid_probe_set_device(pr
, fd
, 0, 0))
948 warnx(_("%s: failed to initialize blkid prober"),
951 ls
= get_partlist(pr
, wholedisk
, type
);
954 int n
= blkid_partlist_numof_partitions(ls
);
957 lower
= n
+ lower
+ 1;
959 upper
= n
+ upper
+ 1;
961 warnx(_("specified range <%d:%d> "
962 "does not make sense"), lower
, upper
);
963 rc
= -1, what
= ACT_NONE
;
968 rc
= show_parts(ls
, tt_flags
, lower
, upper
);
971 rc
= list_parts(ls
, lower
, upper
);
974 rc
= add_parts(fd
, wholedisk
, ls
, lower
, upper
);
977 rc
= upd_parts(fd
, wholedisk
, disk_devno
, ls
, lower
, upper
);
984 blkid_free_probe(pr
);
991 return rc
? EXIT_FAILURE
: EXIT_SUCCESS
;