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}"
71 const char *name
; /* header */
72 double whint
; /* width hint (N < 1 is in percent of termwidth) */
73 int flags
; /* TT_FL_* */
77 /* columns descriptions */
78 struct colinfo infos
[] = {
79 [COL_PARTNO
] = { "NR", 0.25, TT_FL_RIGHT
, N_("partition number") },
80 [COL_START
] = { "START", 0.30, TT_FL_RIGHT
, N_("start of the partition in sectors") },
81 [COL_END
] = { "END", 0.30, TT_FL_RIGHT
, N_("end of the partition in sectors") },
82 [COL_SECTORS
] = { "SECTORS", 0.30, TT_FL_RIGHT
, N_("number of sectors") },
83 [COL_SIZE
] = { "SIZE", 0.30, TT_FL_RIGHT
, N_("human readable size") },
84 [COL_NAME
] = { "NAME", 0.30, TT_FL_TRUNC
, N_("partition name") },
85 [COL_UUID
] = { "UUID", 36, 0, N_("partition UUID")},
86 [COL_SCHEME
] = { "SCHEME", 0.1, TT_FL_TRUNC
, N_("partition table type (dos, gpt, ...)")},
87 [COL_FLAGS
] = { "FLAGS", 0.1, TT_FL_TRUNC
, N_("partition flags")},
88 [COL_TYPE
] = { "TYPE", 1, TT_FL_RIGHT
, N_("partition type hex or uuid")},
91 #define NCOLS ARRAY_SIZE(infos)
93 /* array with IDs of enabled columns */
94 static int columns
[NCOLS
], ncolumns
;
97 static int partx_flags
;
98 static struct loopdev_cxt lc
;
101 static void assoc_loopdev(const char *fname
)
105 if (loopcxt_init(&lc
, 0))
106 err(EXIT_FAILURE
, _("failed to initialize loopcxt"));
108 rc
= loopcxt_find_unused(&lc
);
110 err(EXIT_FAILURE
, _("%s: failed to find unused loop device"),
114 printf(_("Trying to use '%s' for the loop device\n"),
115 loopcxt_get_device(&lc
));
117 if (loopcxt_set_backing_file(&lc
, fname
))
118 err(EXIT_FAILURE
, _("%s: failed to set backing file"), fname
);
120 rc
= loopcxt_setup_device(&lc
);
123 err(EXIT_FAILURE
, _("%s: failed to setup loop device"), fname
);
128 static inline int get_column_id(int num
)
130 assert(ARRAY_SIZE(columns
) == NCOLS
);
131 assert(num
< ncolumns
);
132 assert(columns
[num
] < (int) NCOLS
);
136 static inline struct colinfo
*get_column_info(int num
)
138 return &infos
[ get_column_id(num
) ];
141 static int column_name_to_id(const char *name
, size_t namesz
)
147 for (i
= 0; i
< NCOLS
; i
++) {
148 const char *cn
= infos
[i
].name
;
150 if (!strncasecmp(name
, cn
, namesz
) && !*(cn
+ namesz
))
153 warnx(_("unknown column: %s"), name
);
158 * Given a partition return the corresponding partition number.
160 * Note that this function tries to use sysfs, otherwise it assumes that the
161 * last characters are always numeric (sda1, sdc20, etc).
163 static int get_partno_from_device(char *partition
, dev_t devno
)
167 char *p
, *end
= NULL
;
172 struct sysfs_cxt cxt
;
175 if (sysfs_init(&cxt
, devno
, NULL
))
178 rc
= sysfs_read_int(&cxt
, "partition", &partno
);
185 sz
= strlen(partition
);
186 p
= partition
+ sz
- 1;
188 if (!isdigit((unsigned int) *p
))
191 while (isdigit((unsigned int) *(p
- 1))) p
--;
194 partno
= strtol(p
, &end
, 10);
195 if (errno
|| !end
|| *end
|| p
== end
)
200 errx(EXIT_FAILURE
, _("%s: failed to get partition number"), partition
);
203 static int get_max_partno(const char *disk
, dev_t devno
)
205 char path
[PATH_MAX
], *parent
, *dirname
= NULL
;
211 if (!devno
&& !stat(disk
, &st
))
215 parent
= strrchr(disk
, '/');
220 snprintf(path
, sizeof(path
), _PATH_SYS_DEVBLOCK
"/%d:%d/",
221 major(devno
), minor(devno
));
227 dirname
= xstrdup(path
);
229 while ((d
= readdir(dir
))) {
232 if (!strcmp(d
->d_name
, ".") ||
233 !strcmp(d
->d_name
, ".."))
235 #ifdef _DIRENT_HAVE_D_TYPE
236 if (d
->d_type
!= DT_DIR
)
239 if (strncmp(parent
, d
->d_name
, strlen(parent
)))
241 snprintf(path
, sizeof(path
), "%s/partition", d
->d_name
);
243 fd
= open_at(dirfd(dir
), dirname
, path
, O_RDONLY
);
246 FILE *f
= fdopen(fd
, "r");
248 if (fscanf(f
, "%d", &x
) == 1 && x
> partno
)
262 static void del_parts_warnx(const char *device
, int first
, int last
)
265 warnx(_("%s: error deleting partition %d"), device
, first
);
267 warnx(_("%s: error deleting partitions %d-%d"),
268 device
, first
, last
);
271 static int del_parts(int fd
, const char *device
, dev_t devno
,
272 int lower
, int upper
)
274 int rc
= 0, i
, errfirst
= 0, errlast
= 0;
281 if (!upper
|| lower
< 0 || upper
< 0) {
282 int n
= get_max_partno(device
, devno
);
286 upper
= n
+ upper
+ 1;
288 lower
= n
+ lower
+ 1;
291 warnx(_("specified range <%d:%d> "
292 "does not make sense"), lower
, upper
);
296 for (i
= lower
; i
<= upper
; i
++) {
297 rc
= partx_del_partition(fd
, i
);
300 printf(_("%s: partition #%d removed\n"), device
, i
);
302 } else if (errno
== ENXIO
) {
304 printf(_("%s: partition #%d already doesn't exist\n"), device
, i
);
309 warn(_("%s: deleting partition #%d failed"), device
, i
);
311 errlast
= errfirst
= i
;
312 else if (errlast
+ 1 == i
)
315 del_parts_warnx(device
, errfirst
, errlast
);
316 errlast
= errfirst
= i
;
321 del_parts_warnx(device
, errfirst
, errlast
);
326 static void add_parts_warnx(const char *device
, int first
, int last
)
329 warnx(_("%s: error adding partition %d"), device
, first
);
331 warnx(_("%s: error adding partitions %d-%d"),
332 device
, first
, last
);
335 static int add_parts(int fd
, const char *device
,
336 blkid_partlist ls
, int lower
, int upper
)
338 int i
, nparts
, rc
= 0, errfirst
= 0, errlast
= 0;
344 nparts
= blkid_partlist_numof_partitions(ls
);
346 for (i
= 0; i
< nparts
; i
++) {
347 blkid_partition par
= blkid_partlist_get_partition(ls
, i
);
348 int n
= blkid_partition_get_partno(par
);
349 uintmax_t start
, size
;
351 if (lower
&& n
< lower
)
353 if (upper
&& n
> upper
)
356 start
= blkid_partition_get_start(par
);
357 size
= blkid_partition_get_size(par
);
359 if (blkid_partition_is_extended(par
))
361 * Let's follow the Linux kernel and reduce
362 * DOS extended partition to 1 or 2 sectors.
364 size
= min(size
, (uintmax_t) 2);
366 if (partx_add_partition(fd
, n
, start
, size
) == 0) {
368 printf(_("%s: partition #%d added\n"), device
, n
);
373 warn(_("%s: adding partition #%d failed"), device
, n
);
375 errlast
= errfirst
= n
;
376 else if (errlast
+ 1 == n
)
379 add_parts_warnx(device
, errfirst
, errlast
);
380 errlast
= errfirst
= n
;
385 add_parts_warnx(device
, errfirst
, errlast
);
388 * The kernel with enabled partitions scanner for loop devices add *all*
389 * partitions, so we should delete any extra, unwanted ones, when the -n
392 if (loopdev
&& loopcxt_is_partscan(&lc
) && (lower
|| upper
)) {
393 for (i
= 0; i
< nparts
; i
++) {
394 blkid_partition par
= blkid_partlist_get_partition(ls
, i
);
395 int n
= blkid_partition_get_partno(par
);
397 if (n
< lower
|| n
> upper
)
398 partx_del_partition(fd
, n
);
405 static int list_parts(blkid_partlist ls
, int lower
, int upper
)
411 nparts
= blkid_partlist_numof_partitions(ls
);
413 for (i
= 0; i
< nparts
; i
++) {
414 blkid_partition par
= blkid_partlist_get_partition(ls
, i
);
415 int n
= blkid_partition_get_partno(par
);
416 uintmax_t start
, size
;
418 if (lower
&& n
< lower
)
420 if (upper
&& n
> upper
)
423 start
= blkid_partition_get_start(par
);
424 size
= blkid_partition_get_size(par
);
426 printf(_("#%2d: %9ju-%9ju (%9ju sectors, %6ju MB)\n"),
427 n
, start
, start
+ size
-1,
428 size
, (size
<< 9) / 1000000);
433 static void add_tt_line(struct tt
*tt
, blkid_partition par
)
435 struct tt_line
*line
;
441 line
= tt_add_line(tt
, NULL
);
443 warn(_("failed to add line to output"));
447 for (i
= 0; i
< ncolumns
; i
++) {
450 switch (get_column_id(i
)) {
452 xasprintf(&str
, "%d", blkid_partition_get_partno(par
));
455 xasprintf(&str
, "%ju", blkid_partition_get_start(par
));
458 xasprintf(&str
, "%ju",
459 blkid_partition_get_start(par
) +
460 blkid_partition_get_size(par
) - 1);
463 xasprintf(&str
, "%ju", blkid_partition_get_size(par
));
466 if (partx_flags
& FL_BYTES
)
467 xasprintf(&str
, "%ju", (uintmax_t)
468 blkid_partition_get_size(par
) << 9);
470 str
= size_to_human_string(SIZE_SUFFIX_1LETTER
,
471 blkid_partition_get_size(par
) << 9);
474 str
= (char *) blkid_partition_get_name(par
);
479 str
= (char *) blkid_partition_get_uuid(par
);
484 str
= (char *) blkid_partition_get_type_string(par
);
488 xasprintf(&str
, "0x%x",
489 blkid_partition_get_type(par
));
492 xasprintf(&str
, "0x%llx", blkid_partition_get_flags(par
));
496 blkid_parttable tab
= blkid_partition_get_table(par
);
498 str
= (char *) blkid_parttable_get_type(tab
);
509 tt_line_set_data(line
, i
, str
);
513 static int show_parts(blkid_partlist ls
, int tt_flags
, int lower
, int upper
)
521 nparts
= blkid_partlist_numof_partitions(ls
);
525 tt
= tt_new_table(tt_flags
);
527 warn(_("failed to initialize output table"));
531 for (i
= 0; i
< ncolumns
; i
++) {
532 struct colinfo
*col
= get_column_info(i
);
534 if (!tt_define_column(tt
, col
->name
, col
->whint
, col
->flags
)) {
535 warnx(_("failed to initialize output column"));
540 for (i
= 0; i
< nparts
; i
++) {
541 blkid_partition par
= blkid_partlist_get_partition(ls
, i
);
542 int n
= blkid_partition_get_partno(par
);
544 if (lower
&& n
< lower
)
546 if (upper
&& n
> upper
)
549 add_tt_line(tt
, par
);
559 static blkid_partlist
get_partlist(blkid_probe pr
,
560 const char *device
, char *type
)
569 char *name
[] = { type
, NULL
};
571 if (blkid_probe_filter_partitions_type(pr
,
572 BLKID_FLTR_ONLYIN
, name
)) {
573 warnx(_("failed to initialize blkid "
574 "filter for '%s'"), type
);
579 ls
= blkid_probe_get_partitions(pr
);
581 warnx(_("%s: failed to read partition table"), device
);
585 tab
= blkid_partlist_get_table(ls
);
586 if (verbose
&& tab
) {
587 printf(_("%s: partition table type '%s' detected\n"),
588 device
, blkid_parttable_get_type(tab
));
590 if (!blkid_partlist_numof_partitions(ls
))
591 printf(_("%s: partition table with no partitions"), device
);
597 static void __attribute__((__noreturn__
)) usage(FILE *out
)
601 fputs(USAGE_HEADER
, out
);
603 _(" %s [-a|-d|-s] [--nr <n:m> | <partition>] <disk>\n"),
604 program_invocation_short_name
);
606 fputs(USAGE_OPTIONS
, out
);
607 fputs(_(" -a, --add add specified partitions or all of them\n"
608 " -d, --delete delete specified partitions or all of them\n"
609 " -l, --list list partitions (DEPRECATED)\n"
610 " -s, --show list partitions\n\n"
612 " -b, --bytes print SIZE in bytes rather than in human readable format\n"
613 " -g, --noheadings don't print headings for --show\n"
614 " -n, --nr <n:m> specify the range of partitions (e.g. --nr 2:4)\n"
615 " -o, --output <type> define which output columns to use\n"
616 " -P, --pairs use key=\"value\" output format\n"
617 " -r, --raw use raw output format\n"
618 " -t, --type <type> specify the partition type (dos, bsd, solaris, etc.)\n"
619 " -v, --verbose verbose mode\n"), out
);
621 fputs(USAGE_SEPARATOR
, out
);
622 fputs(USAGE_HELP
, out
);
623 fputs(USAGE_VERSION
, out
);
625 fputs(_("\nAvailable columns (for --show, --raw or --pairs):\n"), out
);
627 for (i
= 0; i
< NCOLS
; i
++)
628 fprintf(out
, " %10s %s\n", infos
[i
].name
, _(infos
[i
].help
));
630 fprintf(out
, USAGE_MAN_TAIL("partx(8)"));
632 exit(out
== stderr
? EXIT_FAILURE
: EXIT_SUCCESS
);
635 int main(int argc
, char **argv
)
637 int fd
, c
, what
= ACT_NONE
, lower
= 0, upper
= 0, rc
= 0;
640 char *device
= NULL
; /* pointer to argv[], ie: /dev/sda1 */
641 char *wholedisk
= NULL
; /* allocated, ie: /dev/sda */
643 dev_t disk_devno
= 0, part_devno
= 0;
645 static const struct option long_opts
[] = {
646 { "bytes", no_argument
, NULL
, 'b' },
647 { "noheadings", no_argument
, NULL
, 'g' },
648 { "raw", no_argument
, NULL
, 'r' },
649 { "list", no_argument
, NULL
, 'l' },
650 { "show", no_argument
, NULL
, 's' },
651 { "add", no_argument
, NULL
, 'a' },
652 { "delete", no_argument
, NULL
, 'd' },
653 { "type", required_argument
, NULL
, 't' },
654 { "nr", required_argument
, NULL
, 'n' },
655 { "output", required_argument
, NULL
, 'o' },
656 { "pairs", no_argument
, NULL
, 'P' },
657 { "help", no_argument
, NULL
, 'h' },
658 { "version", no_argument
, NULL
, 'V' },
659 { "verbose", no_argument
, NULL
, 'v' },
663 static const ul_excl_t excl
[] = { /* rows and cols in in ASCII order */
664 { 'P','a','d','l','r','s' },
667 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
669 setlocale(LC_ALL
, "");
670 bindtextdomain(PACKAGE
, LOCALEDIR
);
672 atexit(close_stdout
);
674 while ((c
= getopt_long(argc
, argv
,
675 "abdglrsvn:t:o:PhV", long_opts
, NULL
)) != -1) {
677 err_exclusive_options(c
, long_opts
, excl
, excl_st
);
684 partx_flags
|= FL_BYTES
;
690 tt_flags
|= TT_FL_NOHEADINGS
;
696 if (parse_range(optarg
, &lower
, &upper
, 0))
697 errx(EXIT_FAILURE
, _("failed to parse --nr <M-N> range"));
703 tt_flags
|= TT_FL_EXPORT
;
707 tt_flags
|= TT_FL_RAW
;
722 printf(UTIL_LINUX_VERSION
);
730 if (what
== ACT_NONE
)
733 /* --show default, could by modified by -o */
734 if (what
== ACT_SHOW
&& !ncolumns
) {
735 columns
[ncolumns
++] = COL_PARTNO
;
736 columns
[ncolumns
++] = COL_START
;
737 columns
[ncolumns
++] = COL_END
;
738 columns
[ncolumns
++] = COL_SECTORS
;
739 columns
[ncolumns
++] = COL_SIZE
;
740 columns
[ncolumns
++] = COL_NAME
;
741 columns
[ncolumns
++] = COL_UUID
;
744 if (what
== ACT_SHOW
&& outarg
&&
745 string_add_to_idarray(outarg
, columns
, ARRAY_SIZE(columns
),
746 &ncolumns
, column_name_to_id
) < 0)
750 * Note that 'partx /dev/sda1' == 'partx /dev/sda1 /dev/sda'
751 * so assume that the device and/or disk are always the last
752 * arguments to be passed to partx.
754 if (optind
== argc
- 2) {
755 /* passed 2 arguments:
756 * /dev/sda1 /dev/sda : partition + whole-disk
757 * -- /dev/sda1 : partition that should be used as a whole-disk
759 device
= argv
[optind
];
761 if (strcmp(device
, "-") == 0) {
763 wholedisk
= xstrdup(argv
[optind
+ 1]);
765 device
= argv
[optind
];
766 wholedisk
= xstrdup(argv
[optind
+ 1]);
768 } else if (optind
== argc
- 1) {
769 /* passed only one arg (ie: /dev/sda3 or /dev/sda) */
772 device
= argv
[optind
];
774 if (stat(device
, &sb
))
775 err(EXIT_FAILURE
, _("stat failed %s"), device
);
777 part_devno
= sb
.st_rdev
;
779 if (blkid_devno_to_wholedisk(part_devno
,
780 NULL
, 0, &disk_devno
) == 0 &&
781 part_devno
!= disk_devno
)
782 wholedisk
= blkid_devno_to_devname(disk_devno
);
785 wholedisk
= xstrdup(device
);
786 disk_devno
= part_devno
;
793 if (device
&& (upper
|| lower
))
794 errx(EXIT_FAILURE
, _("--nr and <partition> are mutually exclusive"));
799 /* use partno from given partition instead of --nr range, e.g:
802 * partx -d --nr 3 /dev/sda
806 if (!part_devno
&& !stat(device
, &sb
))
807 part_devno
= sb
.st_rdev
;
809 lower
= upper
= get_partno_from_device(device
, part_devno
);
813 printf(_("partition: %s, disk: %s, lower: %d, upper: %d\n"),
814 device
? device
: "none", wholedisk
, lower
, upper
);
816 if (what
== ACT_ADD
|| what
== ACT_DELETE
) {
819 if (stat(wholedisk
, &x
))
820 errx(EXIT_FAILURE
, "%s", wholedisk
);
822 if (S_ISREG(x
.st_mode
)) {
823 /* not a blkdev, try to associate it to a loop device */
824 if (what
== ACT_DELETE
)
825 errx(EXIT_FAILURE
, _("%s: cannot delete partitions"),
827 if (!loopmod_supports_partscan())
828 errx(EXIT_FAILURE
, _("%s: partitioned loop devices unsupported"),
830 assoc_loopdev(wholedisk
);
831 wholedisk
= xstrdup(lc
.device
);
832 } else if (!S_ISBLK(x
.st_mode
))
833 errx(EXIT_FAILURE
, _("%s: not a block device"), wholedisk
);
835 if ((fd
= open(wholedisk
, O_RDONLY
)) == -1)
836 err(EXIT_FAILURE
, _("cannot open %s"), wholedisk
);
838 if (what
== ACT_DELETE
)
839 rc
= del_parts(fd
, wholedisk
, disk_devno
, lower
, upper
);
841 blkid_probe pr
= blkid_new_probe();
842 blkid_partlist ls
= NULL
;
844 if (!pr
|| blkid_probe_set_device(pr
, fd
, 0, 0))
845 warnx(_("%s: failed to initialize blkid prober"),
848 ls
= get_partlist(pr
, wholedisk
, type
);
851 int n
= blkid_partlist_numof_partitions(ls
);
854 lower
= n
+ lower
+ 1;
856 upper
= n
+ upper
+ 1;
858 warnx(_("specified range <%d:%d> "
859 "does not make sense"), lower
, upper
);
860 rc
= -1, what
= ACT_NONE
;
865 rc
= show_parts(ls
, tt_flags
, lower
, upper
);
868 rc
= list_parts(ls
, lower
, upper
);
871 rc
= add_parts(fd
, wholedisk
, ls
, lower
, upper
);
879 blkid_free_probe(pr
);
886 return rc
? EXIT_FAILURE
: EXIT_SUCCESS
;