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