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