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