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