]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/lsblk.c
Merge branch 'meson-more-build-options' of https://github.com/jwillikers/util-linux
[thirdparty/util-linux.git] / misc-utils / lsblk.c
1 /*
2 * lsblk(8) - list block devices
3 *
4 * Copyright (C) 2010-2018 Red Hat, Inc. All rights reserved.
5 * Written by Milan Broz <mbroz@redhat.com>
6 * Karel Zak <kzak@redhat.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it would be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22 #include <stdio.h>
23 #include <errno.h>
24 #include <getopt.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <dirent.h>
30 #include <fcntl.h>
31 #include <string.h>
32 #include <sys/ioctl.h>
33 #include <stdarg.h>
34 #include <locale.h>
35 #include <pwd.h>
36 #include <grp.h>
37 #include <ctype.h>
38 #include <assert.h>
39
40 #include <blkid.h>
41
42 #include "c.h"
43 #include "pathnames.h"
44 #include "blkdev.h"
45 #include "canonicalize.h"
46 #include "nls.h"
47 #include "xalloc.h"
48 #include "strutils.h"
49 #include "sysfs.h"
50 #include "closestream.h"
51 #include "optutils.h"
52 #include "fileutils.h"
53
54 #include "lsblk.h"
55
56 UL_DEBUG_DEFINE_MASK(lsblk);
57 UL_DEBUG_DEFINE_MASKNAMES(lsblk) = UL_DEBUG_EMPTY_MASKNAMES;
58
59 #define LSBLK_EXIT_SOMEOK 64
60 #define LSBLK_EXIT_ALLFAILED 32
61
62 static int column_id_to_number(int id);
63
64 /* column IDs */
65 enum {
66 COL_NAME = 0,
67 COL_KNAME,
68 COL_PATH,
69 COL_MAJMIN,
70 COL_FSAVAIL,
71 COL_FSSIZE,
72 COL_FSTYPE,
73 COL_FSUSED,
74 COL_FSUSEPERC,
75 COL_TARGET,
76 COL_LABEL,
77 COL_UUID,
78 COL_PTUUID,
79 COL_PTTYPE,
80 COL_PARTTYPE,
81 COL_PARTLABEL,
82 COL_PARTUUID,
83 COL_PARTFLAGS,
84 COL_RA,
85 COL_RO,
86 COL_RM,
87 COL_HOTPLUG,
88 COL_MODEL,
89 COL_SERIAL,
90 COL_SIZE,
91 COL_STATE,
92 COL_OWNER,
93 COL_GROUP,
94 COL_MODE,
95 COL_ALIOFF,
96 COL_MINIO,
97 COL_OPTIO,
98 COL_PHYSEC,
99 COL_LOGSEC,
100 COL_ROTA,
101 COL_SCHED,
102 COL_RQ_SIZE,
103 COL_TYPE,
104 COL_DALIGN,
105 COL_DGRAN,
106 COL_DMAX,
107 COL_DZERO,
108 COL_WSAME,
109 COL_WWN,
110 COL_RAND,
111 COL_PKNAME,
112 COL_HCTL,
113 COL_TRANSPORT,
114 COL_SUBSYS,
115 COL_REV,
116 COL_VENDOR,
117 COL_ZONED,
118 };
119
120 /* basic table settings */
121 enum {
122 LSBLK_ASCII = (1 << 0),
123 LSBLK_RAW = (1 << 1),
124 LSBLK_NOHEADINGS = (1 << 2),
125 LSBLK_EXPORT = (1 << 3),
126 LSBLK_TREE = (1 << 4),
127 LSBLK_JSON = (1 << 5),
128 };
129
130 /* Types used for qsort() and JSON */
131 enum {
132 COLTYPE_STR = 0, /* default */
133 COLTYPE_NUM = 1, /* always u64 number */
134 COLTYPE_SORTNUM = 2, /* string on output, u64 for qsort() */
135 COLTYPE_SIZE = 3, /* srring by default, number when --bytes */
136 COLTYPE_BOOL = 4 /* 0 or 1 */
137 };
138
139 /* column names */
140 struct colinfo {
141 const char *name; /* header */
142 double whint; /* width hint (N < 1 is in percent of termwidth) */
143 int flags; /* SCOLS_FL_* */
144 const char *help;
145 int type; /* COLTYPE_* */
146 };
147
148 /* columns descriptions */
149 static struct colinfo infos[] = {
150 [COL_NAME] = { "NAME", 0.25, SCOLS_FL_NOEXTREMES, N_("device name") },
151 [COL_KNAME] = { "KNAME", 0.3, 0, N_("internal kernel device name") },
152 [COL_PKNAME] = { "PKNAME", 0.3, 0, N_("internal parent kernel device name") },
153 [COL_PATH] = { "PATH", 0.3, 0, N_("path to the device node") },
154 [COL_MAJMIN] = { "MAJ:MIN", 6, 0, N_("major:minor device number"), COLTYPE_SORTNUM },
155
156 [COL_FSAVAIL] = { "FSAVAIL", 5, SCOLS_FL_RIGHT, N_("filesystem size available") },
157 [COL_FSSIZE] = { "FSSIZE", 5, SCOLS_FL_RIGHT, N_("filesystem size") },
158 [COL_FSTYPE] = { "FSTYPE", 0.1, SCOLS_FL_TRUNC, N_("filesystem type") },
159 [COL_FSUSED] = { "FSUSED", 5, SCOLS_FL_RIGHT, N_("filesystem size used") },
160 [COL_FSUSEPERC] = { "FSUSE%", 3, SCOLS_FL_RIGHT, N_("filesystem use percentage") },
161
162 [COL_TARGET] = { "MOUNTPOINT", 0.10, SCOLS_FL_TRUNC, N_("where the device is mounted") },
163 [COL_LABEL] = { "LABEL", 0.1, 0, N_("filesystem LABEL") },
164 [COL_UUID] = { "UUID", 36, 0, N_("filesystem UUID") },
165
166 [COL_PTUUID] = { "PTUUID", 36, 0, N_("partition table identifier (usually UUID)") },
167 [COL_PTTYPE] = { "PTTYPE", 0.1, 0, N_("partition table type") },
168
169 [COL_PARTTYPE] = { "PARTTYPE", 36, 0, N_("partition type UUID") },
170 [COL_PARTLABEL] = { "PARTLABEL", 0.1, 0, N_("partition LABEL") },
171 [COL_PARTUUID] = { "PARTUUID", 36, 0, N_("partition UUID") },
172 [COL_PARTFLAGS] = { "PARTFLAGS", 36, 0, N_("partition flags") },
173
174 [COL_RA] = { "RA", 3, SCOLS_FL_RIGHT, N_("read-ahead of the device"), COLTYPE_NUM },
175 [COL_RO] = { "RO", 1, SCOLS_FL_RIGHT, N_("read-only device"), COLTYPE_BOOL },
176 [COL_RM] = { "RM", 1, SCOLS_FL_RIGHT, N_("removable device"), COLTYPE_BOOL },
177 [COL_HOTPLUG]= { "HOTPLUG", 1, SCOLS_FL_RIGHT, N_("removable or hotplug device (usb, pcmcia, ...)"), COLTYPE_BOOL },
178 [COL_ROTA] = { "ROTA", 1, SCOLS_FL_RIGHT, N_("rotational device"), COLTYPE_BOOL },
179 [COL_RAND] = { "RAND", 1, SCOLS_FL_RIGHT, N_("adds randomness"), COLTYPE_BOOL },
180 [COL_MODEL] = { "MODEL", 0.1, SCOLS_FL_TRUNC, N_("device identifier") },
181 [COL_SERIAL] = { "SERIAL", 0.1, SCOLS_FL_TRUNC, N_("disk serial number") },
182 [COL_SIZE] = { "SIZE", 5, SCOLS_FL_RIGHT, N_("size of the device"), COLTYPE_SIZE },
183 [COL_STATE] = { "STATE", 7, SCOLS_FL_TRUNC, N_("state of the device") },
184 [COL_OWNER] = { "OWNER", 0.1, SCOLS_FL_TRUNC, N_("user name"), },
185 [COL_GROUP] = { "GROUP", 0.1, SCOLS_FL_TRUNC, N_("group name") },
186 [COL_MODE] = { "MODE", 10, 0, N_("device node permissions") },
187 [COL_ALIOFF] = { "ALIGNMENT", 6, SCOLS_FL_RIGHT, N_("alignment offset"), COLTYPE_NUM },
188 [COL_MINIO] = { "MIN-IO", 6, SCOLS_FL_RIGHT, N_("minimum I/O size"), COLTYPE_NUM },
189 [COL_OPTIO] = { "OPT-IO", 6, SCOLS_FL_RIGHT, N_("optimal I/O size"), COLTYPE_NUM },
190 [COL_PHYSEC] = { "PHY-SEC", 7, SCOLS_FL_RIGHT, N_("physical sector size"), COLTYPE_NUM },
191 [COL_LOGSEC] = { "LOG-SEC", 7, SCOLS_FL_RIGHT, N_("logical sector size"), COLTYPE_NUM },
192 [COL_SCHED] = { "SCHED", 0.1, 0, N_("I/O scheduler name") },
193 [COL_RQ_SIZE]= { "RQ-SIZE", 5, SCOLS_FL_RIGHT, N_("request queue size"), COLTYPE_NUM },
194 [COL_TYPE] = { "TYPE", 4, 0, N_("device type") },
195 [COL_DALIGN] = { "DISC-ALN", 6, SCOLS_FL_RIGHT, N_("discard alignment offset"), COLTYPE_NUM },
196 [COL_DGRAN] = { "DISC-GRAN", 6, SCOLS_FL_RIGHT, N_("discard granularity"), COLTYPE_SIZE },
197 [COL_DMAX] = { "DISC-MAX", 6, SCOLS_FL_RIGHT, N_("discard max bytes"), COLTYPE_SIZE },
198 [COL_DZERO] = { "DISC-ZERO", 1, SCOLS_FL_RIGHT, N_("discard zeroes data"), COLTYPE_BOOL },
199 [COL_WSAME] = { "WSAME", 6, SCOLS_FL_RIGHT, N_("write same max bytes"), COLTYPE_SIZE },
200 [COL_WWN] = { "WWN", 18, 0, N_("unique storage identifier") },
201 [COL_HCTL] = { "HCTL", 10, 0, N_("Host:Channel:Target:Lun for SCSI") },
202 [COL_TRANSPORT] = { "TRAN", 6, 0, N_("device transport type") },
203 [COL_SUBSYS] = { "SUBSYSTEMS", 0.1, SCOLS_FL_NOEXTREMES, N_("de-duplicated chain of subsystems") },
204 [COL_REV] = { "REV", 4, SCOLS_FL_RIGHT, N_("device revision") },
205 [COL_VENDOR] = { "VENDOR", 0.1, SCOLS_FL_TRUNC, N_("device vendor") },
206 [COL_ZONED] = { "ZONED", 0.3, 0, N_("zone model") },
207 };
208
209 struct lsblk *lsblk; /* global handler */
210
211 /*
212 * columns[] array specifies all currently wanted output column. The columns
213 * are defined by infos[] array and you can specify (on command line) each
214 * column twice. That's enough, dynamically allocated array of the columns is
215 * unnecessary overkill and over-engineering in this case
216 */
217 static int columns[ARRAY_SIZE(infos) * 2];
218 static size_t ncolumns;
219
220 static inline void add_column(int id)
221 {
222 if (ncolumns >= ARRAY_SIZE(columns))
223 errx(EXIT_FAILURE, _("too many columns specified, "
224 "the limit is %zu columns"),
225 ARRAY_SIZE(columns) - 1);
226 columns[ ncolumns++ ] = id;
227 }
228
229 static inline void add_uniq_column(int id)
230 {
231 if (column_id_to_number(id) < 0)
232 add_column(id);
233 }
234
235 static void lsblk_init_debug(void)
236 {
237 __UL_INIT_DEBUG_FROM_ENV(lsblk, LSBLK_DEBUG_, 0, LSBLK_DEBUG);
238 }
239
240 /*
241 * exclude/include devices filter based on major device numbers
242 */
243 static int excludes[256];
244 static size_t nexcludes;
245
246 static int includes[256];
247 static size_t nincludes;
248
249 static int is_maj_excluded(int maj)
250 {
251 size_t i;
252
253 assert(ARRAY_SIZE(excludes) > nexcludes);
254
255 if (!nexcludes)
256 return 0; /* filter not enabled, device not excluded */
257
258 for (i = 0; i < nexcludes; i++) {
259 if (excludes[i] == maj) {
260 DBG(FILTER, ul_debug("exclude: maj=%d", maj));
261 return 1;
262 }
263 }
264 return 0;
265 }
266
267 static int is_maj_included(int maj)
268 {
269 size_t i;
270
271 assert(ARRAY_SIZE(includes) > nincludes);
272
273 if (!nincludes)
274 return 1; /* filter not enabled, device is included */
275
276 for (i = 0; i < nincludes; i++) {
277 if (includes[i] == maj) {
278 DBG(FILTER, ul_debug("include: maj=%d", maj));
279 return 1;
280 }
281 }
282 return 0;
283 }
284
285 /* Converts column sequential number to column ID (COL_*) */
286 static int get_column_id(int num)
287 {
288 assert(num >= 0);
289 assert((size_t) num < ncolumns);
290 assert(columns[num] < (int) ARRAY_SIZE(infos));
291 return columns[num];
292 }
293
294 /* Returns column description for the column sequential number */
295 static struct colinfo *get_column_info(int num)
296 {
297 return &infos[ get_column_id(num) ];
298 }
299
300 /* Converts column name (as defined in the infos[] to the column ID */
301 static int column_name_to_id(const char *name, size_t namesz)
302 {
303 size_t i;
304
305 for (i = 0; i < ARRAY_SIZE(infos); i++) {
306 const char *cn = infos[i].name;
307
308 if (!strncasecmp(name, cn, namesz) && !*(cn + namesz))
309 return i;
310 }
311 warnx(_("unknown column: %s"), name);
312 return -1;
313 }
314
315 /* Converts column ID (COL_*) to column sequential number */
316 static int column_id_to_number(int id)
317 {
318 size_t i;
319
320 for (i = 0; i < ncolumns; i++)
321 if (columns[i] == id)
322 return i;
323 return -1;
324 }
325
326 /* Checks for DM prefix in the device name */
327 static int is_dm(const char *name)
328 {
329 return strncmp(name, "dm-", 3) ? 0 : 1;
330 }
331
332 /* Returns full pat to the device node (TODO: what about sysfs_blkdev_get_path()) */
333 static char *get_device_path(struct lsblk_device *dev)
334 {
335 char path[PATH_MAX];
336
337 assert(dev);
338 assert(dev->name);
339
340 if (is_dm(dev->name))
341 return __canonicalize_dm_name(lsblk->sysroot, dev->name);
342
343 snprintf(path, sizeof(path), "/dev/%s", dev->name);
344 sysfs_devname_sys_to_dev(path);
345 return xstrdup(path);
346 }
347
348 static int is_readonly_device(struct lsblk_device *dev)
349 {
350 int fd, ro = 0;
351
352 if (ul_path_scanf(dev->sysfs, "ro", "%d", &ro) == 1)
353 return ro;
354
355 /* fallback if "ro" attribute does not exist */
356 fd = open(dev->filename, O_RDONLY);
357 if (fd != -1) {
358 if (ioctl(fd, BLKROGET, &ro) != 0)
359 ro = 0;
360 close(fd);
361 }
362 return ro;
363 }
364
365 static char *get_scheduler(struct lsblk_device *dev)
366 {
367 char buf[128];
368 char *p, *res = NULL;
369
370 if (ul_path_read_buffer(dev->sysfs, buf, sizeof(buf), "queue/scheduler") == 0)
371 return NULL;
372 p = strchr(buf, '[');
373 if (p) {
374 res = p + 1;
375 p = strchr(res, ']');
376 if (p) {
377 *p = '\0';
378 res = xstrdup(res);
379 } else
380 res = NULL;
381 }
382 return res;
383 }
384
385 static char *get_type(struct lsblk_device *dev)
386 {
387 char *res = NULL, *p;
388
389 if (device_is_partition(dev))
390 return xstrdup("part");
391
392 if (is_dm(dev->name)) {
393 char *dm_uuid = NULL;
394
395 /* The DM_UUID prefix should be set to subsystem owning
396 * the device - LVM, CRYPT, DMRAID, MPATH, PART */
397 if (ul_path_read_string(dev->sysfs, &dm_uuid, "dm/uuid") > 0
398 && dm_uuid) {
399 char *tmp = dm_uuid;
400 char *dm_uuid_prefix = strsep(&tmp, "-");
401
402 if (dm_uuid_prefix) {
403 /* kpartx hack to remove partition number */
404 if (strncasecmp(dm_uuid_prefix, "part", 4) == 0)
405 dm_uuid_prefix[4] = '\0';
406
407 res = xstrdup(dm_uuid_prefix);
408 }
409 }
410
411 free(dm_uuid);
412 if (!res)
413 /* No UUID or no prefix - just mark it as DM device */
414 res = xstrdup("dm");
415
416 } else if (!strncmp(dev->name, "loop", 4)) {
417 res = xstrdup("loop");
418
419 } else if (!strncmp(dev->name, "md", 2)) {
420 char *md_level = NULL;
421
422 ul_path_read_string(dev->sysfs, &md_level, "md/level");
423 res = md_level ? md_level : xstrdup("md");
424
425 } else {
426 const char *type = NULL;
427 int x = 0;
428
429 if (ul_path_read_s32(dev->sysfs, &x, "device/type") == 0)
430 type = blkdev_scsi_type_to_name(x);
431 if (!type)
432 type = "disk";
433 res = xstrdup(type);
434 }
435
436 for (p = res; p && *p; p++)
437 *p = tolower((unsigned char) *p);
438 return res;
439 }
440
441 /* Thanks to lsscsi code for idea of detection logic used here */
442 static char *get_transport(struct lsblk_device *dev)
443 {
444 struct path_cxt *sysfs = dev->sysfs;
445 char *attr = NULL;
446 const char *trans = NULL;
447
448
449 /* SCSI - Serial Peripheral Interface */
450 if (sysfs_blkdev_scsi_host_is(sysfs, "spi"))
451 trans = "spi";
452
453 /* FC/FCoE - Fibre Channel / Fibre Channel over Ethernet */
454 else if (sysfs_blkdev_scsi_host_is(sysfs, "fc")) {
455 attr = sysfs_blkdev_scsi_host_strdup_attribute(sysfs, "fc", "symbolic_name");
456 if (!attr)
457 return NULL;
458 trans = strstr(attr, " over ") ? "fcoe" : "fc";
459 free(attr);
460 }
461
462 /* SAS - Serial Attached SCSI */
463 else if (sysfs_blkdev_scsi_host_is(sysfs, "sas") ||
464 sysfs_blkdev_scsi_has_attribute(sysfs, "sas_device"))
465 trans = "sas";
466
467
468 /* SBP - Serial Bus Protocol (FireWire) */
469 else if (sysfs_blkdev_scsi_has_attribute(sysfs, "ieee1394_id"))
470 trans = "sbp";
471
472 /* iSCSI */
473 else if (sysfs_blkdev_scsi_host_is(sysfs, "iscsi"))
474 trans ="iscsi";
475
476 /* USB - Universal Serial Bus */
477 else if (sysfs_blkdev_scsi_path_contains(sysfs, "usb"))
478 trans = "usb";
479
480 /* ATA, SATA */
481 else if (sysfs_blkdev_scsi_host_is(sysfs, "scsi")) {
482 attr = sysfs_blkdev_scsi_host_strdup_attribute(sysfs, "scsi", "proc_name");
483 if (!attr)
484 return NULL;
485 if (!strncmp(attr, "ahci", 4) || !strncmp(attr, "sata", 4))
486 trans = "sata";
487 else if (strstr(attr, "ata"))
488 trans = "ata";
489 free(attr);
490
491 } else if (strncmp(dev->name, "nvme", 4) == 0)
492 trans = "nvme";
493
494 return trans ? xstrdup(trans) : NULL;
495 }
496
497 static char *get_subsystems(struct lsblk_device *dev)
498 {
499 char path[PATH_MAX];
500 char *sub, *chain, *res = NULL;
501 size_t len = 0, last = 0;
502
503 chain = sysfs_blkdev_get_devchain(dev->sysfs, path, sizeof(path));
504 if (!chain)
505 return NULL;
506
507 while (sysfs_blkdev_next_subsystem(dev->sysfs, chain, &sub) == 0) {
508 size_t sz;
509
510 /* don't create "block:scsi:scsi", but "block:scsi" */
511 if (len && strcmp(res + last, sub) == 0) {
512 free(sub);
513 continue;
514 }
515
516 sz = strlen(sub);
517 res = xrealloc(res, len + sz + 2);
518 if (len)
519 res[len++] = ':';
520
521 memcpy(res + len, sub, sz + 1);
522 last = len;
523 len += sz;
524 free(sub);
525 }
526
527 return res;
528 }
529
530
531 #define is_parsable(_l) (scols_table_is_raw((_l)->table) || \
532 scols_table_is_export((_l)->table) || \
533 scols_table_is_json((_l)->table))
534
535 static char *mk_name(const char *name)
536 {
537 char *p;
538 if (!name)
539 return NULL;
540 if (lsblk->paths)
541 xasprintf(&p, "/dev/%s", name);
542 else
543 p = xstrdup(name);
544 if (p)
545 sysfs_devname_sys_to_dev(p);
546 return p;
547 }
548
549 static char *mk_dm_name(const char *name)
550 {
551 char *p;
552 if (!name)
553 return NULL;
554 if (lsblk->paths)
555 xasprintf(&p, "/dev/mapper/%s", name);
556 else
557 p = xstrdup(name);
558 return p;
559 }
560
561 /* stores data to scols cell userdata (invisible and independent on output)
562 * to make the original values accessible for sort functions
563 */
564 static void set_sortdata_u64(struct libscols_line *ln, int col, uint64_t x)
565 {
566 struct libscols_cell *ce = scols_line_get_cell(ln, col);
567 uint64_t *data;
568
569 if (!ce)
570 return;
571 data = xmalloc(sizeof(uint64_t));
572 *data = x;
573 scols_cell_set_userdata(ce, data);
574 }
575
576 /* do not modify *data on any error */
577 static void str2u64(const char *str, uint64_t *data)
578 {
579 uintmax_t num;
580 char *end = NULL;
581
582 errno = 0;
583 if (str == NULL || *str == '\0')
584 return;
585 num = strtoumax(str, &end, 10);
586
587 if (errno || str == end || (end && *end))
588 return;
589 *data = num;
590 }
591
592 static void unref_sortdata(struct libscols_table *tb)
593 {
594 struct libscols_iter *itr;
595 struct libscols_line *ln;
596
597 if (!tb || !lsblk->sort_col)
598 return;
599 itr = scols_new_iter(SCOLS_ITER_FORWARD);
600 if (!itr)
601 return;
602 while (scols_table_next_line(tb, itr, &ln) == 0) {
603 struct libscols_cell *ce = scols_line_get_column_cell(ln,
604 lsblk->sort_col);
605 void *data = scols_cell_get_userdata(ce);
606 free(data);
607 }
608
609 scols_free_iter(itr);
610 }
611
612 static char *get_vfs_attribute(struct lsblk_device *dev, int id)
613 {
614 char *sizestr;
615 uint64_t vfs_attr = 0;
616 char *mnt;
617
618 if (!dev->fsstat.f_blocks) {
619 mnt = lsblk_device_get_mountpoint(dev);
620 if (!mnt || dev->is_swap)
621 return NULL;
622 if (statvfs(mnt, &dev->fsstat) != 0)
623 return NULL;
624 }
625
626 switch(id) {
627 case COL_FSSIZE:
628 vfs_attr = dev->fsstat.f_frsize * dev->fsstat.f_blocks;
629 break;
630 case COL_FSAVAIL:
631 vfs_attr = dev->fsstat.f_frsize * dev->fsstat.f_bavail;
632 break;
633 case COL_FSUSED:
634 vfs_attr = dev->fsstat.f_frsize * (dev->fsstat.f_blocks - dev->fsstat.f_bfree);
635 break;
636 case COL_FSUSEPERC:
637 if (dev->fsstat.f_blocks == 0)
638 return xstrdup("-");
639
640 xasprintf(&sizestr, "%.0f%%",
641 (double)(dev->fsstat.f_blocks - dev->fsstat.f_bfree) /
642 dev->fsstat.f_blocks * 100);
643 return sizestr;
644 }
645
646 if (!vfs_attr)
647 sizestr = xstrdup("0");
648 else if (lsblk->bytes)
649 xasprintf(&sizestr, "%ju", vfs_attr);
650 else
651 sizestr = size_to_human_string(SIZE_SUFFIX_1LETTER, vfs_attr);
652
653 return sizestr;
654 }
655
656 static struct stat *device_get_stat(struct lsblk_device *dev)
657 {
658 if (!dev->st.st_rdev
659 && stat(dev->filename, &dev->st) != 0)
660 return NULL;
661
662 return &dev->st;
663 }
664
665 static int is_removable_device(struct lsblk_device *dev, struct lsblk_device *parent)
666 {
667 struct path_cxt *pc;
668
669 if (dev->removable != -1)
670 goto done;
671 if (ul_path_scanf(dev->sysfs, "removable", "%d", &dev->removable) == 1)
672 goto done;
673
674 if (parent) {
675 pc = sysfs_blkdev_get_parent(dev->sysfs);
676 if (!pc)
677 goto done;
678
679 /* dev is partition and parent is whole-disk */
680 if (pc == parent->sysfs)
681 dev->removable = is_removable_device(parent, NULL);
682
683 /* parent is something else, use sysfs parent */
684 else if (ul_path_scanf(pc, "removable", "%d", &dev->removable) != 1)
685 dev->removable = 0;
686 }
687 done:
688 if (dev->removable == -1)
689 dev->removable = 0;
690 return dev->removable;
691 }
692
693 static uint64_t device_get_discard_granularity(struct lsblk_device *dev)
694 {
695 if (dev->discard_granularity == (uint64_t) -1
696 && ul_path_read_u64(dev->sysfs, &dev->discard_granularity,
697 "queue/discard_granularity") != 0)
698 dev->discard_granularity = 0;
699
700 return dev->discard_granularity;
701 }
702
703 /*
704 * Generates data (string) for column specified by column ID for specified device. If sortdata
705 * is not NULL then returns number usable to sort the column if the data are available for the
706 * column.
707 */
708 static char *device_get_data(
709 struct lsblk_device *dev, /* device */
710 struct lsblk_device *parent, /* device parent as defined in the tree */
711 int id, /* column ID (COL_*) */
712 uint64_t *sortdata) /* returns sort data as number */
713 {
714 struct lsblk_devprop *prop;
715 char *str = NULL;
716
717 switch(id) {
718 case COL_NAME:
719 str = dev->dm_name ? mk_dm_name(dev->dm_name) : mk_name(dev->name);
720 break;
721 case COL_KNAME:
722 str = mk_name(dev->name);
723 break;
724 case COL_PKNAME:
725 if (parent)
726 str = mk_name(parent->name);
727 break;
728 case COL_PATH:
729 if (dev->filename)
730 str = xstrdup(dev->filename);
731 break;
732 case COL_OWNER:
733 {
734 struct stat *st = device_get_stat(dev);
735 struct passwd *pw = st ? getpwuid(st->st_uid) : NULL;
736 if (pw)
737 str = xstrdup(pw->pw_name);
738 break;
739 }
740 case COL_GROUP:
741 {
742 struct stat *st = device_get_stat(dev);
743 struct group *gr = st ? getgrgid(st->st_gid) : NULL;
744 if (gr)
745 str = xstrdup(gr->gr_name);
746 break;
747 }
748 case COL_MODE:
749 {
750 struct stat *st = device_get_stat(dev);
751 char md[11] = { '\0' };
752
753 if (st)
754 str = xstrdup(xstrmode(st->st_mode, md));
755 break;
756 }
757 case COL_MAJMIN:
758 if (is_parsable(lsblk))
759 xasprintf(&str, "%u:%u", dev->maj, dev->min);
760 else
761 xasprintf(&str, "%3u:%-3u", dev->maj, dev->min);
762 if (sortdata)
763 *sortdata = makedev(dev->maj, dev->min);
764 break;
765 case COL_FSTYPE:
766 prop = lsblk_device_get_properties(dev);
767 if (prop && prop->fstype)
768 str = xstrdup(prop->fstype);
769 break;
770 case COL_FSSIZE:
771 case COL_FSAVAIL:
772 case COL_FSUSED:
773 case COL_FSUSEPERC:
774 str = get_vfs_attribute(dev, id);
775 break;
776 case COL_TARGET:
777 str = xstrdup(lsblk_device_get_mountpoint(dev));
778 break;
779 case COL_LABEL:
780 prop = lsblk_device_get_properties(dev);
781 if (prop && prop->label)
782 str = xstrdup(prop->label);
783 break;
784 case COL_UUID:
785 prop = lsblk_device_get_properties(dev);
786 if (prop && prop->uuid)
787 str = xstrdup(prop->uuid);
788 break;
789 case COL_PTUUID:
790 prop = lsblk_device_get_properties(dev);
791 if (prop && prop->ptuuid)
792 str = xstrdup(prop->ptuuid);
793 break;
794 case COL_PTTYPE:
795 prop = lsblk_device_get_properties(dev);
796 if (prop && prop->pttype)
797 str = xstrdup(prop->pttype);
798 break;
799 case COL_PARTTYPE:
800 prop = lsblk_device_get_properties(dev);
801 if (prop && prop->parttype)
802 str = xstrdup(prop->parttype);
803 break;
804 case COL_PARTLABEL:
805 prop = lsblk_device_get_properties(dev);
806 if (prop && prop->partlabel)
807 str = xstrdup(prop->partlabel);
808 break;
809 case COL_PARTUUID:
810 prop = lsblk_device_get_properties(dev);
811 if (prop && prop->partuuid)
812 str = xstrdup(prop->partuuid);
813 break;
814 case COL_PARTFLAGS:
815 prop = lsblk_device_get_properties(dev);
816 if (prop && prop->partflags)
817 str = xstrdup(prop->partflags);
818 break;
819 case COL_WWN:
820 prop = lsblk_device_get_properties(dev);
821 if (prop && prop->wwn)
822 str = xstrdup(prop->wwn);
823 break;
824 case COL_RA:
825 ul_path_read_string(dev->sysfs, &str, "queue/read_ahead_kb");
826 if (sortdata)
827 str2u64(str, sortdata);
828 break;
829 case COL_RO:
830 str = xstrdup(is_readonly_device(dev) ? "1" : "0");
831 break;
832 case COL_RM:
833 str = xstrdup(is_removable_device(dev, parent) ? "1" : "0");
834 break;
835 case COL_HOTPLUG:
836 str = sysfs_blkdev_is_hotpluggable(dev->sysfs) ? xstrdup("1") : xstrdup("0");
837 break;
838 case COL_ROTA:
839 ul_path_read_string(dev->sysfs, &str, "queue/rotational");
840 break;
841 case COL_RAND:
842 ul_path_read_string(dev->sysfs, &str, "queue/add_random");
843 break;
844 case COL_MODEL:
845 if (!device_is_partition(dev) && dev->nslaves == 0) {
846 prop = lsblk_device_get_properties(dev);
847 if (prop && prop->model)
848 str = xstrdup(prop->model);
849 else
850 ul_path_read_string(dev->sysfs, &str, "device/model");
851 }
852 break;
853 case COL_SERIAL:
854 if (!device_is_partition(dev) && dev->nslaves == 0) {
855 prop = lsblk_device_get_properties(dev);
856 if (prop && prop->serial)
857 str = xstrdup(prop->serial);
858 else
859 ul_path_read_string(dev->sysfs, &str, "device/serial");
860 }
861 break;
862 case COL_REV:
863 if (!device_is_partition(dev) && dev->nslaves == 0)
864 ul_path_read_string(dev->sysfs, &str, "device/rev");
865 break;
866 case COL_VENDOR:
867 if (!device_is_partition(dev) && dev->nslaves == 0)
868 ul_path_read_string(dev->sysfs, &str, "device/vendor");
869 break;
870 case COL_SIZE:
871 if (!dev->size)
872 break;
873 if (lsblk->bytes)
874 xasprintf(&str, "%ju", dev->size);
875 else
876 str = size_to_human_string(SIZE_SUFFIX_1LETTER, dev->size);
877 if (sortdata)
878 *sortdata = dev->size;
879 break;
880 case COL_STATE:
881 if (!device_is_partition(dev) && !dev->dm_name)
882 ul_path_read_string(dev->sysfs, &str, "device/state");
883 else if (dev->dm_name) {
884 int x = 0;
885 if (ul_path_read_s32(dev->sysfs, &x, "dm/suspended") == 0)
886 str = xstrdup(x ? "suspended" : "running");
887 }
888 break;
889 case COL_ALIOFF:
890 ul_path_read_string(dev->sysfs, &str, "alignment_offset");
891 if (sortdata)
892 str2u64(str, sortdata);
893 break;
894 case COL_MINIO:
895 ul_path_read_string(dev->sysfs, &str, "queue/minimum_io_size");
896 if (sortdata)
897 str2u64(str, sortdata);
898 break;
899 case COL_OPTIO:
900 ul_path_read_string(dev->sysfs, &str, "queue/optimal_io_size");
901 if (sortdata)
902 str2u64(str, sortdata);
903 break;
904 case COL_PHYSEC:
905 ul_path_read_string(dev->sysfs, &str, "queue/physical_block_size");
906 if (sortdata)
907 str2u64(str, sortdata);
908 break;
909 case COL_LOGSEC:
910 ul_path_read_string(dev->sysfs, &str, "queue/logical_block_size");
911 if (sortdata)
912 str2u64(str, sortdata);
913 break;
914 case COL_SCHED:
915 str = get_scheduler(dev);
916 break;
917 case COL_RQ_SIZE:
918 ul_path_read_string(dev->sysfs, &str, "queue/nr_requests");
919 if (sortdata)
920 str2u64(str, sortdata);
921 break;
922 case COL_TYPE:
923 str = get_type(dev);
924 break;
925 case COL_HCTL:
926 {
927 int h, c, t, l;
928 if (sysfs_blkdev_scsi_get_hctl(dev->sysfs, &h, &c, &t, &l) == 0)
929 xasprintf(&str, "%d:%d:%d:%d", h, c, t, l);
930 break;
931 }
932 case COL_TRANSPORT:
933 str = get_transport(dev);
934 break;
935 case COL_SUBSYS:
936 str = get_subsystems(dev);
937 break;
938 case COL_DALIGN:
939 if (device_get_discard_granularity(dev) > 0)
940 ul_path_read_string(dev->sysfs, &str, "discard_alignment");
941 if (!str)
942 str = xstrdup("0");
943 if (sortdata)
944 str2u64(str, sortdata);
945 break;
946 case COL_DGRAN:
947 if (lsblk->bytes) {
948 ul_path_read_string(dev->sysfs, &str, "queue/discard_granularity");
949 if (sortdata)
950 str2u64(str, sortdata);
951 } else {
952 uint64_t x = device_get_discard_granularity(dev);
953 str = size_to_human_string(SIZE_SUFFIX_1LETTER, x);
954 if (sortdata)
955 *sortdata = x;
956 }
957 break;
958 case COL_DMAX:
959 if (lsblk->bytes) {
960 ul_path_read_string(dev->sysfs, &str, "queue/discard_max_bytes");
961 if (sortdata)
962 str2u64(str, sortdata);
963 } else {
964 uint64_t x;
965 if (ul_path_read_u64(dev->sysfs, &x, "queue/discard_max_bytes") == 0) {
966 str = size_to_human_string(SIZE_SUFFIX_1LETTER, x);
967 if (sortdata)
968 *sortdata = x;
969 }
970 }
971 break;
972 case COL_DZERO:
973 if (device_get_discard_granularity(dev) > 0)
974 ul_path_read_string(dev->sysfs, &str, "queue/discard_zeroes_data");
975 if (!str)
976 str = xstrdup("0");
977 break;
978 case COL_WSAME:
979 if (lsblk->bytes) {
980 ul_path_read_string(dev->sysfs, &str, "queue/write_same_max_bytes");
981 if (sortdata)
982 str2u64(str, sortdata);
983 } else {
984 uint64_t x;
985
986 if (ul_path_read_u64(dev->sysfs, &x, "queue/write_same_max_bytes") == 0) {
987 str = size_to_human_string(SIZE_SUFFIX_1LETTER, x);
988 if (sortdata)
989 *sortdata = x;
990 }
991 }
992 if (!str)
993 str = xstrdup("0");
994 break;
995 case COL_ZONED:
996 ul_path_read_string(dev->sysfs, &str, "queue/zoned");
997 break;
998 };
999
1000 return str;
1001 }
1002
1003 /*
1004 * Adds data for all wanted columns about the device to the smartcols table
1005 */
1006 static void device_to_scols(
1007 struct lsblk_device *dev,
1008 struct lsblk_device *parent,
1009 struct libscols_table *tab,
1010 struct libscols_line *parent_line)
1011 {
1012 size_t i;
1013 struct libscols_line *ln;
1014 struct lsblk_iter itr;
1015 struct lsblk_device *child = NULL;
1016 int link_group = 0;
1017
1018
1019 DBG(DEV, ul_debugobj(dev, "add '%s' to scols", dev->name));
1020 ON_DBG(DEV, if (ul_path_isopen_dirfd(dev->sysfs)) ul_debugobj(dev, " %s ---> is open!", dev->name));
1021
1022 /* Do not print device more than one in --list mode */
1023 if (!(lsblk->flags & LSBLK_TREE) && dev->is_printed)
1024 return;
1025
1026 if (lsblk->merge && list_count_entries(&dev->parents) > 1) {
1027 if (!lsblk_device_is_last_parent(dev, parent))
1028 return;
1029 link_group = 1;
1030 }
1031
1032 ln = scols_table_new_line(tab, link_group ? NULL : parent_line);
1033 if (!ln)
1034 err(EXIT_FAILURE, _("failed to allocate output line"));
1035
1036 dev->is_printed = 1;
1037
1038 if (link_group) {
1039 struct lsblk_device *p;
1040 struct libscols_line *gr = parent_line;
1041
1042 /* Merge all my parents to the one group */
1043 DBG(DEV, ul_debugobj(dev, " grouping parents [--merge]"));
1044 lsblk_reset_iter(&itr, LSBLK_ITER_FORWARD);
1045 while (lsblk_device_next_parent(dev, &itr, &p) == 0) {
1046 if (!p->scols_line) {
1047 DBG(DEV, ul_debugobj(dev, " *** ignore '%s' no scols line yet", p->name));
1048 continue;
1049 }
1050 DBG(DEV, ul_debugobj(dev, " group '%s'", p->name));
1051 scols_table_group_lines(tab, p->scols_line, gr, 0);
1052 }
1053
1054 /* Link the group -- this makes group->child connection */
1055 DBG(DEV, ul_debugobj(dev, " linking the group [--merge]"));
1056 scols_line_link_group(ln, gr, 0);
1057 }
1058
1059 /* read column specific data and set it to smartcols table line */
1060 for (i = 0; i < ncolumns; i++) {
1061 char *data;
1062 int id = get_column_id(i);
1063
1064 if (lsblk->sort_id != id)
1065 data = device_get_data(dev, parent, id, NULL);
1066 else {
1067 uint64_t sortdata = (uint64_t) -1;
1068
1069 data = device_get_data(dev, parent, id, &sortdata);
1070 if (data && sortdata != (uint64_t) -1)
1071 set_sortdata_u64(ln, i, sortdata);
1072 }
1073 DBG(DEV, ul_debugobj(dev, " refer data[%zu]=\"%s\"", i, data));
1074 if (data && scols_line_refer_data(ln, i, data))
1075 err(EXIT_FAILURE, _("failed to add output data"));
1076 }
1077
1078 dev->scols_line = ln;
1079
1080 if (dev->npartitions == 0)
1081 /* For partitions we often read from parental whole-disk sysfs,
1082 * otherwise we can close */
1083 ul_path_close_dirfd(dev->sysfs);
1084
1085 lsblk_reset_iter(&itr, LSBLK_ITER_FORWARD);
1086 while (lsblk_device_next_child(dev, &itr, &child) == 0) {
1087 DBG(DEV, ul_debugobj(dev, "%s -> continue to child", dev->name));
1088 device_to_scols(child, dev, tab, ln);
1089 DBG(DEV, ul_debugobj(dev, "%s <- child done", dev->name));
1090 }
1091
1092 /* Let's be careful with number of open files */
1093 ul_path_close_dirfd(dev->sysfs);
1094 }
1095
1096 /*
1097 * Walks on tree and adds one line for each device to the smartcols table
1098 */
1099 static void devtree_to_scols(struct lsblk_devtree *tr, struct libscols_table *tab)
1100 {
1101 struct lsblk_iter itr;
1102 struct lsblk_device *dev = NULL;
1103
1104 lsblk_reset_iter(&itr, LSBLK_ITER_FORWARD);
1105
1106 while (lsblk_devtree_next_root(tr, &itr, &dev) == 0)
1107 device_to_scols(dev, NULL, tab, NULL);
1108 }
1109
1110 /*
1111 * Reads very basic information about the device from sysfs into the device struct
1112 */
1113 static int initialize_device(struct lsblk_device *dev,
1114 struct lsblk_device *wholedisk,
1115 const char *name)
1116 {
1117 dev_t devno;
1118
1119 DBG(DEV, ul_debugobj(dev, "initialize %s [wholedisk=%p %s]",
1120 name, wholedisk, wholedisk ? wholedisk->name : ""));
1121
1122 dev->name = xstrdup(name);
1123
1124 if (wholedisk) {
1125 dev->wholedisk = wholedisk;
1126 lsblk_ref_device(wholedisk);
1127 }
1128
1129 dev->filename = get_device_path(dev);
1130 if (!dev->filename) {
1131 DBG(DEV, ul_debugobj(dev, "%s: failed to get device path", dev->name));
1132 return -1;
1133 }
1134 DBG(DEV, ul_debugobj(dev, "%s: filename=%s", dev->name, dev->filename));
1135
1136 devno = __sysfs_devname_to_devno(lsblk->sysroot, dev->name, wholedisk ? wholedisk->name : NULL);
1137 if (!devno) {
1138 DBG(DEV, ul_debugobj(dev, "%s: unknown device name", dev->name));
1139 return -1;
1140 }
1141
1142 dev->sysfs = ul_new_sysfs_path(devno, wholedisk ? wholedisk->sysfs : NULL, lsblk->sysroot);
1143 if (!dev->sysfs) {
1144 DBG(DEV, ul_debugobj(dev, "%s: failed to initialize sysfs handler", dev->name));
1145 return -1;
1146 }
1147
1148 dev->maj = major(devno);
1149 dev->min = minor(devno);
1150 dev->size = 0;
1151
1152 if (ul_path_read_u64(dev->sysfs, &dev->size, "size") == 0) /* in sectors */
1153 dev->size <<= 9; /* in bytes */
1154
1155 /* Ignore devices of zero size */
1156 if (!lsblk->all_devices && dev->size == 0) {
1157 DBG(DEV, ul_debugobj(dev, "zero size device -- ignore"));
1158 return -1;
1159 }
1160 if (is_dm(dev->name)) {
1161 ul_path_read_string(dev->sysfs, &dev->dm_name, "dm/name");
1162 if (!dev->dm_name) {
1163 DBG(DEV, ul_debugobj(dev, "%s: failed to get dm name", dev->name));
1164 return -1;
1165 }
1166 }
1167
1168 dev->npartitions = sysfs_blkdev_count_partitions(dev->sysfs, dev->name);
1169 dev->nholders = ul_path_count_dirents(dev->sysfs, "holders");
1170 dev->nslaves = ul_path_count_dirents(dev->sysfs, "slaves");
1171
1172 DBG(DEV, ul_debugobj(dev, "%s: npartitions=%d, nholders=%d, nslaves=%d",
1173 dev->name, dev->npartitions, dev->nholders, dev->nslaves));
1174
1175 /* ignore non-SCSI devices */
1176 if (lsblk->scsi && sysfs_blkdev_scsi_get_hctl(dev->sysfs, NULL, NULL, NULL, NULL)) {
1177 DBG(DEV, ul_debugobj(dev, "non-scsi device -- ignore"));
1178 return -1;
1179 }
1180
1181 DBG(DEV, ul_debugobj(dev, "%s: context successfully initialized", dev->name));
1182 return 0;
1183 }
1184
1185 static struct lsblk_device *devtree_get_device_or_new(struct lsblk_devtree *tr,
1186 struct lsblk_device *disk,
1187 const char *name)
1188 {
1189 struct lsblk_device *dev = lsblk_devtree_get_device(tr, name);
1190
1191 if (!dev) {
1192 dev = lsblk_new_device();
1193 if (!dev)
1194 err(EXIT_FAILURE, _("failed to allocate device"));
1195
1196 if (initialize_device(dev, disk, name) != 0) {
1197 lsblk_unref_device(dev);
1198 return NULL;
1199 }
1200 lsblk_devtree_add_device(tr, dev);
1201 lsblk_unref_device(dev); /* keep it referenced by devtree only */
1202 } else
1203 DBG(DEV, ul_debugobj(dev, "%s: already processed", name));
1204
1205 return dev;
1206 }
1207
1208 static int process_dependencies(
1209 struct lsblk_devtree *tr,
1210 struct lsblk_device *dev,
1211 int do_partitions);
1212
1213 /*
1214 * Read devices from whole-disk device into tree
1215 */
1216 static int process_partitions(struct lsblk_devtree *tr, struct lsblk_device *disk)
1217 {
1218 DIR *dir;
1219 struct dirent *d;
1220
1221 assert(disk);
1222
1223 /*
1224 * Do not process further if there are no partitions for
1225 * this device or the device itself is a partition.
1226 */
1227 if (!disk->npartitions || device_is_partition(disk))
1228 return -EINVAL;
1229
1230 DBG(DEV, ul_debugobj(disk, "%s: probe whole-disk for partitions", disk->name));
1231
1232 dir = ul_path_opendir(disk->sysfs, NULL);
1233 if (!dir)
1234 err(EXIT_FAILURE, _("failed to open device directory in sysfs"));
1235
1236 while ((d = xreaddir(dir))) {
1237 struct lsblk_device *part;
1238
1239 if (!(sysfs_blkdev_is_partition_dirent(dir, d, disk->name)))
1240 continue;
1241
1242 DBG(DEV, ul_debugobj(disk, " checking %s", d->d_name));
1243
1244 part = devtree_get_device_or_new(tr, disk, d->d_name);
1245 if (!part)
1246 continue;
1247
1248 if (lsblk_device_new_dependence(disk, part) == 0)
1249 process_dependencies(tr, part, 0);
1250
1251 ul_path_close_dirfd(part->sysfs);
1252 }
1253
1254 /* For partitions we need parental (whole-disk) sysfs directory pretty
1255 * often, so close it now when all is done */
1256 ul_path_close_dirfd(disk->sysfs);
1257
1258 DBG(DEV, ul_debugobj(disk, "probe whole-disk for partitions -- done"));
1259 closedir(dir);
1260 return 0;
1261 }
1262
1263 static char *get_wholedisk_from_partition_dirent(DIR *dir, struct dirent *d, char *buf, size_t bufsz)
1264 {
1265 char *p;
1266 int len;
1267
1268 if ((len = readlinkat(dirfd(dir), d->d_name, buf, bufsz - 1)) < 0)
1269 return 0;
1270
1271 buf[len] = '\0';
1272
1273 /* The path ends with ".../<device>/<partition>" */
1274 p = strrchr(buf, '/');
1275 if (!p)
1276 return NULL;
1277 *p = '\0';
1278
1279 p = strrchr(buf, '/');
1280 if (!p)
1281 return NULL;
1282 p++;
1283
1284 return p;
1285 }
1286
1287 /*
1288 * Reads slaves/holders and partitions for specified device into device tree
1289 */
1290 static int process_dependencies(
1291 struct lsblk_devtree *tr,
1292 struct lsblk_device *dev,
1293 int do_partitions)
1294 {
1295 DIR *dir;
1296 struct dirent *d;
1297 const char *depname;
1298
1299 assert(dev);
1300
1301 if (lsblk->nodeps)
1302 return 0;
1303
1304 /* read all or specified partition */
1305 if (do_partitions && dev->npartitions)
1306 process_partitions(tr, dev);
1307
1308 DBG(DEV, ul_debugobj(dev, "%s: reading dependencies", dev->name));
1309
1310 if (!(lsblk->inverse ? dev->nslaves : dev->nholders)) {
1311 DBG(DEV, ul_debugobj(dev, " ignore (no slaves/holders)"));
1312 return 0;
1313 }
1314
1315 depname = lsblk->inverse ? "slaves" : "holders";
1316 dir = ul_path_opendir(dev->sysfs, depname);
1317 if (!dir) {
1318 DBG(DEV, ul_debugobj(dev, " ignore (no slaves/holders directory)"));
1319 return 0;
1320 }
1321 ul_path_close_dirfd(dev->sysfs);
1322
1323 DBG(DEV, ul_debugobj(dev, " %s: checking for '%s' dependence", dev->name, depname));
1324
1325 while ((d = xreaddir(dir))) {
1326 struct lsblk_device *dep = NULL;
1327 struct lsblk_device *disk = NULL;
1328
1329 /* Is the dependency a partition? */
1330 if (sysfs_blkdev_is_partition_dirent(dir, d, NULL)) {
1331
1332 char buf[PATH_MAX];
1333 char *diskname;
1334
1335 DBG(DEV, ul_debugobj(dev, " %s: dependence is partition", d->d_name));
1336
1337 diskname = get_wholedisk_from_partition_dirent(dir, d, buf, sizeof(buf));
1338 if (diskname)
1339 disk = devtree_get_device_or_new(tr, NULL, diskname);
1340 if (!disk) {
1341 DBG(DEV, ul_debugobj(dev, " ignore no wholedisk ???"));
1342 goto next;
1343 }
1344
1345 dep = devtree_get_device_or_new(tr, disk, d->d_name);
1346 if (!dep)
1347 goto next;
1348
1349 if (lsblk_device_new_dependence(dev, dep) == 0)
1350 process_dependencies(tr, dep, 1);
1351
1352 if (lsblk->inverse
1353 && lsblk_device_new_dependence(dep, disk) == 0)
1354 process_dependencies(tr, disk, 0);
1355 }
1356 /* The dependency is a whole device. */
1357 else {
1358 DBG(DEV, ul_debugobj(dev, " %s: %s: dependence is whole-disk",
1359 dev->name, d->d_name));
1360
1361 dep = devtree_get_device_or_new(tr, NULL, d->d_name);
1362 if (!dep)
1363 goto next;
1364
1365 if (lsblk_device_new_dependence(dev, dep) == 0)
1366 /* For inverse tree we don't want to show partitions
1367 * if the dependence is on whole-disk */
1368 process_dependencies(tr, dep, lsblk->inverse ? 0 : 1);
1369 }
1370 next:
1371 if (dep && dep->sysfs)
1372 ul_path_close_dirfd(dep->sysfs);
1373 if (disk && disk->sysfs)
1374 ul_path_close_dirfd(disk->sysfs);
1375 }
1376 closedir(dir);
1377
1378 DBG(DEV, ul_debugobj(dev, "%s: checking for '%s' -- done", dev->name, depname));
1379 return 0;
1380 }
1381
1382 /*
1383 * Defines the device as root node in the device tree and walks on all dependencies of the device.
1384 */
1385 static int __process_one_device(struct lsblk_devtree *tr, char *devname, dev_t devno)
1386 {
1387 struct lsblk_device *dev = NULL;
1388 struct lsblk_device *disk = NULL;
1389 char buf[PATH_MAX + 1], *name = NULL, *diskname = NULL;
1390 int real_part = 0, rc = -EINVAL;
1391
1392 if (devno == 0 && devname) {
1393 struct stat st;
1394
1395 DBG(DEV, ul_debug("%s: reading alone device", devname));
1396
1397 if (stat(devname, &st) || !S_ISBLK(st.st_mode)) {
1398 warnx(_("%s: not a block device"), devname);
1399 goto leave;
1400 }
1401 devno = st.st_rdev;
1402 } else if (devno) {
1403 DBG(DEV, ul_debug("%d:%d: reading alone device", major(devno), minor(devno)));
1404 } else {
1405 assert(devno || devname);
1406 return -EINVAL;
1407 }
1408
1409 /* TODO: sysfs_devno_to_devname() internally initializes path_cxt, it
1410 * would be better to use ul_new_sysfs_path() + sysfs_blkdev_get_name()
1411 * and reuse path_cxt for initialize_device()
1412 */
1413 name = sysfs_devno_to_devname(devno, buf, sizeof(buf));
1414 if (!name) {
1415 if (devname)
1416 warn(_("%s: failed to get sysfs name"), devname);
1417 goto leave;
1418 }
1419 name = xstrdup(name);
1420
1421 if (!strncmp(name, "dm-", 3)) {
1422 /* dm mapping is never a real partition! */
1423 real_part = 0;
1424 } else {
1425 dev_t diskno = 0;
1426
1427 if (blkid_devno_to_wholedisk(devno, buf, sizeof(buf), &diskno)) {
1428 warn(_("%s: failed to get whole-disk device number"), name);
1429 goto leave;
1430 }
1431 diskname = buf;
1432 real_part = devno != diskno;
1433 }
1434
1435 if (!real_part) {
1436 /*
1437 * Device is not a partition.
1438 */
1439 DBG(DEV, ul_debug(" non-partition"));
1440
1441 dev = devtree_get_device_or_new(tr, NULL, name);
1442 if (!dev)
1443 goto leave;
1444
1445 lsblk_devtree_add_root(tr, dev);
1446 process_dependencies(tr, dev, !lsblk->inverse);
1447 } else {
1448 /*
1449 * Partition, read sysfs name of the disk device
1450 */
1451 DBG(DEV, ul_debug(" partition"));
1452
1453 disk = devtree_get_device_or_new(tr, NULL, diskname);
1454 if (!disk)
1455 goto leave;
1456
1457 dev = devtree_get_device_or_new(tr, disk, name);
1458 if (!dev)
1459 goto leave;
1460
1461 lsblk_devtree_add_root(tr, dev);
1462 process_dependencies(tr, dev, 1);
1463
1464 if (lsblk->inverse
1465 && lsblk_device_new_dependence(dev, disk) == 0)
1466 process_dependencies(tr, disk, 0);
1467 else
1468 ul_path_close_dirfd(disk->sysfs);
1469 }
1470
1471 rc = 0;
1472 leave:
1473 if (dev && dev->sysfs)
1474 ul_path_close_dirfd(dev->sysfs);
1475 if (disk && disk->sysfs)
1476 ul_path_close_dirfd(disk->sysfs);
1477 free(name);
1478 return rc;
1479 }
1480
1481 static int process_one_device(struct lsblk_devtree *tr, char *devname)
1482 {
1483 assert(devname);
1484 return __process_one_device(tr, devname, 0);
1485 }
1486
1487 /*
1488 * The /sys/block contains only root devices, and no partitions. It seems more
1489 * simple to scan /sys/dev/block where are all devices without exceptions to get
1490 * top-level devices for the reverse tree.
1491 */
1492 static int process_all_devices_inverse(struct lsblk_devtree *tr)
1493 {
1494 DIR *dir;
1495 struct dirent *d;
1496 struct path_cxt *pc = ul_new_path(_PATH_SYS_DEVBLOCK);
1497
1498 assert(lsblk->inverse);
1499
1500 if (!pc)
1501 err(EXIT_FAILURE, _("failed to allocate /sys handler"));
1502
1503 ul_path_set_prefix(pc, lsblk->sysroot);
1504 dir = ul_path_opendir(pc, NULL);
1505 if (!dir)
1506 goto done;
1507
1508 DBG(DEV, ul_debug("iterate on " _PATH_SYS_DEVBLOCK));
1509
1510 while ((d = xreaddir(dir))) {
1511 dev_t devno;
1512 int maj, min;
1513
1514 DBG(DEV, ul_debug(" %s dentry", d->d_name));
1515
1516 if (sscanf(d->d_name, "%d:%d", &maj, &min) != 2)
1517 continue;
1518 devno = makedev(maj, min);
1519
1520 if (is_maj_excluded(maj) || !is_maj_included(maj))
1521 continue;
1522 if (ul_path_countf_dirents(pc, "%s/holders", d->d_name) != 0)
1523 continue;
1524 if (sysfs_devno_count_partitions(devno) != 0)
1525 continue;
1526 __process_one_device(tr, NULL, devno);
1527 }
1528
1529 closedir(dir);
1530 done:
1531 ul_unref_path(pc);
1532 DBG(DEV, ul_debug("iterate on " _PATH_SYS_DEVBLOCK " -- done"));
1533 return 0;
1534 }
1535
1536 /*
1537 * Reads root nodes (devices) from /sys/block into devices tree
1538 */
1539 static int process_all_devices(struct lsblk_devtree *tr)
1540 {
1541 DIR *dir;
1542 struct dirent *d;
1543 struct path_cxt *pc;
1544
1545 assert(lsblk->inverse == 0);
1546
1547 pc = ul_new_path(_PATH_SYS_BLOCK);
1548 if (!pc)
1549 err(EXIT_FAILURE, _("failed to allocate /sys handler"));
1550
1551 ul_path_set_prefix(pc, lsblk->sysroot);
1552 dir = ul_path_opendir(pc, NULL);
1553 if (!dir)
1554 goto done;
1555
1556 DBG(DEV, ul_debug("iterate on " _PATH_SYS_BLOCK));
1557
1558 while ((d = xreaddir(dir))) {
1559 struct lsblk_device *dev = NULL;
1560
1561 DBG(DEV, ul_debug(" %s dentry", d->d_name));
1562 dev = devtree_get_device_or_new(tr, NULL, d->d_name);
1563 if (!dev)
1564 goto next;
1565
1566 /* remove unwanted devices */
1567 if (is_maj_excluded(dev->maj) || !is_maj_included(dev->maj)) {
1568 DBG(DEV, ul_debug(" %s: ignore (by filter)", d->d_name));
1569 lsblk_devtree_remove_device(tr, dev);
1570 dev = NULL;
1571 goto next;
1572 }
1573
1574 if (dev->nslaves) {
1575 DBG(DEV, ul_debug(" %s: ignore (in-middle)", d->d_name));
1576 goto next;
1577 }
1578
1579 lsblk_devtree_add_root(tr, dev);
1580 process_dependencies(tr, dev, 1);
1581 next:
1582 /* Let's be careful with number of open files */
1583 if (dev && dev->sysfs)
1584 ul_path_close_dirfd(dev->sysfs);
1585 }
1586
1587 closedir(dir);
1588 done:
1589 ul_unref_path(pc);
1590 DBG(DEV, ul_debug("iterate on " _PATH_SYS_BLOCK " -- done"));
1591 return 0;
1592 }
1593
1594 /*
1595 * Parses major numbers as specified on lsblk command line
1596 */
1597 static void parse_excludes(const char *str0)
1598 {
1599 const char *str = str0;
1600
1601 while (str && *str) {
1602 char *end = NULL;
1603 unsigned long n;
1604
1605 errno = 0;
1606 n = strtoul(str, &end, 10);
1607
1608 if (end == str || (end && *end && *end != ','))
1609 errx(EXIT_FAILURE, _("failed to parse list '%s'"), str0);
1610 if (errno != 0 && (n == ULONG_MAX || n == 0))
1611 err(EXIT_FAILURE, _("failed to parse list '%s'"), str0);
1612 excludes[nexcludes++] = n;
1613
1614 if (nexcludes == ARRAY_SIZE(excludes))
1615 /* TRANSLATORS: The standard value for %d is 256. */
1616 errx(EXIT_FAILURE, _("the list of excluded devices is "
1617 "too large (limit is %d devices)"),
1618 (int)ARRAY_SIZE(excludes));
1619
1620 str = end && *end ? end + 1 : NULL;
1621 }
1622 }
1623
1624 /*
1625 * Parses major numbers as specified on lsblk command line
1626 * (TODO: what about refactor and merge parse_excludes() and parse_includes().)
1627 */
1628 static void parse_includes(const char *str0)
1629 {
1630 const char *str = str0;
1631
1632 while (str && *str) {
1633 char *end = NULL;
1634 unsigned long n;
1635
1636 errno = 0;
1637 n = strtoul(str, &end, 10);
1638
1639 if (end == str || (end && *end && *end != ','))
1640 errx(EXIT_FAILURE, _("failed to parse list '%s'"), str0);
1641 if (errno != 0 && (n == ULONG_MAX || n == 0))
1642 err(EXIT_FAILURE, _("failed to parse list '%s'"), str0);
1643 includes[nincludes++] = n;
1644
1645 if (nincludes == ARRAY_SIZE(includes))
1646 /* TRANSLATORS: The standard value for %d is 256. */
1647 errx(EXIT_FAILURE, _("the list of included devices is "
1648 "too large (limit is %d devices)"),
1649 (int)ARRAY_SIZE(includes));
1650 str = end && *end ? end + 1 : NULL;
1651 }
1652 }
1653
1654 /*
1655 * see set_sortdata_u64() and columns initialization in main()
1656 */
1657 static int cmp_u64_cells(struct libscols_cell *a,
1658 struct libscols_cell *b,
1659 __attribute__((__unused__)) void *data)
1660 {
1661 uint64_t *adata = (uint64_t *) scols_cell_get_userdata(a),
1662 *bdata = (uint64_t *) scols_cell_get_userdata(b);
1663
1664 if (adata == NULL && bdata == NULL)
1665 return 0;
1666 if (adata == NULL)
1667 return -1;
1668 if (bdata == NULL)
1669 return 1;
1670 return *adata == *bdata ? 0 : *adata >= *bdata ? 1 : -1;
1671 }
1672
1673 static void device_set_dedupkey(
1674 struct lsblk_device *dev,
1675 struct lsblk_device *parent,
1676 int id)
1677 {
1678 struct lsblk_iter itr;
1679 struct lsblk_device *child = NULL;
1680
1681 dev->dedupkey = device_get_data(dev, parent, id, NULL);
1682 if (dev->dedupkey)
1683 DBG(DEV, ul_debugobj(dev, "%s: de-duplication key: %s", dev->name, dev->dedupkey));
1684
1685 if (dev->npartitions == 0)
1686 /* For partitions we often read from parental whole-disk sysfs,
1687 * otherwise we can close */
1688 ul_path_close_dirfd(dev->sysfs);
1689
1690 lsblk_reset_iter(&itr, LSBLK_ITER_FORWARD);
1691
1692 while (lsblk_device_next_child(dev, &itr, &child) == 0)
1693 device_set_dedupkey(child, dev, id);
1694
1695 /* Let's be careful with number of open files */
1696 ul_path_close_dirfd(dev->sysfs);
1697 }
1698
1699 static void devtree_set_dedupkeys(struct lsblk_devtree *tr, int id)
1700 {
1701 struct lsblk_iter itr;
1702 struct lsblk_device *dev = NULL;
1703
1704 lsblk_reset_iter(&itr, LSBLK_ITER_FORWARD);
1705
1706 while (lsblk_devtree_next_root(tr, &itr, &dev) == 0)
1707 device_set_dedupkey(dev, NULL, id);
1708 }
1709
1710 static void __attribute__((__noreturn__)) usage(void)
1711 {
1712 FILE *out = stdout;
1713 size_t i;
1714
1715 fputs(USAGE_HEADER, out);
1716 fprintf(out, _(" %s [options] [<device> ...]\n"), program_invocation_short_name);
1717
1718 fputs(USAGE_SEPARATOR, out);
1719 fputs(_("List information about block devices.\n"), out);
1720
1721 fputs(USAGE_OPTIONS, out);
1722 fputs(_(" -D, --discard print discard capabilities\n"), out);
1723 fputs(_(" -E, --dedup <column> de-duplicate output by <column>\n"), out);
1724 fputs(_(" -I, --include <list> show only devices with specified major numbers\n"), out);
1725 fputs(_(" -J, --json use JSON output format\n"), out);
1726 fputs(_(" -O, --output-all output all columns\n"), out);
1727 fputs(_(" -P, --pairs use key=\"value\" output format\n"), out);
1728 fputs(_(" -S, --scsi output info about SCSI devices\n"), out);
1729 fputs(_(" -T, --tree[=<column>] use tree format output\n"), out);
1730 fputs(_(" -a, --all print all devices\n"), out);
1731 fputs(_(" -b, --bytes print SIZE in bytes rather than in human readable format\n"), out);
1732 fputs(_(" -d, --nodeps don't print slaves or holders\n"), out);
1733 fputs(_(" -e, --exclude <list> exclude devices by major number (default: RAM disks)\n"), out);
1734 fputs(_(" -f, --fs output info about filesystems\n"), out);
1735 fputs(_(" -i, --ascii use ascii characters only\n"), out);
1736 fputs(_(" -l, --list use list format output\n"), out);
1737 fputs(_(" -M, --merge group parents of sub-trees (usable for RAIDs, Multi-path)\n"), out);
1738 fputs(_(" -m, --perms output info about permissions\n"), out);
1739 fputs(_(" -n, --noheadings don't print headings\n"), out);
1740 fputs(_(" -o, --output <list> output columns\n"), out);
1741 fputs(_(" -p, --paths print complete device path\n"), out);
1742 fputs(_(" -r, --raw use raw output format\n"), out);
1743 fputs(_(" -s, --inverse inverse dependencies\n"), out);
1744 fputs(_(" -t, --topology output info about topology\n"), out);
1745 fputs(_(" -z, --zoned print zone model\n"), out);
1746 fputs(_(" -x, --sort <column> sort output by <column>\n"), out);
1747 fputs(_(" --sysroot <dir> use specified directory as system root\n"), out);
1748 fputs(USAGE_SEPARATOR, out);
1749 printf(USAGE_HELP_OPTIONS(22));
1750
1751 fprintf(out, USAGE_COLUMNS);
1752
1753 for (i = 0; i < ARRAY_SIZE(infos); i++)
1754 fprintf(out, " %11s %s\n", infos[i].name, _(infos[i].help));
1755
1756 printf(USAGE_MAN_TAIL("lsblk(8)"));
1757
1758 exit(EXIT_SUCCESS);
1759 }
1760
1761 static void check_sysdevblock(void)
1762 {
1763 if (access(_PATH_SYS_DEVBLOCK, R_OK) != 0)
1764 err(EXIT_FAILURE, _("failed to access sysfs directory: %s"),
1765 _PATH_SYS_DEVBLOCK);
1766 }
1767
1768 int main(int argc, char *argv[])
1769 {
1770 struct lsblk _ls = {
1771 .sort_id = -1,
1772 .dedup_id = -1,
1773 .flags = LSBLK_TREE,
1774 .tree_id = COL_NAME
1775 };
1776 struct lsblk_devtree *tr = NULL;
1777 int c, status = EXIT_FAILURE;
1778 char *outarg = NULL;
1779 size_t i;
1780 int force_tree = 0, has_tree_col = 0;
1781
1782 enum {
1783 OPT_SYSROOT = CHAR_MAX + 1
1784 };
1785
1786 static const struct option longopts[] = {
1787 { "all", no_argument, NULL, 'a' },
1788 { "bytes", no_argument, NULL, 'b' },
1789 { "nodeps", no_argument, NULL, 'd' },
1790 { "discard", no_argument, NULL, 'D' },
1791 { "dedup", required_argument, NULL, 'E' },
1792 { "zoned", no_argument, NULL, 'z' },
1793 { "help", no_argument, NULL, 'h' },
1794 { "json", no_argument, NULL, 'J' },
1795 { "output", required_argument, NULL, 'o' },
1796 { "output-all", no_argument, NULL, 'O' },
1797 { "merge", no_argument, NULL, 'M' },
1798 { "perms", no_argument, NULL, 'm' },
1799 { "noheadings", no_argument, NULL, 'n' },
1800 { "list", no_argument, NULL, 'l' },
1801 { "ascii", no_argument, NULL, 'i' },
1802 { "raw", no_argument, NULL, 'r' },
1803 { "inverse", no_argument, NULL, 's' },
1804 { "fs", no_argument, NULL, 'f' },
1805 { "exclude", required_argument, NULL, 'e' },
1806 { "include", required_argument, NULL, 'I' },
1807 { "topology", no_argument, NULL, 't' },
1808 { "paths", no_argument, NULL, 'p' },
1809 { "pairs", no_argument, NULL, 'P' },
1810 { "scsi", no_argument, NULL, 'S' },
1811 { "sort", required_argument, NULL, 'x' },
1812 { "sysroot", required_argument, NULL, OPT_SYSROOT },
1813 { "tree", optional_argument, NULL, 'T' },
1814 { "version", no_argument, NULL, 'V' },
1815 { NULL, 0, NULL, 0 },
1816 };
1817
1818 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
1819 { 'D','O' },
1820 { 'I','e' },
1821 { 'J', 'P', 'r' },
1822 { 'O','S' },
1823 { 'O','f' },
1824 { 'O','m' },
1825 { 'O','o' },
1826 { 'O','t' },
1827 { 'P','T', 'l','r' },
1828 { 0 }
1829 };
1830 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
1831
1832 setlocale(LC_ALL, "");
1833 bindtextdomain(PACKAGE, LOCALEDIR);
1834 textdomain(PACKAGE);
1835 close_stdout_atexit();
1836
1837 lsblk = &_ls;
1838
1839 lsblk_init_debug();
1840
1841 while((c = getopt_long(argc, argv,
1842 "abdDzE:e:fhJlnMmo:OpPiI:rstVST:x:", longopts, NULL)) != -1) {
1843
1844 err_exclusive_options(c, longopts, excl, excl_st);
1845
1846 switch(c) {
1847 case 'a':
1848 lsblk->all_devices = 1;
1849 break;
1850 case 'b':
1851 lsblk->bytes = 1;
1852 break;
1853 case 'd':
1854 lsblk->nodeps = 1;
1855 break;
1856 case 'D':
1857 add_uniq_column(COL_NAME);
1858 add_uniq_column(COL_DALIGN);
1859 add_uniq_column(COL_DGRAN);
1860 add_uniq_column(COL_DMAX);
1861 add_uniq_column(COL_DZERO);
1862 break;
1863 case 'z':
1864 add_uniq_column(COL_NAME);
1865 add_uniq_column(COL_ZONED);
1866 break;
1867 case 'e':
1868 parse_excludes(optarg);
1869 break;
1870 case 'J':
1871 lsblk->flags |= LSBLK_JSON;
1872 break;
1873 case 'l':
1874 lsblk->flags &= ~LSBLK_TREE; /* disable the default */
1875 break;
1876 case 'M':
1877 lsblk->merge = 1;
1878 break;
1879 case 'n':
1880 lsblk->flags |= LSBLK_NOHEADINGS;
1881 break;
1882 case 'o':
1883 outarg = optarg;
1884 break;
1885 case 'O':
1886 for (ncolumns = 0 ; ncolumns < ARRAY_SIZE(infos); ncolumns++)
1887 columns[ncolumns] = ncolumns;
1888 break;
1889 case 'p':
1890 lsblk->paths = 1;
1891 break;
1892 case 'P':
1893 lsblk->flags |= LSBLK_EXPORT;
1894 lsblk->flags &= ~LSBLK_TREE; /* disable the default */
1895 break;
1896 case 'i':
1897 lsblk->flags |= LSBLK_ASCII;
1898 break;
1899 case 'I':
1900 parse_includes(optarg);
1901 break;
1902 case 'r':
1903 lsblk->flags &= ~LSBLK_TREE; /* disable the default */
1904 lsblk->flags |= LSBLK_RAW; /* enable raw */
1905 break;
1906 case 's':
1907 lsblk->inverse = 1;
1908 break;
1909 case 'f':
1910 add_uniq_column(COL_NAME);
1911 add_uniq_column(COL_FSTYPE);
1912 add_uniq_column(COL_LABEL);
1913 add_uniq_column(COL_UUID);
1914 add_uniq_column(COL_FSAVAIL);
1915 add_uniq_column(COL_FSUSEPERC);
1916 add_uniq_column(COL_TARGET);
1917 break;
1918 case 'm':
1919 add_uniq_column(COL_NAME);
1920 add_uniq_column(COL_SIZE);
1921 add_uniq_column(COL_OWNER);
1922 add_uniq_column(COL_GROUP);
1923 add_uniq_column(COL_MODE);
1924 break;
1925 case 't':
1926 add_uniq_column(COL_NAME);
1927 add_uniq_column(COL_ALIOFF);
1928 add_uniq_column(COL_MINIO);
1929 add_uniq_column(COL_OPTIO);
1930 add_uniq_column(COL_PHYSEC);
1931 add_uniq_column(COL_LOGSEC);
1932 add_uniq_column(COL_ROTA);
1933 add_uniq_column(COL_SCHED);
1934 add_uniq_column(COL_RQ_SIZE);
1935 add_uniq_column(COL_RA);
1936 add_uniq_column(COL_WSAME);
1937 break;
1938 case 'S':
1939 lsblk->nodeps = 1;
1940 lsblk->scsi = 1;
1941 add_uniq_column(COL_NAME);
1942 add_uniq_column(COL_HCTL);
1943 add_uniq_column(COL_TYPE);
1944 add_uniq_column(COL_VENDOR);
1945 add_uniq_column(COL_MODEL);
1946 add_uniq_column(COL_REV);
1947 add_uniq_column(COL_TRANSPORT);
1948 break;
1949 case 'T':
1950 force_tree = 1;
1951 if (optarg)
1952 lsblk->tree_id = column_name_to_id(optarg, strlen(optarg));
1953 break;
1954 case OPT_SYSROOT:
1955 lsblk->sysroot = optarg;
1956 break;
1957 case 'E':
1958 lsblk->dedup_id = column_name_to_id(optarg, strlen(optarg));
1959 if (lsblk->dedup_id >= 0)
1960 break;
1961 errtryhelp(EXIT_FAILURE);
1962 break;
1963 case 'x':
1964 lsblk->flags &= ~LSBLK_TREE; /* disable the default */
1965 lsblk->sort_id = column_name_to_id(optarg, strlen(optarg));
1966 if (lsblk->sort_id >= 0)
1967 break;
1968 errtryhelp(EXIT_FAILURE);
1969 break;
1970
1971 case 'h':
1972 usage();
1973 case 'V':
1974 print_version(EXIT_SUCCESS);
1975 default:
1976 errtryhelp(EXIT_FAILURE);
1977 }
1978 }
1979
1980 if (force_tree)
1981 lsblk->flags |= LSBLK_TREE;
1982
1983 check_sysdevblock();
1984
1985 if (!ncolumns) {
1986 add_column(COL_NAME);
1987 add_column(COL_MAJMIN);
1988 add_column(COL_RM);
1989 add_column(COL_SIZE);
1990 add_column(COL_RO);
1991 add_column(COL_TYPE);
1992 add_column(COL_TARGET);
1993 }
1994
1995 if (outarg && string_add_to_idarray(outarg, columns, ARRAY_SIZE(columns),
1996 &ncolumns, column_name_to_id) < 0)
1997 return EXIT_FAILURE;
1998
1999 if (lsblk->all_devices == 0 && nexcludes == 0 && nincludes == 0)
2000 excludes[nexcludes++] = 1; /* default: ignore RAM disks */
2001
2002 if (lsblk->sort_id < 0)
2003 /* Since Linux 4.8 we have sort devices by default, because
2004 * /sys is no more sorted */
2005 lsblk->sort_id = COL_MAJMIN;
2006
2007 /* For --inverse --list we still follow parent->child relation */
2008 if (lsblk->inverse && !(lsblk->flags & LSBLK_TREE))
2009 lsblk->force_tree_order = 1;
2010
2011 if (lsblk->sort_id >= 0 && column_id_to_number(lsblk->sort_id) < 0) {
2012 /* the sort column is not between output columns -- add as hidden */
2013 add_column(lsblk->sort_id);
2014 lsblk->sort_hidden = 1;
2015 }
2016
2017 if (lsblk->dedup_id >= 0 && column_id_to_number(lsblk->dedup_id) < 0) {
2018 /* the deduplication column is not between output columns -- add as hidden */
2019 add_column(lsblk->dedup_id);
2020 lsblk->dedup_hidden = 1;
2021 }
2022
2023 lsblk_mnt_init();
2024 scols_init_debug(0);
2025 ul_path_init_debug();
2026
2027 /*
2028 * initialize output columns
2029 */
2030 if (!(lsblk->table = scols_new_table()))
2031 errx(EXIT_FAILURE, _("failed to allocate output table"));
2032 scols_table_enable_raw(lsblk->table, !!(lsblk->flags & LSBLK_RAW));
2033 scols_table_enable_export(lsblk->table, !!(lsblk->flags & LSBLK_EXPORT));
2034 scols_table_enable_ascii(lsblk->table, !!(lsblk->flags & LSBLK_ASCII));
2035 scols_table_enable_json(lsblk->table, !!(lsblk->flags & LSBLK_JSON));
2036 scols_table_enable_noheadings(lsblk->table, !!(lsblk->flags & LSBLK_NOHEADINGS));
2037
2038 if (lsblk->flags & LSBLK_JSON)
2039 scols_table_set_name(lsblk->table, "blockdevices");
2040
2041 for (i = 0; i < ncolumns; i++) {
2042 struct colinfo *ci = get_column_info(i);
2043 struct libscols_column *cl;
2044 int id = get_column_id(i), fl = ci->flags;
2045
2046 if ((lsblk->flags & LSBLK_TREE)
2047 && has_tree_col == 0
2048 && id == lsblk->tree_id) {
2049 fl |= SCOLS_FL_TREE;
2050 fl &= ~SCOLS_FL_RIGHT;
2051 has_tree_col = 1;
2052 }
2053
2054 if (lsblk->sort_hidden && lsblk->sort_id == id)
2055 fl |= SCOLS_FL_HIDDEN;
2056 if (lsblk->dedup_hidden && lsblk->dedup_id == id)
2057 fl |= SCOLS_FL_HIDDEN;
2058
2059 if (force_tree
2060 && lsblk->flags & LSBLK_JSON
2061 && has_tree_col == 0
2062 && i + 1 == ncolumns)
2063 /* The "--tree --json" specified, but no column with
2064 * SCOLS_FL_TREE yet; force it for the last column
2065 */
2066 fl |= SCOLS_FL_TREE;
2067
2068 cl = scols_table_new_column(lsblk->table, ci->name, ci->whint, fl);
2069 if (!cl) {
2070 warn(_("failed to allocate output column"));
2071 goto leave;
2072 }
2073 if (!lsblk->sort_col && lsblk->sort_id == id) {
2074 lsblk->sort_col = cl;
2075 scols_column_set_cmpfunc(cl,
2076 ci->type == COLTYPE_NUM ? cmp_u64_cells :
2077 ci->type == COLTYPE_SIZE ? cmp_u64_cells :
2078 ci->type == COLTYPE_SORTNUM ? cmp_u64_cells : scols_cmpstr_cells,
2079 NULL);
2080 }
2081 if (lsblk->flags & LSBLK_JSON) {
2082 switch (ci->type) {
2083 case COLTYPE_SIZE:
2084 if (!lsblk->bytes)
2085 break;
2086 /* fallthrough */
2087 case COLTYPE_NUM:
2088 scols_column_set_json_type(cl, SCOLS_JSON_NUMBER);
2089 break;
2090 case COLTYPE_BOOL:
2091 scols_column_set_json_type(cl, SCOLS_JSON_BOOLEAN);
2092 break;
2093 default:
2094 scols_column_set_json_type(cl, SCOLS_JSON_STRING);
2095 break;
2096 }
2097 }
2098 }
2099
2100 tr = lsblk_new_devtree();
2101 if (!tr)
2102 err(EXIT_FAILURE, _("failed to allocate device tree"));
2103
2104 if (optind == argc) {
2105 int rc = lsblk->inverse ?
2106 process_all_devices_inverse(tr) :
2107 process_all_devices(tr);
2108
2109 status = rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
2110 } else {
2111 int cnt = 0, cnt_err = 0;
2112
2113 while (optind < argc) {
2114 if (process_one_device(tr, argv[optind++]) != 0)
2115 cnt_err++;
2116 cnt++;
2117 }
2118 status = cnt == 0 ? EXIT_FAILURE : /* nothing */
2119 cnt == cnt_err ? LSBLK_EXIT_ALLFAILED :/* all failed */
2120 cnt_err ? LSBLK_EXIT_SOMEOK : /* some ok */
2121 EXIT_SUCCESS; /* all success */
2122 }
2123
2124 if (lsblk->dedup_id > -1) {
2125 devtree_set_dedupkeys(tr, lsblk->dedup_id);
2126 lsblk_devtree_deduplicate_devices(tr);
2127 }
2128
2129 devtree_to_scols(tr, lsblk->table);
2130
2131 if (lsblk->sort_col)
2132 scols_sort_table(lsblk->table, lsblk->sort_col);
2133 if (lsblk->force_tree_order)
2134 scols_sort_table_by_tree(lsblk->table);
2135
2136 scols_print_table(lsblk->table);
2137
2138 leave:
2139 if (lsblk->sort_col)
2140 unref_sortdata(lsblk->table);
2141
2142 scols_unref_table(lsblk->table);
2143
2144 lsblk_mnt_deinit();
2145 lsblk_properties_deinit();
2146 lsblk_unref_devtree(tr);
2147
2148 return status;
2149 }