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