]> git.ipfire.org Git - thirdparty/util-linux.git/blame - disk-utils/partx.c
misc: consolidate smartcols error messages
[thirdparty/util-linux.git] / disk-utils / partx.c
CommitLineData
22853e4a 1/*
c4ecaf21 2 * partx: tell the kernel about your disk's partitions
22853e4a
KZ
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.]
6 *
22853e4a 7 * aeb, 2000-03-21 -- sah is 42 now
c4ecaf21
DB
8 *
9 * Copyright (C) 2010 Davidlohr Bueso <dave@gnu.org>
a9485396 10 * Rewritten to use libblkid for util-linux
c4ecaf21 11 * based on ideas from Karel Zak <kzak@redhat.com>
22853e4a
KZ
12 */
13
14#include <stdio.h>
22853e4a
KZ
15#include <errno.h>
16#include <stdlib.h>
c4ecaf21 17#include <ctype.h>
22853e4a 18#include <getopt.h>
1d4ad1de 19#include <unistd.h>
c4ecaf21 20#include <assert.h>
c4ecaf21
DB
21#include <dirent.h>
22
23#include <blkid.h>
016aa0ac 24#include <libsmartcols.h>
0d518f34 25
1aff9b62 26#include "c.h"
c4ecaf21
DB
27#include "pathnames.h"
28#include "nls.h"
0d518f34 29#include "blkdev.h"
c4ecaf21
DB
30#include "strutils.h"
31#include "xalloc.h"
22853e4a 32#include "partx.h"
a88268b8 33#include "sysfs.h"
0e938113 34#include "loopdev.h"
757bbfad 35#include "closestream.h"
6320c5aa 36#include "optutils.h"
22853e4a 37
c4ecaf21
DB
38/* this is the default upper limit, could be modified by --nr */
39#define SLICES_MAX 256
40
016aa0ac
OO
41/* basic table settings */
42enum {
43 PARTX_RAW = (1 << 0),
44 PARTX_NOHEADINGS = (1 << 1),
45 PARTX_EXPORT = (1 << 2),
46};
47
c4ecaf21
DB
48/* all the columns (-o option) */
49enum {
50 COL_PARTNO,
51 COL_START,
52 COL_END,
53 COL_SECTORS,
54 COL_SIZE,
55 COL_NAME,
56 COL_UUID,
57 COL_TYPE,
5de966b3
KZ
58 COL_FLAGS,
59 COL_SCHEME,
c4ecaf21 60};
22853e4a 61
6320c5aa 62#define ACT_ERROR "--{add,delete,show,list,raw,pairs}"
c4ecaf21 63enum {
6320c5aa
SK
64 ACT_NONE,
65 ACT_LIST,
c4ecaf21
DB
66 ACT_SHOW,
67 ACT_ADD,
3b905b79 68 ACT_UPD,
c4ecaf21
DB
69 ACT_DELETE
70};
71
72enum {
73 FL_BYTES = (1 << 1)
74};
75
76/* column names */
77struct colinfo {
78 const char *name; /* header */
79 double whint; /* width hint (N < 1 is in percent of termwidth) */
016aa0ac 80 int flags; /* SCOLS_FL_* */
c4ecaf21
DB
81 const char *help;
82};
22853e4a 83
c4ecaf21 84/* columns descriptions */
2ba641e5 85static struct colinfo infos[] = {
016aa0ac
OO
86 [COL_PARTNO] = { "NR", 0.25, SCOLS_FL_RIGHT, N_("partition number") },
87 [COL_START] = { "START", 0.30, SCOLS_FL_RIGHT, N_("start of the partition in sectors") },
88 [COL_END] = { "END", 0.30, SCOLS_FL_RIGHT, N_("end of the partition in sectors") },
89 [COL_SECTORS] = { "SECTORS", 0.30, SCOLS_FL_RIGHT, N_("number of sectors") },
90 [COL_SIZE] = { "SIZE", 0.30, SCOLS_FL_RIGHT, N_("human readable size") },
91 [COL_NAME] = { "NAME", 0.30, SCOLS_FL_TRUNC, N_("partition name") },
c4ecaf21 92 [COL_UUID] = { "UUID", 36, 0, N_("partition UUID")},
016aa0ac
OO
93 [COL_SCHEME] = { "SCHEME", 0.1, SCOLS_FL_TRUNC, N_("partition table type (dos, gpt, ...)")},
94 [COL_FLAGS] = { "FLAGS", 0.1, SCOLS_FL_TRUNC, N_("partition flags")},
95 [COL_TYPE] = { "TYPE", 1, SCOLS_FL_RIGHT, N_("partition type (a string, a UUID, or hex)")},
c4ecaf21 96};
10ebfeea
DB
97
98#define NCOLS ARRAY_SIZE(infos)
99
c4ecaf21 100/* array with IDs of enabled columns */
40b17508 101static int columns[NCOLS];
2ba641e5 102static size_t ncolumns;
c4ecaf21
DB
103
104static int verbose;
105static int partx_flags;
0e938113
DB
106static struct loopdev_cxt lc;
107static int loopdev;
22853e4a 108
0e938113
DB
109static void assoc_loopdev(const char *fname)
110{
111 int rc;
112
defa0710
KZ
113 if (loopcxt_init(&lc, 0))
114 err(EXIT_FAILURE, _("failed to initialize loopcxt"));
0e938113
DB
115
116 rc = loopcxt_find_unused(&lc);
117 if (rc)
118 err(EXIT_FAILURE, _("%s: failed to find unused loop device"),
119 fname);
120
121 if (verbose)
122 printf(_("Trying to use '%s' for the loop device\n"),
123 loopcxt_get_device(&lc));
124
125 if (loopcxt_set_backing_file(&lc, fname))
126 err(EXIT_FAILURE, _("%s: failed to set backing file"), fname);
127
128 rc = loopcxt_setup_device(&lc);
129
130 if (rc == -EBUSY)
dbfff473 131 err(EXIT_FAILURE, _("%s: failed to set up loop device"), fname);
0e938113
DB
132
133 loopdev = 1;
134}
22853e4a 135
c4ecaf21 136static inline int get_column_id(int num)
1d4ad1de 137{
10ebfeea 138 assert(ARRAY_SIZE(columns) == NCOLS);
b9710f1f 139 assert((size_t)num < ncolumns);
10ebfeea 140 assert(columns[num] < (int) NCOLS);
c4ecaf21 141 return columns[num];
22853e4a
KZ
142}
143
c4ecaf21 144static inline struct colinfo *get_column_info(int num)
1d4ad1de 145{
c4ecaf21 146 return &infos[ get_column_id(num) ];
22853e4a
KZ
147}
148
c4ecaf21
DB
149static int column_name_to_id(const char *name, size_t namesz)
150{
10ebfeea 151 size_t i;
22853e4a 152
c4ecaf21 153 assert(name);
22853e4a 154
10ebfeea 155 for (i = 0; i < NCOLS; i++) {
c4ecaf21 156 const char *cn = infos[i].name;
22853e4a 157
c4ecaf21
DB
158 if (!strncasecmp(name, cn, namesz) && !*(cn + namesz))
159 return i;
22853e4a 160 }
c4ecaf21
DB
161 warnx(_("unknown column: %s"), name);
162 return -1;
163}
22853e4a 164
c4ecaf21
DB
165/*
166 * Given a partition return the corresponding partition number.
167 *
168 * Note that this function tries to use sysfs, otherwise it assumes that the
169 * last characters are always numeric (sda1, sdc20, etc).
c4ecaf21
DB
170 */
171static int get_partno_from_device(char *partition, dev_t devno)
172{
173 int partno = 0;
174 size_t sz;
175 char *p, *end = NULL;
176
177 assert(partition);
178
179 if (devno) {
a88268b8 180 struct sysfs_cxt cxt;
43e3f054 181 int rc;
a88268b8 182
5bfbbc78
KZ
183 if (sysfs_init(&cxt, devno, NULL))
184 goto err;
185
43e3f054
KZ
186 rc = sysfs_read_int(&cxt, "partition", &partno);
187 sysfs_deinit(&cxt);
188
189 if (rc == 0)
c4ecaf21
DB
190 return partno;
191 }
22853e4a 192
c4ecaf21
DB
193 sz = strlen(partition);
194 p = partition + sz - 1;
22853e4a 195
bae57b5a 196 if (!isdigit((unsigned char) *p))
c4ecaf21 197 goto err;
22853e4a 198
bae57b5a 199 while (isdigit((unsigned char) *(p - 1))) p--;
c4ecaf21
DB
200
201 errno = 0;
202 partno = strtol(p, &end, 10);
203 if (errno || !end || *end || p == end)
204 goto err;
205
206 return partno;
207err:
208 errx(EXIT_FAILURE, _("%s: failed to get partition number"), partition);
209}
210
211static int get_max_partno(const char *disk, dev_t devno)
212{
741a5b10 213 char path[PATH_MAX], *parent, *dirname = NULL;
c4ecaf21
DB
214 struct stat st;
215 DIR *dir;
216 struct dirent *d;
217 int partno = 0;
218
219 if (!devno && !stat(disk, &st))
220 devno = st.st_rdev;
221 if (!devno)
222 goto dflt;
223 parent = strrchr(disk, '/');
224 if (!parent)
225 goto dflt;
226 parent++;
227
228 snprintf(path, sizeof(path), _PATH_SYS_DEVBLOCK "/%d:%d/",
229 major(devno), minor(devno));
230
231 dir = opendir(path);
232 if (!dir)
233 goto dflt;
234
741a5b10
KZ
235 dirname = xstrdup(path);
236
237 while ((d = readdir(dir))) {
c4ecaf21
DB
238 int fd;
239
240 if (!strcmp(d->d_name, ".") ||
241 !strcmp(d->d_name, ".."))
242 continue;
243#ifdef _DIRENT_HAVE_D_TYPE
a7c60528 244 if (d->d_type != DT_DIR && d->d_type != DT_UNKNOWN)
c4ecaf21
DB
245 continue;
246#endif
247 if (strncmp(parent, d->d_name, strlen(parent)))
248 continue;
249 snprintf(path, sizeof(path), "%s/partition", d->d_name);
250
2208b3cc 251 fd = openat(dirfd(dir), path, O_RDONLY);
c4ecaf21
DB
252 if (fd) {
253 int x = 0;
254 FILE *f = fdopen(fd, "r");
255 if (f) {
256 if (fscanf(f, "%d", &x) == 1 && x > partno)
257 partno = x;
258 fclose(f);
22853e4a 259 }
22853e4a 260 }
22853e4a
KZ
261 }
262
741a5b10 263 free(dirname);
c4ecaf21
DB
264 closedir(dir);
265 return partno;
266dflt:
267 return SLICES_MAX;
268}
269
2d47fa39
KZ
270static int recount_range_by_pt(blkid_partlist ls, int *lower, int *upper)
271{
272 int n = 0, i, nparts = blkid_partlist_numof_partitions(ls);
273
274 for (i = 0; i < nparts; i++) {
275 blkid_partition par = blkid_partlist_get_partition(ls, i);
276 int partno = blkid_partition_get_partno(par);
277 n = max(partno, n);
278 }
279
280 if (*lower < 0)
281 *lower = n + *lower + 1;
282 if (*upper < 0)
283 *upper = n + *upper + 1;
284
285 if (*lower > *upper && *upper != 0) {
286 warnx(_("specified range <%d:%d> does not make sense"), *lower, *upper);
287 return -EINVAL;
288 }
289 if (verbose)
290 printf(_("range recount: max partno=%d, lower=%d, upper=%d\n"), n, *lower, *upper);
291 return 0;
292}
293
c4ecaf21
DB
294static void del_parts_warnx(const char *device, int first, int last)
295{
296 if (first == last)
297 warnx(_("%s: error deleting partition %d"), device, first);
298 else
299 warnx(_("%s: error deleting partitions %d-%d"),
300 device, first, last);
301}
302
303static int del_parts(int fd, const char *device, dev_t devno,
304 int lower, int upper)
305{
306 int rc = 0, i, errfirst = 0, errlast = 0;
307
308 assert(fd >= 0);
309 assert(device);
310
2d47fa39 311 /* recount range by information in /sys */
c4ecaf21
DB
312 if (!lower)
313 lower = 1;
314 if (!upper || lower < 0 || upper < 0) {
315 int n = get_max_partno(device, devno);
316 if (!upper)
317 upper = n;
318 else if (upper < 0)
319 upper = n + upper + 1;
320 if (lower < 0)
321 lower = n + lower + 1;
322 }
323 if (lower > upper) {
144df9a2 324 warnx(_("specified range <%d:%d> "
c4ecaf21
DB
325 "does not make sense"), lower, upper);
326 return -1;
327 }
328
329 for (i = lower; i <= upper; i++) {
ab025087
PS
330 rc = partx_del_partition(fd, i);
331 if (rc == 0) {
c4ecaf21
DB
332 if (verbose)
333 printf(_("%s: partition #%d removed\n"), device, i);
334 continue;
ab025087
PS
335 } else if (errno == ENXIO) {
336 if (verbose)
4b8dfcc8 337 printf(_("%s: partition #%d doesn't exist\n"), device, i);
ab025087 338 continue;
c4ecaf21
DB
339 }
340 rc = -1;
341 if (verbose)
144df9a2 342 warn(_("%s: deleting partition #%d failed"), device, i);
c4ecaf21
DB
343 if (!errfirst)
344 errlast = errfirst = i;
345 else if (errlast + 1 == i)
346 errlast++;
347 else {
348 del_parts_warnx(device, errfirst, errlast);
349 errlast = errfirst = i;
22853e4a 350 }
22853e4a
KZ
351 }
352
c4ecaf21
DB
353 if (errfirst)
354 del_parts_warnx(device, errfirst, errlast);
355 return rc;
356}
357
0e938113 358
c4ecaf21
DB
359static void add_parts_warnx(const char *device, int first, int last)
360{
361 if (first == last)
362 warnx(_("%s: error adding partition %d"), device, first);
363 else
364 warnx(_("%s: error adding partitions %d-%d"),
365 device, first, last);
366}
367
368static int add_parts(int fd, const char *device,
0e938113 369 blkid_partlist ls, int lower, int upper)
c4ecaf21 370{
2d47fa39 371 int i, nparts, rc, errfirst = 0, errlast = 0;
c4ecaf21
DB
372
373 assert(fd >= 0);
374 assert(device);
375 assert(ls);
376
2d47fa39
KZ
377 rc = recount_range_by_pt(ls, &lower, &upper);
378 if (rc)
379 return rc;
380
c4ecaf21
DB
381 nparts = blkid_partlist_numof_partitions(ls);
382
383 for (i = 0; i < nparts; i++) {
384 blkid_partition par = blkid_partlist_get_partition(ls, i);
385 int n = blkid_partition_get_partno(par);
386 uintmax_t start, size;
387
388 if (lower && n < lower)
389 continue;
390 if (upper && n > upper)
391 continue;
392
393 start = blkid_partition_get_start(par);
394 size = blkid_partition_get_size(par);
395
396 if (blkid_partition_is_extended(par))
397 /*
144df9a2
BS
398 * Let's follow the Linux kernel and reduce
399 * DOS extended partition to 1 or 2 sectors.
c4ecaf21
DB
400 */
401 size = min(size, (uintmax_t) 2);
402
403 if (partx_add_partition(fd, n, start, size) == 0) {
404 if (verbose)
405 printf(_("%s: partition #%d added\n"), device, n);
406 continue;
407 }
408 rc = -1;
409 if (verbose)
144df9a2 410 warn(_("%s: adding partition #%d failed"), device, n);
c4ecaf21
DB
411 if (!errfirst)
412 errlast = errfirst = n;
413 else if (errlast + 1 == n)
414 errlast++;
415 else {
416 add_parts_warnx(device, errfirst, errlast);
417 errlast = errfirst = n;
418 }
22853e4a 419 }
c4ecaf21
DB
420
421 if (errfirst)
422 add_parts_warnx(device, errfirst, errlast);
0e938113 423
59d749c3
KZ
424 /*
425 * The kernel with enabled partitions scanner for loop devices add *all*
426 * partitions, so we should delete any extra, unwanted ones, when the -n
427 * option is passed.
428 */
429 if (loopdev && loopcxt_is_partscan(&lc) && (lower || upper)) {
0e938113
DB
430 for (i = 0; i < nparts; i++) {
431 blkid_partition par = blkid_partlist_get_partition(ls, i);
432 int n = blkid_partition_get_partno(par);
433
434 if (n < lower || n > upper)
435 partx_del_partition(fd, n);
436 }
437 }
438
c4ecaf21
DB
439 return rc;
440}
441
3b905b79
PS
442static void upd_parts_warnx(const char *device, int first, int last)
443{
444 if (first == last)
445 warnx(_("%s: error updating partition %d"), device, first);
446 else
447 warnx(_("%s: error updating partitions %d-%d"),
448 device, first, last);
449}
450
451static int upd_parts(int fd, const char *device, dev_t devno,
452 blkid_partlist ls, int lower, int upper)
453{
84ac3112 454 int n, nparts, rc = 0, errfirst = 0, errlast = 0, err;
3b905b79
PS
455 blkid_partition par;
456 uintmax_t start, size;
457
458 assert(fd >= 0);
459 assert(device);
460 assert(ls);
461
2d47fa39
KZ
462 /* recount range by information in /sys, if on disk number of
463 * partitions is greater than in /sys the use on-disk limit */
3b905b79
PS
464 nparts = blkid_partlist_numof_partitions(ls);
465 if (!lower)
466 lower = 1;
467 if (!upper || lower < 0 || upper < 0) {
468 n = get_max_partno(device, devno);
469 if (!upper)
470 upper = n > nparts ? n : nparts;
471 else if (upper < 0)
472 upper = n + upper + 1;
473 if (lower < 0)
474 lower = n + lower + 1;
475 }
476 if (lower > upper) {
477 warnx(_("specified range <%d:%d> "
478 "does not make sense"), lower, upper);
479 return -1;
480 }
481
84ac3112 482 for (n = lower; n <= upper; n++) {
c62f164c 483 par = blkid_partlist_get_partition_by_partno(ls, n);
84ac3112
SM
484 if (!par) {
485 if (verbose)
486 warn(_("%s: no partition #%d"), device, n);
3b905b79 487 continue;
84ac3112 488 }
3b905b79
PS
489
490 start = blkid_partition_get_start(par);
491 size = blkid_partition_get_size(par);
3b905b79
PS
492 if (blkid_partition_is_extended(par))
493 /*
494 * Let's follow the Linux kernel and reduce
495 * DOS extended partition to 1 or 2 sectors.
496 */
497 size = min(size, (uintmax_t) 2);
498
499 err = partx_del_partition(fd, n);
500 if (err == -1 && errno == ENXIO)
501 err = 0; /* good, it already doesn't exist */
84ac3112 502 if (err == -1 && errno == EBUSY)
3b905b79 503 {
84ac3112
SM
504 /* try to resize */
505 err = partx_resize_partition(fd, n, start, size);
506 if (verbose)
507 printf(_("%s: partition #%d resized\n"), device, n);
508 if (err == 0)
3b905b79 509 continue;
3b905b79 510 }
84ac3112
SM
511 if (err == 0 && partx_add_partition(fd, n, start, size) == 0) {
512 if (verbose)
513 printf(_("%s: partition #%d added\n"), device, n);
514 continue;
515 }
516
3b905b79
PS
517 if (err == 0)
518 continue;
519 rc = -1;
520 if (verbose)
521 warn(_("%s: updating partition #%d failed"), device, n);
522 if (!errfirst)
523 errlast = errfirst = n;
524 else if (errlast + 1 == n)
525 errlast++;
526 else {
527 upd_parts_warnx(device, errfirst, errlast);
528 errlast = errfirst = n;
529 }
530 }
531
532 if (errfirst)
533 upd_parts_warnx(device, errfirst, errlast);
534 return rc;
535}
536
c4ecaf21
DB
537static int list_parts(blkid_partlist ls, int lower, int upper)
538{
2d47fa39 539 int i, nparts, rc;
c4ecaf21
DB
540
541 assert(ls);
542
2d47fa39
KZ
543 rc = recount_range_by_pt(ls, &lower, &upper);
544 if (rc)
545 return rc;
546
c4ecaf21
DB
547 nparts = blkid_partlist_numof_partitions(ls);
548
549 for (i = 0; i < nparts; i++) {
550 blkid_partition par = blkid_partlist_get_partition(ls, i);
551 int n = blkid_partition_get_partno(par);
552 uintmax_t start, size;
553
554 if (lower && n < lower)
555 continue;
556 if (upper && n > upper)
557 continue;
558
559 start = blkid_partition_get_start(par);
560 size = blkid_partition_get_size(par);
561
0df61bea
BS
562 printf(P_("#%2d: %9ju-%9ju (%9ju sector, %6ju MB)\n",
563 "#%2d: %9ju-%9ju (%9ju sectors, %6ju MB)\n",
564 size),
c4ecaf21
DB
565 n, start, start + size -1,
566 size, (size << 9) / 1000000);
22853e4a 567 }
c4ecaf21
DB
568 return 0;
569}
570
3b80b370 571static int add_scols_line(struct libscols_table *table, blkid_partition par)
c4ecaf21 572{
016aa0ac 573 struct libscols_line *line;
3b80b370 574 int i, rc = 0;
c4ecaf21 575
016aa0ac 576 assert(table);
c4ecaf21 577 assert(par);
22853e4a 578
016aa0ac 579 line = scols_table_new_line(table, NULL);
c4ecaf21 580 if (!line) {
780ce22c 581 warn(_("failed to allocate output line"));
3b80b370 582 return -ENOMEM;
22853e4a 583 }
22853e4a 584
b9710f1f 585 for (i = 0; (size_t)i < ncolumns; i++) {
3b80b370
KZ
586 char *str = NULL; /* allocated string */
587 const char *cstr = NULL; /* foreign string */
c4ecaf21
DB
588
589 switch (get_column_id(i)) {
590 case COL_PARTNO:
8acf2fb6 591 xasprintf(&str, "%d", blkid_partition_get_partno(par));
c4ecaf21
DB
592 break;
593 case COL_START:
8acf2fb6 594 xasprintf(&str, "%ju", blkid_partition_get_start(par));
c4ecaf21
DB
595 break;
596 case COL_END:
8acf2fb6 597 xasprintf(&str, "%ju",
c4ecaf21
DB
598 blkid_partition_get_start(par) +
599 blkid_partition_get_size(par) - 1);
600 break;
601 case COL_SECTORS:
8acf2fb6 602 xasprintf(&str, "%ju", blkid_partition_get_size(par));
c4ecaf21
DB
603 break;
604 case COL_SIZE:
605 if (partx_flags & FL_BYTES)
8acf2fb6 606 xasprintf(&str, "%ju", (uintmax_t)
c4ecaf21 607 blkid_partition_get_size(par) << 9);
5de966b3 608 else
5d2a9849 609 str = size_to_human_string(SIZE_SUFFIX_1LETTER,
c4ecaf21 610 blkid_partition_get_size(par) << 9);
c4ecaf21
DB
611 break;
612 case COL_NAME:
3b80b370 613 cstr = blkid_partition_get_name(par);
c4ecaf21
DB
614 break;
615 case COL_UUID:
3b80b370 616 cstr = blkid_partition_get_uuid(par);
c4ecaf21
DB
617 break;
618 case COL_TYPE:
6df8dcfb 619 if (blkid_partition_get_type_string(par))
3b80b370 620 cstr = blkid_partition_get_type_string(par);
5de966b3 621 else
8acf2fb6 622 xasprintf(&str, "0x%x",
5de966b3 623 blkid_partition_get_type(par));
c4ecaf21 624 break;
5de966b3 625 case COL_FLAGS:
8acf2fb6 626 xasprintf(&str, "0x%llx", blkid_partition_get_flags(par));
5de966b3
KZ
627 break;
628 case COL_SCHEME:
629 {
630 blkid_parttable tab = blkid_partition_get_table(par);
6df8dcfb 631 if (tab)
3b80b370 632 cstr = blkid_parttable_get_type(tab);
5de966b3
KZ
633 break;
634 }
c4ecaf21
DB
635 default:
636 break;
637 }
638
3b80b370
KZ
639 if (cstr)
640 rc = scols_line_set_data(line, i, cstr);
641 else if (str)
642 rc = scols_line_refer_data(line, i, str);
643 if (rc) {
780ce22c 644 warn(_("failed to add output data"));
3b80b370
KZ
645 break;
646 }
22853e4a 647 }
3b80b370
KZ
648
649 return rc;
c4ecaf21 650}
22853e4a 651
016aa0ac 652static int show_parts(blkid_partlist ls, int scols_flags, int lower, int upper)
c4ecaf21
DB
653{
654 int i, rc = -1;
016aa0ac 655 struct libscols_table *table;
c4ecaf21 656 int nparts;
22853e4a 657
c4ecaf21
DB
658 assert(ls);
659
660 nparts = blkid_partlist_numof_partitions(ls);
661 if (!nparts)
662 return 0;
663
710ed55d 664 scols_init_debug(0);
0925a9dd 665 table = scols_new_table();
016aa0ac 666 if (!table) {
780ce22c 667 warn(_("failed to allocate output table"));
c4ecaf21 668 return -1;
22853e4a 669 }
0925a9dd
KZ
670 scols_table_enable_raw(table, !!(scols_flags & PARTX_RAW));
671 scols_table_enable_export(table, !!(scols_flags & PARTX_EXPORT));
672 scols_table_enable_noheadings(table, !!(scols_flags & PARTX_NOHEADINGS));
22853e4a 673
b9710f1f 674 for (i = 0; (size_t)i < ncolumns; i++) {
c4ecaf21
DB
675 struct colinfo *col = get_column_info(i);
676
016aa0ac 677 if (!scols_table_new_column(table, col->name, col->whint, col->flags)) {
780ce22c 678 warnx(_("failed to allocate output column"));
c4ecaf21 679 goto done;
22853e4a
KZ
680 }
681 }
682
2d47fa39
KZ
683 rc = recount_range_by_pt(ls, &lower, &upper);
684 if (rc)
685 goto done;
686
c4ecaf21
DB
687 for (i = 0; i < nparts; i++) {
688 blkid_partition par = blkid_partlist_get_partition(ls, i);
689 int n = blkid_partition_get_partno(par);
22853e4a 690
c4ecaf21
DB
691 if (lower && n < lower)
692 continue;
693 if (upper && n > upper)
694 continue;
22853e4a 695
3b80b370
KZ
696 rc = add_scols_line(table, par);
697 if (rc)
698 break;
22853e4a 699 }
c4ecaf21
DB
700
701 rc = 0;
016aa0ac 702 scols_print_table(table);
c4ecaf21 703done:
016aa0ac 704 scols_unref_table(table);
c4ecaf21 705 return rc;
22853e4a
KZ
706}
707
c4ecaf21
DB
708static blkid_partlist get_partlist(blkid_probe pr,
709 const char *device, char *type)
710{
711 blkid_partlist ls;
712 blkid_parttable tab;
713
714 assert(pr);
715 assert(device);
716
717 if (type) {
718 char *name[] = { type, NULL };
719
720 if (blkid_probe_filter_partitions_type(pr,
721 BLKID_FLTR_ONLYIN, name)) {
722 warnx(_("failed to initialize blkid "
144df9a2 723 "filter for '%s'"), type);
c4ecaf21
DB
724 return NULL;
725 }
726 }
727
728 ls = blkid_probe_get_partitions(pr);
729 if (!ls) {
730 warnx(_("%s: failed to read partition table"), device);
731 return NULL;
732 }
733
734 tab = blkid_partlist_get_table(ls);
83ae4c24 735 if (verbose && tab) {
144df9a2 736 printf(_("%s: partition table type '%s' detected\n"),
83ae4c24 737 device, blkid_parttable_get_type(tab));
c4ecaf21 738
83ae4c24
KZ
739 if (!blkid_partlist_numof_partitions(ls))
740 printf(_("%s: partition table with no partitions"), device);
22853e4a 741 }
83ae4c24 742
c4ecaf21
DB
743 return ls;
744}
745
abafd686 746static void __attribute__((__noreturn__)) usage(FILE *out)
c4ecaf21 747{
10ebfeea 748 size_t i;
c4ecaf21 749
4ded3823 750 fputs(USAGE_HEADER, out);
e96fd176 751 fprintf(out,
3b905b79 752 _(" %s [-a|-d|-s|-u] [--nr <n:m> | <partition>] <disk>\n"),
c4ecaf21
DB
753 program_invocation_short_name);
754
451dbcfa
BS
755 fputs(USAGE_SEPARATOR, out);
756 fputs(_("Tell the kernel about the presence and numbering of partitions.\n"), out);
757
8275b732 758 fputs(USAGE_OPTIONS, out);
b7e785ed
SK
759 fputs(_(" -a, --add add specified partitions or all of them\n"), out);
760 fputs(_(" -d, --delete delete specified partitions or all of them\n"), out);
b7e785ed 761 fputs(_(" -u, --update update specified partitions or all of them\n"), out);
dbfff473 762 fputs(_(" -s, --show list partitions\n\n"), out);
b7e785ed
SK
763 fputs(_(" -b, --bytes print SIZE in bytes rather than in human readable format\n"), out);
764 fputs(_(" -g, --noheadings don't print headings for --show\n"), out);
765 fputs(_(" -n, --nr <n:m> specify the range of partitions (e.g. --nr 2:4)\n"), out);
dbfff473 766 fputs(_(" -o, --output <list> define which output columns to use\n"), out);
b7e785ed
SK
767 fputs(_(" -P, --pairs use key=\"value\" output format\n"), out);
768 fputs(_(" -r, --raw use raw output format\n"), out);
f8a4a0d4 769 fputs(_(" -S, --sector-size <num> overwrite sector size\n"), out);
2cdaf94b
SK
770 fputs(_(" -t, --type <type> specify the partition type\n"), out);
771 fputs(_(" --list-types list supported partition types and exit\n"), out);
b7e785ed 772 fputs(_(" -v, --verbose verbose mode\n"), out);
8275b732
KZ
773
774 fputs(USAGE_SEPARATOR, out);
775 fputs(USAGE_HELP, out);
776 fputs(USAGE_VERSION, out);
c4ecaf21 777
e96fd176 778 fputs(_("\nAvailable columns (for --show, --raw or --pairs):\n"), out);
c4ecaf21 779
10ebfeea 780 for (i = 0; i < NCOLS; i++)
d015794e 781 fprintf(out, " %10s %s\n", infos[i].name, _(infos[i].help));
c4ecaf21 782
4ded3823 783 fprintf(out, USAGE_MAN_TAIL("partx(8)"));
c4ecaf21
DB
784
785 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
786}
787
c4ecaf21
DB
788int main(int argc, char **argv)
789{
6320c5aa 790 int fd, c, what = ACT_NONE, lower = 0, upper = 0, rc = 0;
016aa0ac 791 int scols_flags = 0;
c4ecaf21 792 char *type = NULL;
1d6a5daa 793 char *device = NULL; /* pointer to argv[], ie: /dev/sda1 */
c4ecaf21 794 char *wholedisk = NULL; /* allocated, ie: /dev/sda */
4e395c55 795 char *outarg = NULL;
c4ecaf21 796 dev_t disk_devno = 0, part_devno = 0;
f8a4a0d4 797 unsigned int sector_size = 0;
c4ecaf21 798
2cdaf94b
SK
799 enum {
800 OPT_LIST_TYPES = CHAR_MAX + 1
801 };
c4ecaf21
DB
802 static const struct option long_opts[] = {
803 { "bytes", no_argument, NULL, 'b' },
804 { "noheadings", no_argument, NULL, 'g' },
805 { "raw", no_argument, NULL, 'r' },
806 { "list", no_argument, NULL, 'l' },
807 { "show", no_argument, NULL, 's' },
808 { "add", no_argument, NULL, 'a' },
809 { "delete", no_argument, NULL, 'd' },
3b905b79 810 { "update", no_argument, NULL, 'u' },
c4ecaf21 811 { "type", required_argument, NULL, 't' },
2cdaf94b 812 { "list-types", no_argument, NULL, OPT_LIST_TYPES },
c4ecaf21
DB
813 { "nr", required_argument, NULL, 'n' },
814 { "output", required_argument, NULL, 'o' },
8ed48785 815 { "pairs", no_argument, NULL, 'P' },
f8a4a0d4 816 { "sector-size",required_argument, NULL, 'S' },
c4ecaf21 817 { "help", no_argument, NULL, 'h' },
72bb1cc9 818 { "version", no_argument, NULL, 'V' },
8275b732 819 { "verbose", no_argument, NULL, 'v' },
c4ecaf21
DB
820 { NULL, 0, NULL, 0 }
821 };
822
a7349ee3 823 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
08ec8a6f 824 { 'P','a','d','l','r','s','u' },
a29627cb
KZ
825 { 0 }
826 };
827 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
828
5c87aa1a
BS
829 setlocale(LC_ALL, "");
830 bindtextdomain(PACKAGE, LOCALEDIR);
831 textdomain(PACKAGE);
757bbfad 832 atexit(close_stdout);
5c87aa1a 833
8ed48785 834 while ((c = getopt_long(argc, argv,
f8a4a0d4 835 "abdglrsuvn:t:o:PS:hV", long_opts, NULL)) != -1) {
a29627cb
KZ
836
837 err_exclusive_options(c, long_opts, excl, excl_st);
838
c4ecaf21
DB
839 switch(c) {
840 case 'a':
a29627cb 841 what = ACT_ADD;
c4ecaf21
DB
842 break;
843 case 'b':
844 partx_flags |= FL_BYTES;
845 break;
846 case 'd':
a29627cb 847 what = ACT_DELETE;
c4ecaf21
DB
848 break;
849 case 'g':
016aa0ac 850 scols_flags |= PARTX_NOHEADINGS;
c4ecaf21
DB
851 break;
852 case 'l':
a29627cb 853 what = ACT_LIST;
c4ecaf21
DB
854 break;
855 case 'n':
af7df9ee 856 if (parse_range(optarg, &lower, &upper, 0))
c4ecaf21
DB
857 errx(EXIT_FAILURE, _("failed to parse --nr <M-N> range"));
858 break;
c4ecaf21 859 case 'o':
4e395c55 860 outarg = optarg;
c4ecaf21 861 break;
8ed48785 862 case 'P':
016aa0ac 863 scols_flags |= PARTX_EXPORT;
a29627cb 864 what = ACT_SHOW;
8ed48785 865 break;
c4ecaf21 866 case 'r':
016aa0ac 867 scols_flags |= PARTX_RAW;
a29627cb 868 what = ACT_SHOW;
c4ecaf21 869 break;
c4ecaf21 870 case 's':
a29627cb 871 what = ACT_SHOW;
c4ecaf21 872 break;
f8a4a0d4
KZ
873 case 'S':
874 sector_size = strtou32_or_err(optarg, _("invalid sector size argument"));
875 break;
c4ecaf21
DB
876 case 't':
877 type = optarg;
878 break;
3b905b79
PS
879 case 'u':
880 what = ACT_UPD;
881 break;
c4ecaf21
DB
882 case 'v':
883 verbose = 1;
884 break;
2cdaf94b
SK
885 case OPT_LIST_TYPES:
886 {
887 size_t idx = 0;
888 const char *name = NULL;
889
890 while (blkid_partitions_get_name(idx++, &name) == 0)
891 puts(name);
892 return EXIT_SUCCESS;
893 }
c4ecaf21
DB
894 case 'h':
895 usage(stdout);
72bb1cc9
SK
896 case 'V':
897 printf(UTIL_LINUX_VERSION);
898 return EXIT_SUCCESS;
c4ecaf21 899 default:
677ec86c 900 errtryhelp(EXIT_FAILURE);
c4ecaf21
DB
901 }
902 }
903
6320c5aa 904 if (what == ACT_NONE)
7cfd1b26 905 what = ACT_SHOW;
c4ecaf21
DB
906
907 /* --show default, could by modified by -o */
908 if (what == ACT_SHOW && !ncolumns) {
909 columns[ncolumns++] = COL_PARTNO;
910 columns[ncolumns++] = COL_START;
911 columns[ncolumns++] = COL_END;
912 columns[ncolumns++] = COL_SECTORS;
913 columns[ncolumns++] = COL_SIZE;
914 columns[ncolumns++] = COL_NAME;
915 columns[ncolumns++] = COL_UUID;
916 }
917
4e395c55
MB
918 if (what == ACT_SHOW && outarg &&
919 string_add_to_idarray(outarg, columns, ARRAY_SIZE(columns),
920 &ncolumns, column_name_to_id) < 0)
921 return EXIT_FAILURE;
922
c4ecaf21
DB
923 /*
924 * Note that 'partx /dev/sda1' == 'partx /dev/sda1 /dev/sda'
925 * so assume that the device and/or disk are always the last
926 * arguments to be passed to partx.
927 */
928 if (optind == argc - 2) {
929 /* passed 2 arguments:
930 * /dev/sda1 /dev/sda : partition + whole-disk
931 * -- /dev/sda1 : partition that should be used as a whole-disk
932 */
933 device = argv[optind];
934
935 if (strcmp(device, "-") == 0) {
936 device = NULL;
937 wholedisk = xstrdup(argv[optind + 1]);
938 } else {
939 device = argv[optind];
940 wholedisk = xstrdup(argv[optind + 1]);
2d47fa39
KZ
941
942 if (device && wholedisk && !startswith(device, wholedisk))
943 errx(EXIT_FAILURE, _("partition and disk name do not match"));
c4ecaf21
DB
944 }
945 } else if (optind == argc - 1) {
946 /* passed only one arg (ie: /dev/sda3 or /dev/sda) */
947 struct stat sb;
948
949 device = argv[optind];
950
951 if (stat(device, &sb))
fc14ceba 952 err(EXIT_FAILURE, _("stat of %s failed"), device);
c4ecaf21
DB
953
954 part_devno = sb.st_rdev;
955
956 if (blkid_devno_to_wholedisk(part_devno,
957 NULL, 0, &disk_devno) == 0 &&
958 part_devno != disk_devno)
959 wholedisk = blkid_devno_to_devname(disk_devno);
960
961 if (!wholedisk) {
962 wholedisk = xstrdup(device);
963 disk_devno = part_devno;
964 device = NULL;
965 part_devno = 0;
22853e4a 966 }
22853e4a 967 } else
c4ecaf21
DB
968 usage(stderr);
969
970 if (device && (upper || lower))
e22d8b95 971 errx(EXIT_FAILURE, _("--nr and <partition> are mutually exclusive"));
c4ecaf21
DB
972
973 assert(wholedisk);
974
975 if (device) {
976 /* use partno from given partition instead of --nr range, e.g:
977 * partx -d /dev/sda3
978 * is the same like:
979 * partx -d --nr 3 /dev/sda
980 */
981 struct stat sb;
982
983 if (!part_devno && !stat(device, &sb))
984 part_devno = sb.st_rdev;
985
986 lower = upper = get_partno_from_device(device, part_devno);
987 }
988
989 if (verbose)
144df9a2 990 printf(_("partition: %s, disk: %s, lower: %d, upper: %d\n"),
2e2b6bb1 991 device ? device : "none", wholedisk, lower, upper);
c4ecaf21
DB
992
993 if (what == ACT_ADD || what == ACT_DELETE) {
994 struct stat x;
995
0e938113
DB
996 if (stat(wholedisk, &x))
997 errx(EXIT_FAILURE, "%s", wholedisk);
998
999 if (S_ISREG(x.st_mode)) {
1000 /* not a blkdev, try to associate it to a loop device */
1001 if (what == ACT_DELETE)
1002 errx(EXIT_FAILURE, _("%s: cannot delete partitions"),
1003 wholedisk);
59d749c3 1004 if (!loopmod_supports_partscan())
0e938113
DB
1005 errx(EXIT_FAILURE, _("%s: partitioned loop devices unsupported"),
1006 wholedisk);
1007 assoc_loopdev(wholedisk);
1008 wholedisk = xstrdup(lc.device);
1009 } else if (!S_ISBLK(x.st_mode))
c4ecaf21
DB
1010 errx(EXIT_FAILURE, _("%s: not a block device"), wholedisk);
1011 }
1012 if ((fd = open(wholedisk, O_RDONLY)) == -1)
289dcc90 1013 err(EXIT_FAILURE, _("cannot open %s"), wholedisk);
c4ecaf21
DB
1014
1015 if (what == ACT_DELETE)
1016 rc = del_parts(fd, wholedisk, disk_devno, lower, upper);
1017 else {
1018 blkid_probe pr = blkid_new_probe();
1019 blkid_partlist ls = NULL;
1020
1021 if (!pr || blkid_probe_set_device(pr, fd, 0, 0))
1022 warnx(_("%s: failed to initialize blkid prober"),
1023 wholedisk);
f8a4a0d4
KZ
1024 else {
1025 if (sector_size)
1026 blkid_probe_set_sectorsize(pr, sector_size);
1027
c4ecaf21 1028 ls = get_partlist(pr, wholedisk, type);
f8a4a0d4 1029 }
c4ecaf21
DB
1030
1031 if (ls) {
c4ecaf21
DB
1032 switch (what) {
1033 case ACT_SHOW:
016aa0ac 1034 rc = show_parts(ls, scols_flags, lower, upper);
c4ecaf21
DB
1035 break;
1036 case ACT_LIST:
1037 rc = list_parts(ls, lower, upper);
1038 break;
1039 case ACT_ADD:
1040 rc = add_parts(fd, wholedisk, ls, lower, upper);
1041 break;
3b905b79
PS
1042 case ACT_UPD:
1043 rc = upd_parts(fd, wholedisk, disk_devno, ls, lower, upper);
2d47fa39 1044 break;
6320c5aa
SK
1045 case ACT_NONE:
1046 break;
1047 default:
1048 abort();
c4ecaf21
DB
1049 }
1050 }
1051 blkid_free_probe(pr);
1052 }
1053
0e938113
DB
1054 if (loopdev)
1055 loopcxt_deinit(&lc);
1056
83874290
SK
1057 if (close_fd(fd) != 0)
1058 err(EXIT_FAILURE, _("write failed"));
1059
c4ecaf21 1060 return rc ? EXIT_FAILURE : EXIT_SUCCESS;
22853e4a 1061}