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