]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/lsblk.c
Merge branch 'libblkid/bcache-csum' of https://github.com/t-8ch/util-linux
[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 <gmazyland@gmail.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 * const 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 const 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 const 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 else if (strncmp(dev->name, "mmcblk", 6) == 0)
528 trans = "mmc";
529
530 return trans;
531 }
532
533 static char *get_subsystems(struct lsblk_device *dev)
534 {
535 char path[PATH_MAX];
536 char *sub, *chain, *res = NULL;
537 size_t len = 0, last = 0;
538
539 chain = sysfs_blkdev_get_devchain(dev->sysfs, path, sizeof(path));
540 if (!chain)
541 return NULL;
542
543 while (sysfs_blkdev_next_subsystem(dev->sysfs, chain, &sub) == 0) {
544 size_t sz;
545
546 /* don't create "block:scsi:scsi", but "block:scsi" */
547 if (len && strcmp(res + last, sub) == 0) {
548 free(sub);
549 continue;
550 }
551
552 sz = strlen(sub);
553 res = xrealloc(res, len + sz + 2);
554 if (len)
555 res[len++] = ':';
556
557 memcpy(res + len, sub, sz + 1);
558 last = len;
559 len += sz;
560 free(sub);
561 }
562
563 return res;
564 }
565
566
567 #define is_parsable(_l) (scols_table_is_raw((_l)->table) || \
568 scols_table_is_export((_l)->table) || \
569 scols_table_is_json((_l)->table))
570
571 static char *mk_name(const char *name)
572 {
573 char *p;
574 if (!name)
575 return NULL;
576 if (lsblk->paths)
577 xasprintf(&p, "/dev/%s", name);
578 else
579 p = xstrdup(name);
580 if (p)
581 sysfs_devname_sys_to_dev(p);
582 return p;
583 }
584
585 static char *mk_dm_name(const char *name)
586 {
587 char *p;
588 if (!name)
589 return NULL;
590 if (lsblk->paths)
591 xasprintf(&p, "/dev/mapper/%s", name);
592 else
593 p = xstrdup(name);
594 return p;
595 }
596
597 /* stores data to scols cell userdata (invisible and independent on output)
598 * to make the original values accessible for sort functions
599 */
600 static void set_sortdata_u64(struct libscols_line *ln, int col, uint64_t x)
601 {
602 struct libscols_cell *ce = scols_line_get_cell(ln, col);
603 uint64_t *data;
604
605 if (!ce)
606 return;
607 data = xmalloc(sizeof(uint64_t));
608 *data = x;
609 scols_cell_set_userdata(ce, data);
610 }
611
612 /* do not modify *data on any error */
613 static void str2u64(const char *str, uint64_t *data)
614 {
615 uintmax_t num;
616 char *end = NULL;
617
618 errno = 0;
619 if (str == NULL || *str == '\0')
620 return;
621 num = strtoumax(str, &end, 10);
622
623 if (errno || str == end || (end && *end))
624 return;
625 *data = num;
626 }
627
628 static void unref_sortdata(struct libscols_table *tb)
629 {
630 struct libscols_iter *itr;
631 struct libscols_line *ln;
632
633 if (!tb || !lsblk->sort_col)
634 return;
635 itr = scols_new_iter(SCOLS_ITER_FORWARD);
636 if (!itr)
637 return;
638 while (scols_table_next_line(tb, itr, &ln) == 0) {
639 struct libscols_cell *ce = scols_line_get_column_cell(ln,
640 lsblk->sort_col);
641 void *data = scols_cell_get_userdata(ce);
642 free(data);
643 }
644
645 scols_free_iter(itr);
646 }
647
648 static char *get_vfs_attribute(struct lsblk_device *dev, int id)
649 {
650 char *sizestr;
651 uint64_t vfs_attr = 0;
652
653 if (!dev->fsstat.f_blocks) {
654 const char *mnt = lsblk_device_get_mountpoint(dev);
655 if (!mnt || dev->is_swap)
656 return NULL;
657 if (statvfs(mnt, &dev->fsstat) != 0)
658 return NULL;
659 }
660
661 switch(id) {
662 case COL_FSSIZE:
663 vfs_attr = dev->fsstat.f_frsize * dev->fsstat.f_blocks;
664 break;
665 case COL_FSAVAIL:
666 vfs_attr = dev->fsstat.f_frsize * dev->fsstat.f_bavail;
667 break;
668 case COL_FSUSED:
669 vfs_attr = dev->fsstat.f_frsize * (dev->fsstat.f_blocks - dev->fsstat.f_bfree);
670 break;
671 case COL_FSUSEPERC:
672 if (dev->fsstat.f_blocks == 0)
673 return xstrdup("-");
674
675 xasprintf(&sizestr, "%.0f%%",
676 (double)(dev->fsstat.f_blocks - dev->fsstat.f_bfree) /
677 dev->fsstat.f_blocks * 100);
678 return sizestr;
679 }
680
681 if (!vfs_attr)
682 sizestr = xstrdup("0");
683 else if (lsblk->bytes)
684 xasprintf(&sizestr, "%ju", vfs_attr);
685 else
686 sizestr = size_to_human_string(SIZE_SUFFIX_1LETTER, vfs_attr);
687
688 return sizestr;
689 }
690
691 static struct stat *device_get_stat(struct lsblk_device *dev)
692 {
693 if (!dev->st.st_rdev
694 && stat(dev->filename, &dev->st) != 0)
695 return NULL;
696
697 return &dev->st;
698 }
699
700 static int is_removable_device(struct lsblk_device *dev, struct lsblk_device *parent)
701 {
702 struct path_cxt *pc;
703
704 if (dev->removable != -1)
705 goto done;
706
707 dev->removable = sysfs_blkdev_is_removable(dev->sysfs);
708
709 if (!dev->removable && parent) {
710 pc = sysfs_blkdev_get_parent(dev->sysfs);
711 if (!pc)
712 goto done;
713
714 if (pc == parent->sysfs)
715 /* dev is partition and parent is whole-disk */
716 dev->removable = is_removable_device(parent, NULL);
717 else
718 /* parent is something else, use sysfs parent */
719 dev->removable = sysfs_blkdev_is_removable(pc);
720 }
721 done:
722 if (dev->removable == -1)
723 dev->removable = 0;
724 return dev->removable;
725 }
726
727 static uint64_t device_get_discard_granularity(struct lsblk_device *dev)
728 {
729 if (dev->discard_granularity == (uint64_t) -1
730 && ul_path_read_u64(dev->sysfs, &dev->discard_granularity,
731 "queue/discard_granularity") != 0)
732 dev->discard_granularity = 0;
733
734 return dev->discard_granularity;
735 }
736
737 static void device_read_bytes(struct lsblk_device *dev, char *path, char **str,
738 uint64_t *sortdata)
739 {
740 uint64_t x;
741
742 if (lsblk->bytes) {
743 ul_path_read_string(dev->sysfs, str, path);
744 if (sortdata)
745 str2u64(*str, sortdata);
746 return;
747 }
748
749 if (ul_path_read_u64(dev->sysfs, &x, path) == 0) {
750 *str = size_to_human_string(SIZE_SUFFIX_1LETTER, x);
751 if (sortdata)
752 *sortdata = x;
753 }
754 }
755
756 static void process_mq(struct lsblk_device *dev, char **str)
757 {
758 unsigned int queues = 0;
759
760 DBG(DEV, ul_debugobj(dev, "%s: process mq", dev->name));
761
762 queues = ul_path_count_dirents(dev->sysfs, "mq");
763 if (!queues) {
764 *str = xstrdup("1");
765 DBG(DEV, ul_debugobj(dev, "%s: no mq supported, use a single queue", dev->name));
766 return;
767 }
768
769 DBG(DEV, ul_debugobj(dev, "%s: has %d queues", dev->name, queues));
770 xasprintf(str, "%3u", queues);
771 }
772
773 /*
774 * Generates data (string) for column specified by column ID for specified device. If sortdata
775 * is not NULL then returns number usable to sort the column if the data are available for the
776 * column.
777 */
778 static char *device_get_data(
779 struct lsblk_device *dev, /* device */
780 struct lsblk_device *parent, /* device parent as defined in the tree */
781 int id, /* column ID (COL_*) */
782 uint64_t *sortdata) /* returns sort data as number */
783 {
784 struct lsblk_devprop *prop = NULL;
785 char *str = NULL;
786
787 switch(id) {
788 case COL_NAME:
789 str = dev->dm_name ? mk_dm_name(dev->dm_name) : mk_name(dev->name);
790 break;
791 case COL_KNAME:
792 str = mk_name(dev->name);
793 break;
794 case COL_PKNAME:
795 if (parent)
796 str = mk_name(parent->name);
797 break;
798 case COL_PATH:
799 if (dev->filename)
800 str = xstrdup(dev->filename);
801 break;
802 case COL_OWNER:
803 if (lsblk->sysroot)
804 prop = lsblk_device_get_properties(dev);
805 if (prop && prop->owner) {
806 str = xstrdup(prop->owner);
807 } else {
808 struct stat *st = device_get_stat(dev);
809 struct passwd *pw = st ? getpwuid(st->st_uid) : NULL;
810 if (pw)
811 str = xstrdup(pw->pw_name);
812 }
813 break;
814 case COL_GROUP:
815 if (lsblk->sysroot)
816 prop = lsblk_device_get_properties(dev);
817 if (prop && prop->group) {
818 str = xstrdup(prop->group);
819 } else {
820 struct stat *st = device_get_stat(dev);
821 struct group *gr = st ? getgrgid(st->st_gid) : NULL;
822 if (gr)
823 str = xstrdup(gr->gr_name);
824 }
825 break;
826 case COL_MODE:
827 if (lsblk->sysroot)
828 prop = lsblk_device_get_properties(dev);
829 if (prop && prop->mode) {
830 str = xstrdup(prop->mode);
831 } else {
832 struct stat *st = device_get_stat(dev);
833 char md[11] = { '\0' };
834
835 if (st)
836 str = xstrdup(xstrmode(st->st_mode, md));
837 }
838 break;
839 case COL_MAJMIN:
840 if (is_parsable(lsblk))
841 xasprintf(&str, "%u:%u", dev->maj, dev->min);
842 else
843 xasprintf(&str, "%3u:%-3u", dev->maj, dev->min);
844 if (sortdata)
845 *sortdata = makedev(dev->maj, dev->min);
846 break;
847 case COL_FSTYPE:
848 prop = lsblk_device_get_properties(dev);
849 if (prop && prop->fstype)
850 str = xstrdup(prop->fstype);
851 break;
852 case COL_FSSIZE:
853 case COL_FSAVAIL:
854 case COL_FSUSED:
855 case COL_FSUSEPERC:
856 str = get_vfs_attribute(dev, id);
857 break;
858 case COL_FSVERSION:
859 prop = lsblk_device_get_properties(dev);
860 if (prop && prop->fsversion)
861 str = xstrdup(prop->fsversion);
862 break;
863 case COL_TARGET:
864 {
865 const char *p = lsblk_device_get_mountpoint(dev);
866 if (p)
867 str = xstrdup(p);
868 break;
869 }
870 case COL_TARGETS:
871 {
872 size_t i, n = 0;
873 struct ul_buffer buf = UL_INIT_BUFFER;
874 struct libmnt_fs **fss = lsblk_device_get_filesystems(dev, &n);
875
876 for (i = 0; i < n; i++) {
877 struct libmnt_fs *fs = fss[i];
878 if (mnt_fs_is_swaparea(fs))
879 ul_buffer_append_string(&buf, "[SWAP]");
880 else
881 ul_buffer_append_string(&buf, mnt_fs_get_target(fs));
882 if (i + 1 < n)
883 ul_buffer_append_data(&buf, "\n", 1);
884 }
885 str = ul_buffer_get_data(&buf, NULL, NULL);
886 break;
887 }
888 case COL_FSROOTS:
889 {
890 size_t i, n = 0;
891 struct ul_buffer buf = UL_INIT_BUFFER;
892 struct libmnt_fs **fss = lsblk_device_get_filesystems(dev, &n);
893
894 for (i = 0; i < n; i++) {
895 struct libmnt_fs *fs = fss[i];
896 const char *root = mnt_fs_get_root(fs);
897 if (mnt_fs_is_swaparea(fs))
898 continue;
899 ul_buffer_append_string(&buf, root ? root : "/");
900 if (i + 1 < n)
901 ul_buffer_append_data(&buf, "\n", 1);
902 }
903 str = ul_buffer_get_data(&buf, NULL, NULL);
904 break;
905 }
906 case COL_LABEL:
907 prop = lsblk_device_get_properties(dev);
908 if (prop && prop->label)
909 str = xstrdup(prop->label);
910 break;
911 case COL_UUID:
912 prop = lsblk_device_get_properties(dev);
913 if (prop && prop->uuid)
914 str = xstrdup(prop->uuid);
915 break;
916 case COL_PTUUID:
917 prop = lsblk_device_get_properties(dev);
918 if (prop && prop->ptuuid)
919 str = xstrdup(prop->ptuuid);
920 break;
921 case COL_PTTYPE:
922 prop = lsblk_device_get_properties(dev);
923 if (prop && prop->pttype)
924 str = xstrdup(prop->pttype);
925 break;
926 case COL_PARTTYPE:
927 prop = lsblk_device_get_properties(dev);
928 if (prop && prop->parttype)
929 str = xstrdup(prop->parttype);
930 break;
931 case COL_PARTTYPENAME:
932 prop = lsblk_device_get_properties(dev);
933 if (prop && prop->parttype && prop->pttype) {
934 const char *x = lsblk_parttype_code_to_string(
935 prop->parttype, prop->pttype);
936 if (x)
937 str = xstrdup(x);
938 }
939 break;
940 case COL_PARTLABEL:
941 prop = lsblk_device_get_properties(dev);
942 if (prop && prop->partlabel)
943 str = xstrdup(prop->partlabel);
944 break;
945 case COL_PARTUUID:
946 prop = lsblk_device_get_properties(dev);
947 if (prop && prop->partuuid)
948 str = xstrdup(prop->partuuid);
949 break;
950 case COL_PARTFLAGS:
951 prop = lsblk_device_get_properties(dev);
952 if (prop && prop->partflags)
953 str = xstrdup(prop->partflags);
954 break;
955 case COL_PARTN:
956 prop = lsblk_device_get_properties(dev);
957 if (prop && prop->partn)
958 str = xstrdup(prop->partn);
959 break;
960 case COL_WWN:
961 prop = lsblk_device_get_properties(dev);
962 if (prop && prop->wwn)
963 str = xstrdup(prop->wwn);
964 break;
965 case COL_IDLINK:
966 prop = lsblk_device_get_properties(dev);
967 if (prop && prop->idlink)
968 str = xstrdup(prop->idlink);
969 break;
970 case COL_ID:
971 prop = lsblk_device_get_properties(dev);
972 if (prop && prop->idlink) {
973 /* skip bus/subsystem prefix */
974 const char *p = strchr(prop->idlink, '-');
975 str = p && *(p + 1) ? xstrdup(p+1) : xstrdup(prop->idlink);
976 }
977 break;
978 case COL_RA:
979 ul_path_read_string(dev->sysfs, &str, "queue/read_ahead_kb");
980 if (sortdata)
981 str2u64(str, sortdata);
982 break;
983 case COL_RO:
984 str = xstrdup(is_readonly_device(dev) ? "1" : "0");
985 break;
986 case COL_RM:
987 str = xstrdup(is_removable_device(dev, parent) ? "1" : "0");
988 break;
989 case COL_HOTPLUG:
990 str = sysfs_blkdev_is_hotpluggable(dev->sysfs) ? xstrdup("1") : xstrdup("0");
991 break;
992 case COL_ROTA:
993 ul_path_read_string(dev->sysfs, &str, "queue/rotational");
994 break;
995 case COL_RAND:
996 ul_path_read_string(dev->sysfs, &str, "queue/add_random");
997 break;
998 case COL_MODEL:
999 if (!device_is_partition(dev) && dev->nslaves == 0) {
1000 prop = lsblk_device_get_properties(dev);
1001 if (prop && prop->model)
1002 str = xstrdup(prop->model);
1003 else
1004 ul_path_read_string(dev->sysfs, &str, "device/model");
1005 }
1006 break;
1007 case COL_SERIAL:
1008 if (!device_is_partition(dev) && dev->nslaves == 0) {
1009 prop = lsblk_device_get_properties(dev);
1010 if (prop && prop->serial)
1011 str = xstrdup(prop->serial);
1012 else
1013 ul_path_read_string(dev->sysfs, &str, "device/serial");
1014 }
1015 break;
1016 case COL_REV:
1017 if (!device_is_partition(dev) && dev->nslaves == 0) {
1018 prop = lsblk_device_get_properties(dev);
1019 if (prop && prop->revision)
1020 str = xstrdup(prop->revision);
1021 else
1022 ul_path_read_string(dev->sysfs, &str, "device/rev");
1023 }
1024 break;
1025 case COL_VENDOR:
1026 if (!device_is_partition(dev) && dev->nslaves == 0)
1027 ul_path_read_string(dev->sysfs, &str, "device/vendor");
1028 break;
1029 case COL_SIZE:
1030 if (lsblk->bytes)
1031 xasprintf(&str, "%ju", dev->size);
1032 else
1033 str = size_to_human_string(SIZE_SUFFIX_1LETTER, dev->size);
1034 if (sortdata)
1035 *sortdata = dev->size;
1036 break;
1037 case COL_START:
1038 ul_path_read_string(dev->sysfs, &str, "start");
1039 if (sortdata)
1040 str2u64(str, sortdata);
1041 break;
1042 case COL_STATE:
1043 if (!device_is_partition(dev) && !dev->dm_name)
1044 ul_path_read_string(dev->sysfs, &str, "device/state");
1045 else if (dev->dm_name) {
1046 int x = 0;
1047 if (ul_path_read_s32(dev->sysfs, &x, "dm/suspended") == 0)
1048 str = xstrdup(x ? "suspended" : "running");
1049 }
1050 break;
1051 case COL_ALIOFF:
1052 ul_path_read_string(dev->sysfs, &str, "alignment_offset");
1053 if (sortdata)
1054 str2u64(str, sortdata);
1055 break;
1056 case COL_MINIO:
1057 ul_path_read_string(dev->sysfs, &str, "queue/minimum_io_size");
1058 if (sortdata)
1059 str2u64(str, sortdata);
1060 break;
1061 case COL_OPTIO:
1062 ul_path_read_string(dev->sysfs, &str, "queue/optimal_io_size");
1063 if (sortdata)
1064 str2u64(str, sortdata);
1065 break;
1066 case COL_PHYSEC:
1067 ul_path_read_string(dev->sysfs, &str, "queue/physical_block_size");
1068 if (sortdata)
1069 str2u64(str, sortdata);
1070 break;
1071 case COL_LOGSEC:
1072 ul_path_read_string(dev->sysfs, &str, "queue/logical_block_size");
1073 if (sortdata)
1074 str2u64(str, sortdata);
1075 break;
1076 case COL_SCHED:
1077 str = get_scheduler(dev);
1078 break;
1079 case COL_RQ_SIZE:
1080 ul_path_read_string(dev->sysfs, &str, "queue/nr_requests");
1081 if (sortdata)
1082 str2u64(str, sortdata);
1083 break;
1084 case COL_TYPE:
1085 str = get_type(dev);
1086 break;
1087 case COL_HCTL:
1088 {
1089 int h, c, t, l;
1090 if (sysfs_blkdev_scsi_get_hctl(dev->sysfs, &h, &c, &t, &l) == 0)
1091 xasprintf(&str, "%d:%d:%d:%d", h, c, t, l);
1092 break;
1093 }
1094 case COL_TRANSPORT:
1095 {
1096 const char *trans = get_transport(dev);
1097 if (trans)
1098 str = xstrdup(trans);
1099 break;
1100 }
1101 case COL_SUBSYS:
1102 str = get_subsystems(dev);
1103 break;
1104 case COL_DALIGN:
1105 if (device_get_discard_granularity(dev) > 0)
1106 ul_path_read_string(dev->sysfs, &str, "discard_alignment");
1107 if (!str)
1108 str = xstrdup("0");
1109 if (sortdata)
1110 str2u64(str, sortdata);
1111 break;
1112 case COL_DGRAN:
1113 if (lsblk->bytes) {
1114 ul_path_read_string(dev->sysfs, &str, "queue/discard_granularity");
1115 if (sortdata)
1116 str2u64(str, sortdata);
1117 } else {
1118 uint64_t x = device_get_discard_granularity(dev);
1119 str = size_to_human_string(SIZE_SUFFIX_1LETTER, x);
1120 if (sortdata)
1121 *sortdata = x;
1122 }
1123 break;
1124 case COL_DMAX:
1125 device_read_bytes(dev, "queue/discard_max_bytes", &str, sortdata);
1126 break;
1127 case COL_DZERO:
1128 if (device_get_discard_granularity(dev) > 0)
1129 ul_path_read_string(dev->sysfs, &str, "queue/discard_zeroes_data");
1130 if (!str)
1131 str = xstrdup("0");
1132 break;
1133 case COL_WSAME:
1134 device_read_bytes(dev, "queue/write_same_max_bytes", &str, sortdata);
1135 if (!str)
1136 str = xstrdup("0");
1137 break;
1138 case COL_ZONED:
1139 ul_path_read_string(dev->sysfs, &str, "queue/zoned");
1140 break;
1141 case COL_ZONE_SZ:
1142 {
1143 uint64_t x;
1144
1145 if (ul_path_read_u64(dev->sysfs, &x, "queue/chunk_sectors") == 0) {
1146 x <<= 9;
1147 if (lsblk->bytes)
1148 xasprintf(&str, "%ju", x);
1149 else
1150 str = size_to_human_string(SIZE_SUFFIX_1LETTER, x);
1151 if (sortdata)
1152 *sortdata = x;
1153 }
1154 break;
1155 }
1156 case COL_ZONE_WGRAN:
1157 device_read_bytes(dev, "queue/zone_write_granularity", &str, sortdata);
1158 break;
1159 case COL_ZONE_APP:
1160 device_read_bytes(dev, "queue/zone_append_max_bytes", &str, sortdata);
1161 break;
1162 case COL_ZONE_NR:
1163 ul_path_read_string(dev->sysfs, &str, "queue/nr_zones");
1164 if (sortdata)
1165 str2u64(str, sortdata);
1166 break;
1167 case COL_ZONE_OMAX:
1168 ul_path_read_string(dev->sysfs, &str, "queue/max_open_zones");
1169 if (!str)
1170 str = xstrdup("0");
1171 if (sortdata)
1172 str2u64(str, sortdata);
1173 break;
1174 case COL_ZONE_AMAX:
1175 ul_path_read_string(dev->sysfs, &str, "queue/max_active_zones");
1176 if (!str)
1177 str = xstrdup("0");
1178 if (sortdata)
1179 str2u64(str, sortdata);
1180 break;
1181 case COL_DAX:
1182 ul_path_read_string(dev->sysfs, &str, "queue/dax");
1183 break;
1184 case COL_MQ:
1185 process_mq(dev, &str);
1186 break;
1187 case COL_DISKSEQ:
1188 ul_path_read_string(dev->sysfs, &str, "diskseq");
1189 if (sortdata)
1190 str2u64(str, sortdata);
1191 break;
1192 };
1193
1194 return str;
1195 }
1196
1197 /*
1198 * Adds data for all wanted columns about the device to the smartcols table
1199 */
1200 static void device_to_scols(
1201 struct lsblk_device *dev,
1202 struct lsblk_device *parent,
1203 struct libscols_table *tab,
1204 struct libscols_line *parent_line)
1205 {
1206 size_t i;
1207 struct libscols_line *ln;
1208 struct lsblk_iter itr;
1209 struct lsblk_device *child = NULL;
1210 int link_group = 0;
1211
1212
1213 DBG(DEV, ul_debugobj(dev, "add '%s' to scols", dev->name));
1214 ON_DBG(DEV, if (ul_path_isopen_dirfd(dev->sysfs)) ul_debugobj(dev, " %s ---> is open!", dev->name));
1215
1216 if (!parent && dev->wholedisk)
1217 parent = dev->wholedisk;
1218
1219 /* Do not print device more than once on --list if tree order is not requested */
1220 if (!(lsblk->flags & LSBLK_TREE) && !lsblk->force_tree_order && dev->is_printed)
1221 return;
1222
1223 if (lsblk->merge && list_count_entries(&dev->parents) > 1) {
1224 if (!lsblk_device_is_last_parent(dev, parent))
1225 return;
1226 link_group = 1;
1227 }
1228
1229 ln = scols_table_new_line(tab, link_group ? NULL : parent_line);
1230 if (!ln)
1231 err(EXIT_FAILURE, _("failed to allocate output line"));
1232
1233 dev->is_printed = 1;
1234
1235 if (link_group) {
1236 struct lsblk_device *p;
1237 struct libscols_line *gr = parent_line;
1238
1239 /* Merge all my parents to the one group */
1240 DBG(DEV, ul_debugobj(dev, " grouping parents [--merge]"));
1241 lsblk_reset_iter(&itr, LSBLK_ITER_FORWARD);
1242 while (lsblk_device_next_parent(dev, &itr, &p) == 0) {
1243 if (!p->scols_line) {
1244 DBG(DEV, ul_debugobj(dev, " *** ignore '%s' no scols line yet", p->name));
1245 continue;
1246 }
1247 DBG(DEV, ul_debugobj(dev, " group '%s'", p->name));
1248 scols_table_group_lines(tab, p->scols_line, gr, 0);
1249 }
1250
1251 /* Link the group -- this makes group->child connection */
1252 DBG(DEV, ul_debugobj(dev, " linking the group [--merge]"));
1253 scols_line_link_group(ln, gr, 0);
1254 }
1255
1256 /* read column specific data and set it to smartcols table line */
1257 for (i = 0; i < ncolumns; i++) {
1258 char *data;
1259 int id = get_column_id(i);
1260
1261 if (lsblk->sort_id != id)
1262 data = device_get_data(dev, parent, id, NULL);
1263 else {
1264 uint64_t sortdata = (uint64_t) -1;
1265
1266 data = device_get_data(dev, parent, id, &sortdata);
1267 if (data && sortdata != (uint64_t) -1)
1268 set_sortdata_u64(ln, i, sortdata);
1269 }
1270 DBG(DEV, ul_debugobj(dev, " refer data[%zu]=\"%s\"", i, data));
1271 if (data && scols_line_refer_data(ln, i, data))
1272 err(EXIT_FAILURE, _("failed to add output data"));
1273 }
1274
1275 dev->scols_line = ln;
1276
1277 if (dev->npartitions == 0)
1278 /* For partitions we often read from parental whole-disk sysfs,
1279 * otherwise we can close */
1280 ul_path_close_dirfd(dev->sysfs);
1281
1282 lsblk_reset_iter(&itr, LSBLK_ITER_FORWARD);
1283 while (lsblk_device_next_child(dev, &itr, &child) == 0) {
1284 DBG(DEV, ul_debugobj(dev, "%s -> continue to child", dev->name));
1285 device_to_scols(child, dev, tab, ln);
1286 DBG(DEV, ul_debugobj(dev, "%s <- child done", dev->name));
1287 }
1288
1289 /* Let's be careful with number of open files */
1290 ul_path_close_dirfd(dev->sysfs);
1291 }
1292
1293 /*
1294 * Walks on tree and adds one line for each device to the smartcols table
1295 */
1296 static void devtree_to_scols(struct lsblk_devtree *tr, struct libscols_table *tab)
1297 {
1298 struct lsblk_iter itr;
1299 struct lsblk_device *dev = NULL;
1300
1301 lsblk_reset_iter(&itr, LSBLK_ITER_FORWARD);
1302
1303 while (lsblk_devtree_next_root(tr, &itr, &dev) == 0)
1304 device_to_scols(dev, NULL, tab, NULL);
1305 }
1306
1307 static int ignore_empty(struct lsblk_device *dev)
1308 {
1309 /* show all non-empty devices */
1310 if (dev->size)
1311 return 0;
1312
1313 if (lsblk->noempty && dev->size == 0)
1314 return 1;
1315
1316 /* ignore empty loop devices without backing file */
1317 if (dev->maj == LOOPDEV_MAJOR &&
1318 !loopdev_has_backing_file(dev->filename))
1319 return 1;
1320
1321 return 0;
1322 }
1323
1324 /*
1325 * Reads very basic information about the device from sysfs into the device struct
1326 */
1327 static int initialize_device(struct lsblk_device *dev,
1328 struct lsblk_device *wholedisk,
1329 const char *name)
1330 {
1331 dev_t devno;
1332
1333 DBG(DEV, ul_debugobj(dev, "initialize %s [wholedisk=%p %s]",
1334 name, wholedisk, wholedisk ? wholedisk->name : ""));
1335
1336 if (sysfs_devname_is_hidden(lsblk->sysroot, name)) {
1337 DBG(DEV, ul_debugobj(dev, "%s: hidden, ignore", name));
1338 return -1;
1339 }
1340
1341 dev->name = xstrdup(name);
1342
1343 if (wholedisk) {
1344 dev->wholedisk = wholedisk;
1345 lsblk_ref_device(wholedisk);
1346 }
1347
1348 dev->filename = get_device_path(dev);
1349 if (!dev->filename) {
1350 DBG(DEV, ul_debugobj(dev, "%s: failed to get device path", dev->name));
1351 return -1;
1352 }
1353 DBG(DEV, ul_debugobj(dev, "%s: filename=%s", dev->name, dev->filename));
1354
1355 devno = __sysfs_devname_to_devno(lsblk->sysroot, dev->name, wholedisk ? wholedisk->name : NULL);
1356 if (!devno) {
1357 DBG(DEV, ul_debugobj(dev, "%s: unknown device name", dev->name));
1358 return -1;
1359 }
1360
1361 dev->sysfs = ul_new_sysfs_path(devno, wholedisk ? wholedisk->sysfs : NULL, lsblk->sysroot);
1362 if (!dev->sysfs) {
1363 DBG(DEV, ul_debugobj(dev, "%s: failed to initialize sysfs handler", dev->name));
1364 return -1;
1365 }
1366
1367 dev->maj = major(devno);
1368 dev->min = minor(devno);
1369 dev->size = 0;
1370
1371 if (ul_path_read_u64(dev->sysfs, &dev->size, "size") == 0) /* in sectors */
1372 dev->size <<= 9; /* in bytes */
1373
1374 /* Ignore devices of zero size */
1375 if (!lsblk->all_devices && ignore_empty(dev)) {
1376 DBG(DEV, ul_debugobj(dev, "zero size device -- ignore"));
1377 return -1;
1378 }
1379 if (is_dm(dev->name)) {
1380 ul_path_read_string(dev->sysfs, &dev->dm_name, "dm/name");
1381 if (!dev->dm_name) {
1382 DBG(DEV, ul_debugobj(dev, "%s: failed to get dm name", dev->name));
1383 return -1;
1384 }
1385 }
1386
1387 dev->npartitions = sysfs_blkdev_count_partitions(dev->sysfs, dev->name);
1388 dev->nholders = ul_path_count_dirents(dev->sysfs, "holders");
1389 dev->nslaves = ul_path_count_dirents(dev->sysfs, "slaves");
1390
1391 DBG(DEV, ul_debugobj(dev, "%s: npartitions=%d, nholders=%d, nslaves=%d",
1392 dev->name, dev->npartitions, dev->nholders, dev->nslaves));
1393
1394 /* ignore non-SCSI devices */
1395 if (lsblk->scsi && sysfs_blkdev_scsi_get_hctl(dev->sysfs, NULL, NULL, NULL, NULL)) {
1396 DBG(DEV, ul_debugobj(dev, "non-scsi device -- ignore"));
1397 return -1;
1398 }
1399
1400 /* ignore non-NVMe devices */
1401 if (lsblk->nvme) {
1402 const char *transport = get_transport(dev);
1403
1404 if (!transport || strcmp(transport, "nvme")) {
1405 DBG(DEV, ul_debugobj(dev, "non-nvme device -- ignore"));
1406 return -1;
1407 }
1408 }
1409
1410 /* ignore non-virtio devices */
1411 if (lsblk->virtio) {
1412 const char *transport = get_transport(dev);
1413
1414 if (!transport || strcmp(transport, "virtio")) {
1415 DBG(DEV, ul_debugobj(dev, "non-virtio device -- ignore"));
1416 return -1;
1417 }
1418 }
1419
1420 DBG(DEV, ul_debugobj(dev, "%s: context successfully initialized", dev->name));
1421 return 0;
1422 }
1423
1424 static struct lsblk_device *devtree_get_device_or_new(struct lsblk_devtree *tr,
1425 struct lsblk_device *disk,
1426 const char *name)
1427 {
1428 struct lsblk_device *dev = lsblk_devtree_get_device(tr, name);
1429
1430 if (!dev) {
1431 dev = lsblk_new_device();
1432 if (!dev)
1433 err(EXIT_FAILURE, _("failed to allocate device"));
1434
1435 if (initialize_device(dev, disk, name) != 0) {
1436 lsblk_unref_device(dev);
1437 return NULL;
1438 }
1439 lsblk_devtree_add_device(tr, dev);
1440 lsblk_unref_device(dev); /* keep it referenced by devtree only */
1441 } else
1442 DBG(DEV, ul_debugobj(dev, "%s: already processed", name));
1443
1444 return dev;
1445 }
1446
1447 static struct lsblk_device *devtree_pktcdvd_get_dep(
1448 struct lsblk_devtree *tr,
1449 struct lsblk_device *dev,
1450 int want_slave)
1451 {
1452 char buf[PATH_MAX], *name;
1453 dev_t devno;
1454
1455 devno = lsblk_devtree_pktcdvd_get_mate(tr,
1456 makedev(dev->maj, dev->min), !want_slave);
1457 if (!devno)
1458 return NULL;
1459
1460 name = sysfs_devno_to_devname(devno, buf, sizeof(buf));
1461 if (!name)
1462 return NULL;
1463
1464 return devtree_get_device_or_new(tr, NULL, name);
1465 }
1466
1467 static int process_dependencies(
1468 struct lsblk_devtree *tr,
1469 struct lsblk_device *dev,
1470 int do_partitions);
1471
1472 /*
1473 * Read devices from whole-disk device into tree
1474 */
1475 static int process_partitions(struct lsblk_devtree *tr, struct lsblk_device *disk)
1476 {
1477 DIR *dir;
1478 struct dirent *d;
1479
1480 assert(disk);
1481
1482 /*
1483 * Do not process further if there are no partitions for
1484 * this device or the device itself is a partition.
1485 */
1486 if (!disk->npartitions || device_is_partition(disk))
1487 return -EINVAL;
1488
1489 DBG(DEV, ul_debugobj(disk, "%s: probe whole-disk for partitions", disk->name));
1490
1491 dir = ul_path_opendir(disk->sysfs, NULL);
1492 if (!dir)
1493 err(EXIT_FAILURE, _("failed to open device directory in sysfs"));
1494
1495 while ((d = xreaddir(dir))) {
1496 struct lsblk_device *part;
1497
1498 if (!(sysfs_blkdev_is_partition_dirent(dir, d, disk->name)))
1499 continue;
1500
1501 DBG(DEV, ul_debugobj(disk, " checking %s", d->d_name));
1502
1503 part = devtree_get_device_or_new(tr, disk, d->d_name);
1504 if (!part)
1505 continue;
1506
1507 if (lsblk_device_new_dependence(disk, part) == 0)
1508 process_dependencies(tr, part, 0);
1509
1510 ul_path_close_dirfd(part->sysfs);
1511 }
1512
1513 /* For partitions we need parental (whole-disk) sysfs directory pretty
1514 * often, so close it now when all is done */
1515 ul_path_close_dirfd(disk->sysfs);
1516
1517 DBG(DEV, ul_debugobj(disk, "probe whole-disk for partitions -- done"));
1518 closedir(dir);
1519 return 0;
1520 }
1521
1522 static char *get_wholedisk_from_partition_dirent(DIR *dir, struct dirent *d, char *buf, size_t bufsz)
1523 {
1524 char *p;
1525 int len;
1526
1527 if ((len = readlinkat(dirfd(dir), d->d_name, buf, bufsz - 1)) < 0)
1528 return 0;
1529
1530 buf[len] = '\0';
1531
1532 /* The path ends with ".../<device>/<partition>" */
1533 p = strrchr(buf, '/');
1534 if (!p)
1535 return NULL;
1536 *p = '\0';
1537
1538 p = strrchr(buf, '/');
1539 if (!p)
1540 return NULL;
1541 p++;
1542
1543 return p;
1544 }
1545
1546 /*
1547 * Reads slaves/holders and partitions for specified device into device tree
1548 */
1549 static int process_dependencies(
1550 struct lsblk_devtree *tr,
1551 struct lsblk_device *dev,
1552 int do_partitions)
1553 {
1554 DIR *dir;
1555 struct dirent *d;
1556 const char *depname;
1557 struct lsblk_device *dep = NULL;
1558
1559 assert(dev);
1560
1561 if (lsblk->nodeps)
1562 return 0;
1563
1564 /* read all or specified partition */
1565 if (do_partitions && dev->npartitions)
1566 process_partitions(tr, dev);
1567
1568 DBG(DEV, ul_debugobj(dev, "%s: reading dependencies", dev->name));
1569
1570 if (!(lsblk->inverse ? dev->nslaves : dev->nholders)) {
1571 DBG(DEV, ul_debugobj(dev, " ignore (no slaves/holders)"));
1572 goto done;
1573 }
1574
1575 depname = lsblk->inverse ? "slaves" : "holders";
1576 dir = ul_path_opendir(dev->sysfs, depname);
1577 if (!dir) {
1578 DBG(DEV, ul_debugobj(dev, " ignore (no slaves/holders directory)"));
1579 goto done;
1580 }
1581 ul_path_close_dirfd(dev->sysfs);
1582
1583 DBG(DEV, ul_debugobj(dev, " %s: checking for '%s' dependence", dev->name, depname));
1584
1585 while ((d = xreaddir(dir))) {
1586 struct lsblk_device *disk = NULL;
1587
1588 /* Is the dependency a partition? */
1589 if (sysfs_blkdev_is_partition_dirent(dir, d, NULL)) {
1590
1591 char buf[PATH_MAX];
1592 char *diskname;
1593
1594 DBG(DEV, ul_debugobj(dev, " %s: dependence is partition", d->d_name));
1595
1596 diskname = get_wholedisk_from_partition_dirent(dir, d, buf, sizeof(buf));
1597 if (diskname)
1598 disk = devtree_get_device_or_new(tr, NULL, diskname);
1599 if (!disk) {
1600 DBG(DEV, ul_debugobj(dev, " ignore no wholedisk ???"));
1601 goto next;
1602 }
1603
1604 dep = devtree_get_device_or_new(tr, disk, d->d_name);
1605 if (!dep)
1606 goto next;
1607
1608 if (lsblk_device_new_dependence(dev, dep) == 0)
1609 process_dependencies(tr, dep, 1);
1610
1611 if (lsblk->inverse
1612 && lsblk_device_new_dependence(dep, disk) == 0)
1613 process_dependencies(tr, disk, 0);
1614 }
1615 /* The dependency is a whole device. */
1616 else {
1617 DBG(DEV, ul_debugobj(dev, " %s: %s: dependence is whole-disk",
1618 dev->name, d->d_name));
1619
1620 dep = devtree_get_device_or_new(tr, NULL, d->d_name);
1621 if (!dep)
1622 goto next;
1623
1624 if (lsblk_device_new_dependence(dev, dep) == 0)
1625 /* For inverse tree we don't want to show partitions
1626 * if the dependence is on whole-disk */
1627 process_dependencies(tr, dep, lsblk->inverse ? 0 : 1);
1628 }
1629 next:
1630 if (dep && dep->sysfs)
1631 ul_path_close_dirfd(dep->sysfs);
1632 if (disk && disk->sysfs)
1633 ul_path_close_dirfd(disk->sysfs);
1634 }
1635 closedir(dir);
1636 done:
1637 dep = devtree_pktcdvd_get_dep(tr, dev, lsblk->inverse);
1638
1639 if (dep && lsblk_device_new_dependence(dev, dep) == 0) {
1640 lsblk_devtree_remove_root(tr, dep);
1641 process_dependencies(tr, dep, lsblk->inverse ? 0 : 1);
1642 }
1643
1644 return 0;
1645 }
1646
1647 /*
1648 * Defines the device as root node in the device tree and walks on all dependencies of the device.
1649 */
1650 static int __process_one_device(struct lsblk_devtree *tr, char *devname, dev_t devno)
1651 {
1652 struct lsblk_device *dev = NULL;
1653 struct lsblk_device *disk = NULL;
1654 char buf[PATH_MAX + 1], *name = NULL, *diskname = NULL;
1655 int real_part = 0, rc = -EINVAL;
1656
1657 if (devno == 0 && devname) {
1658 struct stat st;
1659
1660 DBG(DEV, ul_debug("%s: reading alone device", devname));
1661
1662 if (stat(devname, &st) || !S_ISBLK(st.st_mode)) {
1663 warnx(_("%s: not a block device"), devname);
1664 goto leave;
1665 }
1666 devno = st.st_rdev;
1667 } else if (devno) {
1668 DBG(DEV, ul_debug("%d:%d: reading alone device", major(devno), minor(devno)));
1669 } else {
1670 assert(devno || devname);
1671 return -EINVAL;
1672 }
1673
1674 /* TODO: sysfs_devno_to_devname() internally initializes path_cxt, it
1675 * would be better to use ul_new_sysfs_path() + sysfs_blkdev_get_name()
1676 * and reuse path_cxt for initialize_device()
1677 */
1678 name = sysfs_devno_to_devname(devno, buf, sizeof(buf));
1679 if (!name) {
1680 if (devname)
1681 warn(_("%s: failed to get sysfs name"), devname);
1682 goto leave;
1683 }
1684 name = xstrdup(name);
1685
1686 if (!strncmp(name, "dm-", 3)) {
1687 /* dm mapping is never a real partition! */
1688 real_part = 0;
1689 } else {
1690 dev_t diskno = 0;
1691
1692 if (blkid_devno_to_wholedisk(devno, buf, sizeof(buf), &diskno)) {
1693 warn(_("%s: failed to get whole-disk device number"), name);
1694 goto leave;
1695 }
1696 diskname = buf;
1697 real_part = devno != diskno;
1698 }
1699
1700 if (!real_part) {
1701 /*
1702 * Device is not a partition.
1703 */
1704 DBG(DEV, ul_debug(" non-partition"));
1705
1706 dev = devtree_get_device_or_new(tr, NULL, name);
1707 if (!dev)
1708 goto leave;
1709
1710 lsblk_devtree_add_root(tr, dev);
1711 process_dependencies(tr, dev, !lsblk->inverse);
1712 } else {
1713 /*
1714 * Partition, read sysfs name of the disk device
1715 */
1716 DBG(DEV, ul_debug(" partition"));
1717
1718 disk = devtree_get_device_or_new(tr, NULL, diskname);
1719 if (!disk)
1720 goto leave;
1721
1722 dev = devtree_get_device_or_new(tr, disk, name);
1723 if (!dev)
1724 goto leave;
1725
1726 lsblk_devtree_add_root(tr, dev);
1727 process_dependencies(tr, dev, 1);
1728
1729 if (lsblk->inverse
1730 && lsblk_device_new_dependence(dev, disk) == 0)
1731 process_dependencies(tr, disk, 0);
1732 else
1733 ul_path_close_dirfd(disk->sysfs);
1734 }
1735
1736 rc = 0;
1737 leave:
1738 if (dev && dev->sysfs)
1739 ul_path_close_dirfd(dev->sysfs);
1740 if (disk && disk->sysfs)
1741 ul_path_close_dirfd(disk->sysfs);
1742 free(name);
1743 return rc;
1744 }
1745
1746 static int process_one_device(struct lsblk_devtree *tr, char *devname)
1747 {
1748 assert(devname);
1749 return __process_one_device(tr, devname, 0);
1750 }
1751
1752 /*
1753 * The /sys/block contains only root devices, and no partitions. It seems more
1754 * simple to scan /sys/dev/block where are all devices without exceptions to get
1755 * top-level devices for the reverse tree.
1756 */
1757 static int process_all_devices_inverse(struct lsblk_devtree *tr)
1758 {
1759 DIR *dir;
1760 struct dirent *d;
1761 struct path_cxt *pc = ul_new_path(_PATH_SYS_DEVBLOCK);
1762
1763 assert(lsblk->inverse);
1764
1765 if (!pc)
1766 err(EXIT_FAILURE, _("failed to allocate /sys handler"));
1767
1768 ul_path_set_prefix(pc, lsblk->sysroot);
1769 dir = ul_path_opendir(pc, NULL);
1770 if (!dir)
1771 goto done;
1772
1773 DBG(DEV, ul_debug("iterate on " _PATH_SYS_DEVBLOCK));
1774
1775 while ((d = xreaddir(dir))) {
1776 dev_t devno;
1777 int maj, min;
1778
1779 DBG(DEV, ul_debug(" %s dentry", d->d_name));
1780
1781 if (sscanf(d->d_name, "%d:%d", &maj, &min) != 2)
1782 continue;
1783 devno = makedev(maj, min);
1784
1785 if (is_maj_excluded(maj) || !is_maj_included(maj))
1786 continue;
1787 if (ul_path_countf_dirents(pc, "%s/holders", d->d_name) != 0)
1788 continue;
1789 if (sysfs_devno_count_partitions(devno) != 0)
1790 continue;
1791 __process_one_device(tr, NULL, devno);
1792 }
1793
1794 closedir(dir);
1795 done:
1796 ul_unref_path(pc);
1797 DBG(DEV, ul_debug("iterate on " _PATH_SYS_DEVBLOCK " -- done"));
1798 return 0;
1799 }
1800
1801 /*
1802 * Reads root nodes (devices) from /sys/block into devices tree
1803 */
1804 static int process_all_devices(struct lsblk_devtree *tr)
1805 {
1806 DIR *dir;
1807 struct dirent *d;
1808 struct path_cxt *pc;
1809
1810 assert(lsblk->inverse == 0);
1811
1812 pc = ul_new_path(_PATH_SYS_BLOCK);
1813 if (!pc)
1814 err(EXIT_FAILURE, _("failed to allocate /sys handler"));
1815
1816 ul_path_set_prefix(pc, lsblk->sysroot);
1817 dir = ul_path_opendir(pc, NULL);
1818 if (!dir)
1819 goto done;
1820
1821 DBG(DEV, ul_debug("iterate on " _PATH_SYS_BLOCK));
1822
1823 while ((d = xreaddir(dir))) {
1824 struct lsblk_device *dev = NULL;
1825
1826 DBG(DEV, ul_debug(" %s dentry", d->d_name));
1827 dev = devtree_get_device_or_new(tr, NULL, d->d_name);
1828 if (!dev)
1829 goto next;
1830
1831 /* remove unwanted devices */
1832 if (is_maj_excluded(dev->maj) || !is_maj_included(dev->maj)) {
1833 DBG(DEV, ul_debug(" %s: ignore (by filter)", d->d_name));
1834 lsblk_devtree_remove_device(tr, dev);
1835 dev = NULL;
1836 goto next;
1837 }
1838
1839 if (dev->nslaves) {
1840 DBG(DEV, ul_debug(" %s: ignore (in-middle)", d->d_name));
1841 goto next;
1842 }
1843
1844 lsblk_devtree_add_root(tr, dev);
1845 process_dependencies(tr, dev, 1);
1846 next:
1847 /* Let's be careful with number of open files */
1848 if (dev && dev->sysfs)
1849 ul_path_close_dirfd(dev->sysfs);
1850 }
1851
1852 closedir(dir);
1853 done:
1854 ul_unref_path(pc);
1855 DBG(DEV, ul_debug("iterate on " _PATH_SYS_BLOCK " -- done"));
1856 return 0;
1857 }
1858
1859 /*
1860 * Parses major numbers as specified on lsblk command line
1861 */
1862 static void parse_excludes(const char *str0)
1863 {
1864 const char *str = str0;
1865
1866 while (str && *str) {
1867 char *end = NULL;
1868 unsigned long n;
1869
1870 errno = 0;
1871 n = strtoul(str, &end, 10);
1872
1873 if (end == str || (end && *end && *end != ','))
1874 errx(EXIT_FAILURE, _("failed to parse list '%s'"), str0);
1875 if (errno != 0 && (n == ULONG_MAX || n == 0))
1876 err(EXIT_FAILURE, _("failed to parse list '%s'"), str0);
1877 excludes[nexcludes++] = n;
1878
1879 if (nexcludes == ARRAY_SIZE(excludes))
1880 /* TRANSLATORS: The standard value for %d is 256. */
1881 errx(EXIT_FAILURE, _("the list of excluded devices is "
1882 "too large (limit is %d devices)"),
1883 (int)ARRAY_SIZE(excludes));
1884
1885 str = end && *end ? end + 1 : NULL;
1886 }
1887 }
1888
1889 /*
1890 * Parses major numbers as specified on lsblk command line
1891 * (TODO: what about refactor and merge parse_excludes() and parse_includes().)
1892 */
1893 static void parse_includes(const char *str0)
1894 {
1895 const char *str = str0;
1896
1897 while (str && *str) {
1898 char *end = NULL;
1899 unsigned long n;
1900
1901 errno = 0;
1902 n = strtoul(str, &end, 10);
1903
1904 if (end == str || (end && *end && *end != ','))
1905 errx(EXIT_FAILURE, _("failed to parse list '%s'"), str0);
1906 if (errno != 0 && (n == ULONG_MAX || n == 0))
1907 err(EXIT_FAILURE, _("failed to parse list '%s'"), str0);
1908 includes[nincludes++] = n;
1909
1910 if (nincludes == ARRAY_SIZE(includes))
1911 /* TRANSLATORS: The standard value for %d is 256. */
1912 errx(EXIT_FAILURE, _("the list of included devices is "
1913 "too large (limit is %d devices)"),
1914 (int)ARRAY_SIZE(includes));
1915 str = end && *end ? end + 1 : NULL;
1916 }
1917 }
1918
1919 /*
1920 * see set_sortdata_u64() and columns initialization in main()
1921 */
1922 static int cmp_u64_cells(struct libscols_cell *a,
1923 struct libscols_cell *b,
1924 __attribute__((__unused__)) void *data)
1925 {
1926 uint64_t *adata = (uint64_t *) scols_cell_get_userdata(a),
1927 *bdata = (uint64_t *) scols_cell_get_userdata(b);
1928
1929 if (adata == NULL && bdata == NULL)
1930 return 0;
1931 if (adata == NULL)
1932 return -1;
1933 if (bdata == NULL)
1934 return 1;
1935 return *adata == *bdata ? 0 : *adata >= *bdata ? 1 : -1;
1936 }
1937
1938 static void device_set_dedupkey(
1939 struct lsblk_device *dev,
1940 struct lsblk_device *parent,
1941 int id)
1942 {
1943 struct lsblk_iter itr;
1944 struct lsblk_device *child = NULL;
1945
1946 dev->dedupkey = device_get_data(dev, parent, id, NULL);
1947 if (dev->dedupkey)
1948 DBG(DEV, ul_debugobj(dev, "%s: de-duplication key: %s", dev->name, dev->dedupkey));
1949
1950 if (dev->npartitions == 0)
1951 /* For partitions we often read from parental whole-disk sysfs,
1952 * otherwise we can close */
1953 ul_path_close_dirfd(dev->sysfs);
1954
1955 lsblk_reset_iter(&itr, LSBLK_ITER_FORWARD);
1956
1957 while (lsblk_device_next_child(dev, &itr, &child) == 0)
1958 device_set_dedupkey(child, dev, id);
1959
1960 /* Let's be careful with number of open files */
1961 ul_path_close_dirfd(dev->sysfs);
1962 }
1963
1964 static void devtree_set_dedupkeys(struct lsblk_devtree *tr, int id)
1965 {
1966 struct lsblk_iter itr;
1967 struct lsblk_device *dev = NULL;
1968
1969 lsblk_reset_iter(&itr, LSBLK_ITER_FORWARD);
1970
1971 while (lsblk_devtree_next_root(tr, &itr, &dev) == 0)
1972 device_set_dedupkey(dev, NULL, id);
1973 }
1974
1975 static void __attribute__((__noreturn__)) usage(void)
1976 {
1977 FILE *out = stdout;
1978 size_t i;
1979
1980 fputs(USAGE_HEADER, out);
1981 fprintf(out, _(" %s [options] [<device> ...]\n"), program_invocation_short_name);
1982
1983 fputs(USAGE_SEPARATOR, out);
1984 fputs(_("List information about block devices.\n"), out);
1985
1986 fputs(USAGE_OPTIONS, out);
1987 fputs(_(" -A, --noempty don't print empty devices\n"), out);
1988 fputs(_(" -D, --discard print discard capabilities\n"), out);
1989 fputs(_(" -E, --dedup <column> de-duplicate output by <column>\n"), out);
1990 fputs(_(" -I, --include <list> show only devices with specified major numbers\n"), out);
1991 fputs(_(" -J, --json use JSON output format\n"), out);
1992 fputs(_(" -M, --merge group parents of sub-trees (usable for RAIDs, Multi-path)\n"), out);
1993 fputs(_(" -O, --output-all output all columns\n"), out);
1994 fputs(_(" -P, --pairs use key=\"value\" output format\n"), out);
1995 fputs(_(" -S, --scsi output info about SCSI devices\n"), out);
1996 fputs(_(" -N, --nvme output info about NVMe devices\n"), out);
1997 fputs(_(" -v, --virtio output info about virtio devices\n"), out);
1998 fputs(_(" -T, --tree[=<column>] use tree format output\n"), out);
1999 fputs(_(" -a, --all print all devices\n"), out);
2000 fputs(_(" -b, --bytes print SIZE in bytes rather than in human readable format\n"), out);
2001 fputs(_(" -d, --nodeps don't print slaves or holders\n"), out);
2002 fputs(_(" -e, --exclude <list> exclude devices by major number (default: RAM disks)\n"), out);
2003 fputs(_(" -f, --fs output info about filesystems\n"), out);
2004 fputs(_(" -i, --ascii use ascii characters only\n"), out);
2005 fputs(_(" -l, --list use list format output\n"), out);
2006 fputs(_(" -m, --perms output info about permissions\n"), out);
2007 fputs(_(" -n, --noheadings don't print headings\n"), out);
2008 fputs(_(" -o, --output <list> output columns\n"), out);
2009 fputs(_(" -p, --paths print complete device path\n"), out);
2010 fputs(_(" -r, --raw use raw output format\n"), out);
2011 fputs(_(" -s, --inverse inverse dependencies\n"), out);
2012 fputs(_(" -t, --topology output info about topology\n"), out);
2013 fputs(_(" -w, --width <num> specifies output width as number of characters\n"), out);
2014 fputs(_(" -x, --sort <column> sort output by <column>\n"), out);
2015 fputs(_(" -y, --shell use column names to be usable as shell variable identifiers\n"), out);
2016 fputs(_(" -z, --zoned print zone related information\n"), out);
2017 fputs(_(" --sysroot <dir> use specified directory as system root\n"), out);
2018 fputs(USAGE_SEPARATOR, out);
2019 printf(USAGE_HELP_OPTIONS(22));
2020
2021 fprintf(out, USAGE_COLUMNS);
2022
2023 for (i = 0; i < ARRAY_SIZE(infos); i++)
2024 fprintf(out, " %12s %s\n", infos[i].name, _(infos[i].help));
2025
2026 printf(USAGE_MAN_TAIL("lsblk(8)"));
2027
2028 exit(EXIT_SUCCESS);
2029 }
2030
2031 static void check_sysdevblock(void)
2032 {
2033 if (access(_PATH_SYS_DEVBLOCK, R_OK) != 0)
2034 err(EXIT_FAILURE, _("failed to access sysfs directory: %s"),
2035 _PATH_SYS_DEVBLOCK);
2036 }
2037
2038 int main(int argc, char *argv[])
2039 {
2040 struct lsblk _ls = {
2041 .sort_id = -1,
2042 .dedup_id = -1,
2043 .flags = LSBLK_TREE,
2044 .tree_id = COL_NAME
2045 };
2046 struct lsblk_devtree *tr = NULL;
2047 int c, status = EXIT_FAILURE;
2048 char *outarg = NULL;
2049 size_t i;
2050 unsigned int width = 0;
2051 int force_tree = 0, has_tree_col = 0;
2052
2053 enum {
2054 OPT_SYSROOT = CHAR_MAX + 1
2055 };
2056
2057 static const struct option longopts[] = {
2058 { "all", no_argument, NULL, 'a' },
2059 { "bytes", no_argument, NULL, 'b' },
2060 { "nodeps", no_argument, NULL, 'd' },
2061 { "noempty", no_argument, NULL, 'A' },
2062 { "discard", no_argument, NULL, 'D' },
2063 { "dedup", required_argument, NULL, 'E' },
2064 { "zoned", no_argument, NULL, 'z' },
2065 { "help", no_argument, NULL, 'h' },
2066 { "json", no_argument, NULL, 'J' },
2067 { "output", required_argument, NULL, 'o' },
2068 { "output-all", no_argument, NULL, 'O' },
2069 { "merge", no_argument, NULL, 'M' },
2070 { "perms", no_argument, NULL, 'm' },
2071 { "noheadings", no_argument, NULL, 'n' },
2072 { "list", no_argument, NULL, 'l' },
2073 { "ascii", no_argument, NULL, 'i' },
2074 { "raw", no_argument, NULL, 'r' },
2075 { "inverse", no_argument, NULL, 's' },
2076 { "fs", no_argument, NULL, 'f' },
2077 { "exclude", required_argument, NULL, 'e' },
2078 { "include", required_argument, NULL, 'I' },
2079 { "topology", no_argument, NULL, 't' },
2080 { "paths", no_argument, NULL, 'p' },
2081 { "pairs", no_argument, NULL, 'P' },
2082 { "scsi", no_argument, NULL, 'S' },
2083 { "nvme", no_argument, NULL, 'N' },
2084 { "virtio", no_argument, NULL, 'v' },
2085 { "sort", required_argument, NULL, 'x' },
2086 { "sysroot", required_argument, NULL, OPT_SYSROOT },
2087 { "shell", no_argument, NULL, 'y' },
2088 { "tree", optional_argument, NULL, 'T' },
2089 { "version", no_argument, NULL, 'V' },
2090 { "width", required_argument, NULL, 'w' },
2091 { NULL, 0, NULL, 0 },
2092 };
2093
2094 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
2095 { 'D','O' },
2096 { 'I','e' },
2097 { 'J', 'P', 'r' },
2098 { 'O','S' },
2099 { 'O','f' },
2100 { 'O','m' },
2101 { 'O','o' },
2102 { 'O','t' },
2103 { 'P','T', 'l','r' },
2104 { 0 }
2105 };
2106 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
2107
2108 setlocale(LC_ALL, "");
2109 bindtextdomain(PACKAGE, LOCALEDIR);
2110 textdomain(PACKAGE);
2111 close_stdout_atexit();
2112
2113 lsblk = &_ls;
2114
2115 lsblk_init_debug();
2116
2117 while((c = getopt_long(argc, argv,
2118 "AabdDzE:e:fhJlNnMmo:OpPiI:rstVvST::w:x:y",
2119 longopts, NULL)) != -1) {
2120
2121 err_exclusive_options(c, longopts, excl, excl_st);
2122
2123 switch(c) {
2124 case 'A':
2125 lsblk->noempty = 1;
2126 break;
2127 case 'a':
2128 lsblk->all_devices = 1;
2129 break;
2130 case 'b':
2131 lsblk->bytes = 1;
2132 break;
2133 case 'd':
2134 lsblk->nodeps = 1;
2135 break;
2136 case 'D':
2137 add_uniq_column(COL_NAME);
2138 add_uniq_column(COL_DALIGN);
2139 add_uniq_column(COL_DGRAN);
2140 add_uniq_column(COL_DMAX);
2141 add_uniq_column(COL_DZERO);
2142 break;
2143 case 'z':
2144 add_uniq_column(COL_NAME);
2145 add_uniq_column(COL_ZONED);
2146 add_uniq_column(COL_ZONE_SZ);
2147 add_uniq_column(COL_ZONE_NR);
2148 add_uniq_column(COL_ZONE_AMAX);
2149 add_uniq_column(COL_ZONE_OMAX);
2150 add_uniq_column(COL_ZONE_APP);
2151 add_uniq_column(COL_ZONE_WGRAN);
2152 break;
2153 case 'e':
2154 parse_excludes(optarg);
2155 break;
2156 case 'J':
2157 lsblk->flags |= LSBLK_JSON;
2158 break;
2159 case 'l':
2160 lsblk->flags &= ~LSBLK_TREE; /* disable the default */
2161 break;
2162 case 'M':
2163 lsblk->merge = 1;
2164 break;
2165 case 'n':
2166 lsblk->flags |= LSBLK_NOHEADINGS;
2167 break;
2168 case 'o':
2169 outarg = optarg;
2170 break;
2171 case 'O':
2172 for (ncolumns = 0 ; ncolumns < ARRAY_SIZE(infos); ncolumns++)
2173 columns[ncolumns] = ncolumns;
2174 break;
2175 case 'p':
2176 lsblk->paths = 1;
2177 break;
2178 case 'P':
2179 lsblk->flags |= LSBLK_EXPORT;
2180 lsblk->flags &= ~LSBLK_TREE; /* disable the default */
2181 break;
2182 case 'y':
2183 lsblk->flags |= LSBLK_SHELLVAR;
2184 break;
2185 case 'i':
2186 lsblk->flags |= LSBLK_ASCII;
2187 break;
2188 case 'I':
2189 parse_includes(optarg);
2190 break;
2191 case 'r':
2192 lsblk->flags &= ~LSBLK_TREE; /* disable the default */
2193 lsblk->flags |= LSBLK_RAW; /* enable raw */
2194 break;
2195 case 's':
2196 lsblk->inverse = 1;
2197 break;
2198 case 'f':
2199 add_uniq_column(COL_NAME);
2200 add_uniq_column(COL_FSTYPE);
2201 add_uniq_column(COL_FSVERSION);
2202 add_uniq_column(COL_LABEL);
2203 add_uniq_column(COL_UUID);
2204 add_uniq_column(COL_FSAVAIL);
2205 add_uniq_column(COL_FSUSEPERC);
2206 add_uniq_column(COL_TARGETS);
2207 break;
2208 case 'm':
2209 add_uniq_column(COL_NAME);
2210 add_uniq_column(COL_SIZE);
2211 add_uniq_column(COL_OWNER);
2212 add_uniq_column(COL_GROUP);
2213 add_uniq_column(COL_MODE);
2214 break;
2215 case 't':
2216 add_uniq_column(COL_NAME);
2217 add_uniq_column(COL_ALIOFF);
2218 add_uniq_column(COL_MINIO);
2219 add_uniq_column(COL_OPTIO);
2220 add_uniq_column(COL_PHYSEC);
2221 add_uniq_column(COL_LOGSEC);
2222 add_uniq_column(COL_ROTA);
2223 add_uniq_column(COL_SCHED);
2224 add_uniq_column(COL_RQ_SIZE);
2225 add_uniq_column(COL_RA);
2226 add_uniq_column(COL_WSAME);
2227 break;
2228 case 'S':
2229 lsblk->nodeps = 1;
2230 lsblk->scsi = 1;
2231 add_uniq_column(COL_NAME);
2232 add_uniq_column(COL_HCTL);
2233 add_uniq_column(COL_TYPE);
2234 add_uniq_column(COL_VENDOR);
2235 add_uniq_column(COL_MODEL);
2236 add_uniq_column(COL_REV);
2237 add_uniq_column(COL_SERIAL);
2238 add_uniq_column(COL_TRANSPORT);
2239 break;
2240 case 'N':
2241 lsblk->nodeps = 1;
2242 lsblk->nvme = 1;
2243 add_uniq_column(COL_NAME);
2244 add_uniq_column(COL_TYPE);
2245 add_uniq_column(COL_MODEL);
2246 add_uniq_column(COL_SERIAL);
2247 add_uniq_column(COL_REV);
2248 add_uniq_column(COL_TRANSPORT);
2249 add_uniq_column(COL_RQ_SIZE);
2250 add_uniq_column(COL_MQ);
2251 break;
2252 case 'v':
2253 lsblk->nodeps = 1;
2254 lsblk->virtio = 1;
2255 add_uniq_column(COL_NAME);
2256 add_uniq_column(COL_TYPE);
2257 add_uniq_column(COL_TRANSPORT);
2258 add_uniq_column(COL_SIZE);
2259 add_uniq_column(COL_RQ_SIZE);
2260 add_uniq_column(COL_MQ);
2261 break;
2262 case 'T':
2263 force_tree = 1;
2264 if (optarg) {
2265 if (*optarg == '=')
2266 optarg++;
2267 lsblk->tree_id = column_name_to_id(optarg, strlen(optarg));
2268 }
2269 break;
2270 case OPT_SYSROOT:
2271 lsblk->sysroot = optarg;
2272 break;
2273 case 'E':
2274 lsblk->dedup_id = column_name_to_id(optarg, strlen(optarg));
2275 if (lsblk->dedup_id >= 0)
2276 break;
2277 errtryhelp(EXIT_FAILURE);
2278 break;
2279 case 'w':
2280 width = strtou32_or_err(optarg, _("invalid output width number argument"));
2281 break;
2282 case 'x':
2283 lsblk->flags &= ~LSBLK_TREE; /* disable the default */
2284 lsblk->sort_id = column_name_to_id(optarg, strlen(optarg));
2285 if (lsblk->sort_id >= 0)
2286 break;
2287 errtryhelp(EXIT_FAILURE);
2288 break;
2289
2290 case 'h':
2291 usage();
2292 case 'V':
2293 print_version(EXIT_SUCCESS);
2294 default:
2295 errtryhelp(EXIT_FAILURE);
2296 }
2297 }
2298
2299 if (force_tree)
2300 lsblk->flags |= LSBLK_TREE;
2301
2302 check_sysdevblock();
2303
2304 if (!ncolumns) {
2305 add_column(COL_NAME);
2306 add_column(COL_MAJMIN);
2307 add_column(COL_RM);
2308 add_column(COL_SIZE);
2309 add_column(COL_RO);
2310 add_column(COL_TYPE);
2311 add_column(COL_TARGETS);
2312 }
2313
2314 if (outarg && string_add_to_idarray(outarg, columns, ARRAY_SIZE(columns),
2315 &ncolumns, column_name_to_id) < 0)
2316 return EXIT_FAILURE;
2317
2318 if (lsblk->all_devices == 0 && nexcludes == 0 && nincludes == 0)
2319 excludes[nexcludes++] = 1; /* default: ignore RAM disks */
2320
2321 if (lsblk->sort_id < 0)
2322 /* Since Linux 4.8 we have sort devices by default, because
2323 * /sys is no more sorted */
2324 lsblk->sort_id = COL_MAJMIN;
2325
2326 /* For --{inverse,raw,pairs} --list we still follow parent->child relation */
2327 if (!(lsblk->flags & LSBLK_TREE)
2328 && (lsblk->inverse || lsblk->flags & LSBLK_EXPORT || lsblk->flags & LSBLK_RAW))
2329 lsblk->force_tree_order = 1;
2330
2331 if (lsblk->sort_id >= 0 && column_id_to_number(lsblk->sort_id) < 0) {
2332 /* the sort column is not between output columns -- add as hidden */
2333 add_column(lsblk->sort_id);
2334 lsblk->sort_hidden = 1;
2335 }
2336
2337 if (lsblk->dedup_id >= 0 && column_id_to_number(lsblk->dedup_id) < 0) {
2338 /* the deduplication column is not between output columns -- add as hidden */
2339 add_column(lsblk->dedup_id);
2340 lsblk->dedup_hidden = 1;
2341 }
2342
2343 lsblk_mnt_init();
2344 scols_init_debug(0);
2345 ul_path_init_debug();
2346
2347 /*
2348 * initialize output columns
2349 */
2350 if (!(lsblk->table = scols_new_table()))
2351 errx(EXIT_FAILURE, _("failed to allocate output table"));
2352 scols_table_enable_raw(lsblk->table, !!(lsblk->flags & LSBLK_RAW));
2353 scols_table_enable_export(lsblk->table, !!(lsblk->flags & LSBLK_EXPORT));
2354 scols_table_enable_shellvar(lsblk->table, !!(lsblk->flags & LSBLK_SHELLVAR));
2355 scols_table_enable_ascii(lsblk->table, !!(lsblk->flags & LSBLK_ASCII));
2356 scols_table_enable_json(lsblk->table, !!(lsblk->flags & LSBLK_JSON));
2357 scols_table_enable_noheadings(lsblk->table, !!(lsblk->flags & LSBLK_NOHEADINGS));
2358
2359 if (lsblk->flags & LSBLK_JSON)
2360 scols_table_set_name(lsblk->table, "blockdevices");
2361 if (width) {
2362 scols_table_set_termwidth(lsblk->table, width);
2363 scols_table_set_termforce(lsblk->table, SCOLS_TERMFORCE_ALWAYS);
2364 }
2365
2366 for (i = 0; i < ncolumns; i++) {
2367 const struct colinfo *ci = get_column_info(i);
2368 struct libscols_column *cl;
2369 int id = get_column_id(i), fl = ci->flags;
2370
2371 if ((lsblk->flags & LSBLK_TREE)
2372 && has_tree_col == 0
2373 && id == lsblk->tree_id) {
2374 fl |= SCOLS_FL_TREE;
2375 fl &= ~SCOLS_FL_RIGHT;
2376 has_tree_col = 1;
2377 }
2378
2379 if (lsblk->sort_hidden && lsblk->sort_id == id)
2380 fl |= SCOLS_FL_HIDDEN;
2381 if (lsblk->dedup_hidden && lsblk->dedup_id == id)
2382 fl |= SCOLS_FL_HIDDEN;
2383
2384 if (force_tree
2385 && lsblk->flags & LSBLK_JSON
2386 && has_tree_col == 0
2387 && i + 1 == ncolumns)
2388 /* The "--tree --json" specified, but no column with
2389 * SCOLS_FL_TREE yet; force it for the last column
2390 */
2391 fl |= SCOLS_FL_TREE;
2392
2393 cl = scols_table_new_column(lsblk->table, ci->name, ci->whint, fl);
2394 if (!cl) {
2395 warn(_("failed to allocate output column"));
2396 goto leave;
2397 }
2398 if (!lsblk->sort_col && lsblk->sort_id == id) {
2399 lsblk->sort_col = cl;
2400 scols_column_set_cmpfunc(cl,
2401 ci->type == COLTYPE_NUM ? cmp_u64_cells :
2402 ci->type == COLTYPE_SIZE ? cmp_u64_cells :
2403 ci->type == COLTYPE_SORTNUM ? cmp_u64_cells : scols_cmpstr_cells,
2404 NULL);
2405 }
2406 /* multi-line cells (now used for MOUNTPOINTS) */
2407 if (fl & SCOLS_FL_WRAP) {
2408 scols_column_set_wrapfunc(cl,
2409 scols_wrapnl_chunksize,
2410 scols_wrapnl_nextchunk,
2411 NULL);
2412 scols_column_set_safechars(cl, "\n");
2413 }
2414
2415 if (lsblk->flags & LSBLK_JSON) {
2416 switch (ci->type) {
2417 case COLTYPE_SIZE:
2418 if (!lsblk->bytes)
2419 break;
2420 /* fallthrough */
2421 case COLTYPE_NUM:
2422 scols_column_set_json_type(cl, SCOLS_JSON_NUMBER);
2423 break;
2424 case COLTYPE_BOOL:
2425 scols_column_set_json_type(cl, SCOLS_JSON_BOOLEAN);
2426 break;
2427 default:
2428 if (fl & SCOLS_FL_WRAP)
2429 scols_column_set_json_type(cl, SCOLS_JSON_ARRAY_STRING);
2430 else
2431 scols_column_set_json_type(cl, SCOLS_JSON_STRING);
2432 break;
2433 }
2434 }
2435 }
2436
2437 tr = lsblk_new_devtree();
2438 if (!tr)
2439 err(EXIT_FAILURE, _("failed to allocate device tree"));
2440
2441 if (optind == argc) {
2442 int rc = lsblk->inverse ?
2443 process_all_devices_inverse(tr) :
2444 process_all_devices(tr);
2445
2446 status = rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
2447 } else {
2448 int cnt = 0, cnt_err = 0;
2449
2450 while (optind < argc) {
2451 if (process_one_device(tr, argv[optind++]) != 0)
2452 cnt_err++;
2453 cnt++;
2454 }
2455 status = cnt == 0 ? EXIT_FAILURE : /* nothing */
2456 cnt == cnt_err ? LSBLK_EXIT_ALLFAILED :/* all failed */
2457 cnt_err ? LSBLK_EXIT_SOMEOK : /* some ok */
2458 EXIT_SUCCESS; /* all success */
2459 }
2460
2461 if (lsblk->dedup_id > -1) {
2462 devtree_set_dedupkeys(tr, lsblk->dedup_id);
2463 lsblk_devtree_deduplicate_devices(tr);
2464 }
2465
2466 devtree_to_scols(tr, lsblk->table);
2467
2468 if (lsblk->sort_col)
2469 scols_sort_table(lsblk->table, lsblk->sort_col);
2470 if (lsblk->force_tree_order)
2471 scols_sort_table_by_tree(lsblk->table);
2472
2473 scols_print_table(lsblk->table);
2474
2475 leave:
2476 if (lsblk->sort_col)
2477 unref_sortdata(lsblk->table);
2478
2479 scols_unref_table(lsblk->table);
2480
2481 lsblk_mnt_deinit();
2482 lsblk_properties_deinit();
2483 lsblk_unref_devtree(tr);
2484
2485 return status;
2486 }