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