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