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