1/*-
2 * Copyright (c) 2019 Klara Inc.
3 * Copyright (c) 2015 Baptiste Daroussin <bapt@FreeBSD.org>
4 * Copyright (c) 2015 Allan Jude <allanjude@FreeBSD.org>
5 * Copyright (c) 2000 by Matthew Jacob
6 * All rights reserved.
7 *
8 * Portions of this software were developed by Edward Tomasz Napierala
9 * under sponsorship from Klara Inc.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer
16 *    in this position and unchanged.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
22 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 */
32
33#include <sys/cdefs.h>
34__FBSDID("$FreeBSD$");
35
36#include <sys/endian.h>
37#include <sys/param.h>
38#include <sys/disk.h>
39#include <sys/ioctl.h>
40#include <sys/types.h>
41
42#include <err.h>
43#include <errno.h>
44#include <fcntl.h>
45#include <getopt.h>
46#include <glob.h>
47#include <stdbool.h>
48#include <stddef.h>
49#include <stdint.h>
50#include <stdio.h>
51#include <stdlib.h>
52#include <string.h>
53#include <unistd.h>
54#include <libxo/xo.h>
55
56#include <cam/scsi/scsi_enc.h>
57
58#include "eltsub.h"
59
60#define SESUTIL_XO_VERSION	"1"
61
62#define TEMPERATURE_OFFSET	20
63
64#define PRINT_STYLE_DASHED	0
65#define PRINT_STYLE_DASHED_2	1
66#define PRINT_STYLE_CSV 	2
67#define PRINT_STYLE_CSV_2	3
68
69static int encstatus(int argc, char **argv);
70static int fault(int argc, char **argv);
71static int locate(int argc, char **argv);
72static int objmap(int argc, char **argv);
73static int sesled(int argc, char **argv, bool fault);
74static int show(int argc, char **argv);
75static void sesutil_print(int *style, const char *fmt, ...) __printflike(2,3);
76
77static struct command {
78	const char *name;
79	const char *param;
80	const char *desc;
81	int (*exec)(int argc, char **argv);
82} cmds[] = {
83	{ "fault",
84	    "(<disk>|<sesid>|all) (on|off)",
85	    "Change the state of the fault LED associated with a disk",
86	    fault },
87	{ "locate",
88	    "(<disk>|<sesid>|all) (on|off)",
89	    "Change the state of the locate LED associated with a disk",
90	    locate },
91	{ "map", "",
92	    "Print a map of the devices managed by the enclosure", objmap } ,
93	{ "show", "",
94	    "Print a human-friendly summary of the enclosure", show } ,
95	{ "status", "", "Print the status of the enclosure",
96	    encstatus },
97};
98
99static const int nbcmds = nitems(cmds);
100static const char *uflag;
101
102static void
103usage(FILE *out, const char *subcmd)
104{
105	int i;
106
107	if (subcmd == NULL) {
108		fprintf(out, "Usage: %s [-u /dev/ses<N>] <command> [options]\n",
109		    getprogname());
110		fprintf(out, "Commands supported:\n");
111	}
112	for (i = 0; i < nbcmds; i++) {
113		if (subcmd != NULL) {
114			if (strcmp(subcmd, cmds[i].name) == 0) {
115				fprintf(out, "Usage: %s %s [-u /dev/ses<N>] "
116				    "%s\n\t%s\n", getprogname(), subcmd,
117				    cmds[i].param, cmds[i].desc);
118				break;
119			}
120			continue;
121		}
122		fprintf(out, "    %-12s%s\n\t\t%s\n\n", cmds[i].name,
123		    cmds[i].param, cmds[i].desc);
124	}
125
126	exit(EXIT_FAILURE);
127}
128
129static void
130do_led(int fd, unsigned int idx, elm_type_t type, bool onoff, bool setfault)
131{
132	int state = onoff ? 1 : 0;
133	encioc_elm_status_t o;
134	struct ses_ctrl_dev_slot *slot;
135
136	o.elm_idx = idx;
137	if (ioctl(fd, ENCIOC_GETELMSTAT, (caddr_t) &o) < 0) {
138		close(fd);
139		xo_err(EXIT_FAILURE, "ENCIOC_GETELMSTAT");
140	}
141	slot = (struct ses_ctrl_dev_slot *) &o.cstat[0];
142	switch (type) {
143	case ELMTYP_DEVICE:
144	case ELMTYP_ARRAY_DEV:
145		ses_ctrl_common_set_select(&slot->common, 1);
146		if (setfault)
147			ses_ctrl_dev_slot_set_rqst_fault(slot, state);
148		else
149			ses_ctrl_dev_slot_set_rqst_ident(slot, state);
150		break;
151	default:
152		return;
153	}
154	if (ioctl(fd, ENCIOC_SETELMSTAT, (caddr_t) &o) < 0) {
155		close(fd);
156		xo_err(EXIT_FAILURE, "ENCIOC_SETELMSTAT");
157	}
158}
159
160static bool
161disk_match(const char *devnames, const char *disk, size_t len)
162{
163	const char *dname;
164
165	dname = devnames;
166	while ((dname = strstr(dname, disk)) != NULL) {
167		if (dname[len] == '\0' || dname[len] == ',') {
168			return (true);
169		}
170		dname++;
171	}
172
173	return (false);
174}
175
176static int
177sesled(int argc, char **argv, bool setfault)
178{
179	encioc_elm_devnames_t objdn;
180	encioc_element_t *objp;
181	glob_t g;
182	char *disk, *endptr;
183	size_t len, i, ndisks;
184	int fd;
185	unsigned int nobj, j, sesid;
186	bool all, isses, onoff;
187
188	isses = false;
189	all = false;
190	onoff = false;
191
192	if (argc != 3) {
193		usage(stderr, (setfault ? "fault" : "locate"));
194	}
195
196	disk = argv[1];
197
198	sesid = strtoul(disk, &endptr, 10);
199	if (*endptr == '\0') {
200		endptr = strrchr(uflag, '*');
201		if (endptr != NULL && *endptr == '*') {
202			xo_warnx("Must specifying a SES device (-u) to use a SES "
203			    "id# to identify a disk");
204			usage(stderr, (setfault ? "fault" : "locate"));
205		}
206		isses = true;
207	}
208
209	if (strcmp(argv[2], "on") == 0) {
210		onoff = true;
211	} else if (strcmp(argv[2], "off") == 0) {
212		onoff = false;
213	} else {
214		usage(stderr, (setfault ? "fault" : "locate"));
215	}
216
217	if (strcmp(disk, "all") == 0) {
218		all = true;
219	}
220	len = strlen(disk);
221
222	/* Get the list of ses devices */
223	if (glob((uflag != NULL ? uflag : "/dev/ses[0-9]*"), 0, NULL, &g) ==
224	    GLOB_NOMATCH) {
225		globfree(&g);
226		xo_errx(EXIT_FAILURE, "No SES devices found");
227	}
228
229	ndisks = 0;
230	for (i = 0; i < g.gl_pathc; i++) {
231		/* ensure we only got numbers after ses */
232		if (strspn(g.gl_pathv[i] + 8, "0123456789") !=
233		    strlen(g.gl_pathv[i] + 8)) {
234			continue;
235		}
236		if ((fd = open(g.gl_pathv[i], O_RDWR)) < 0) {
237			/*
238			 * Don't treat non-access errors as critical if we are
239			 * accessing all devices
240			 */
241			if (errno == EACCES && g.gl_pathc > 1) {
242				xo_err(EXIT_FAILURE, "unable to access SES device");
243			}
244			xo_warn("unable to access SES device: %s", g.gl_pathv[i]);
245			continue;
246		}
247
248		if (ioctl(fd, ENCIOC_GETNELM, (caddr_t) &nobj) < 0) {
249			close(fd);
250			xo_err(EXIT_FAILURE, "ENCIOC_GETNELM");
251		}
252
253		objp = calloc(nobj, sizeof(encioc_element_t));
254		if (objp == NULL) {
255			close(fd);
256			xo_err(EXIT_FAILURE, "calloc()");
257		}
258
259		if (ioctl(fd, ENCIOC_GETELMMAP, (caddr_t) objp) < 0) {
260			free(objp);
261			close(fd);
262			xo_err(EXIT_FAILURE, "ENCIOC_GETELMMAP");
263		}
264
265		if (isses) {
266			if (sesid >= nobj) {
267				free(objp);
268				close(fd);
269				xo_errx(EXIT_FAILURE,
270				     "Requested SES ID does not exist");
271			}
272			do_led(fd, sesid, objp[sesid].elm_type, onoff, setfault);
273			ndisks++;
274			free(objp);
275			close(fd);
276			break;
277		}
278		for (j = 0; j < nobj; j++) {
279			const int devnames_size = 128;
280			char devnames[devnames_size];
281
282			if (all) {
283				do_led(fd, objp[j].elm_idx, objp[j].elm_type,
284				    onoff, setfault);
285				continue;
286			}
287			memset(&objdn, 0, sizeof(objdn));
288			memset(devnames, 0, devnames_size);
289			objdn.elm_idx = objp[j].elm_idx;
290			objdn.elm_names_size = devnames_size;
291			objdn.elm_devnames = devnames;
292			if (ioctl(fd, ENCIOC_GETELMDEVNAMES,
293			    (caddr_t) &objdn) <0) {
294				continue;
295			}
296			if (objdn.elm_names_len > 0) {
297				if (disk_match(objdn.elm_devnames, disk, len)) {
298					do_led(fd, objdn.elm_idx, objp[j].elm_type,
299					    onoff, setfault);
300					ndisks++;
301					break;
302				}
303			}
304		}
305		free(objp);
306		close(fd);
307	}
308	globfree(&g);
309	if (ndisks == 0 && all == false) {
310		xo_errx(EXIT_FAILURE, "Count not find the SES id of device '%s'",
311		    disk);
312	}
313
314	return (EXIT_SUCCESS);
315}
316
317static int
318locate(int argc, char **argv)
319{
320
321	return (sesled(argc, argv, false));
322}
323
324static int
325fault(int argc, char **argv)
326{
327
328	return (sesled(argc, argv, true));
329}
330
331static void
332sesutil_print(int *style, const char *fmt, ...)
333{
334	va_list args;
335
336	if (*style == PRINT_STYLE_DASHED) {
337		xo_open_container("extra_status");
338		xo_emit("\t\tExtra status:\n");
339		*style = PRINT_STYLE_DASHED_2;
340	} else if (*style == PRINT_STYLE_CSV) {
341		xo_open_container("extra_status");
342		*style = PRINT_STYLE_CSV_2;
343	}
344
345	if (*style == PRINT_STYLE_DASHED_2)
346		xo_emit("\t\t- ");
347	else if (*style == PRINT_STYLE_CSV_2)
348		xo_emit(", ");
349	va_start(args, fmt);
350	xo_emit_hv(NULL, fmt, args);
351	va_end(args);
352	if (*style == PRINT_STYLE_DASHED_2)
353		xo_emit("\n");
354}
355
356static void
357print_extra_status(int eletype, u_char *cstat, int style)
358{
359
360	if (cstat[0] & 0x40) {
361		sesutil_print(&style, "{e:predicted_failure/true} Predicted Failure");
362	}
363	if (cstat[0] & 0x20) {
364		sesutil_print(&style, "{e:disabled/true} Disabled");
365	}
366	if (cstat[0] & 0x10) {
367		sesutil_print(&style, "{e:swapped/true} Swapped");
368	}
369	switch (eletype) {
370	case ELMTYP_DEVICE:
371	case ELMTYP_ARRAY_DEV:
372		if (cstat[2] & 0x02) {
373			sesutil_print(&style, "LED={q:led/locate}");
374		}
375		if (cstat[2] & 0x20) {
376			sesutil_print(&style, "LED={q:led/fault}");
377		}
378		break;
379	case ELMTYP_FAN:
380		sesutil_print(&style, "Speed: {:speed/%d}{Uw:rpm}",
381		    (((0x7 & cstat[1]) << 8) + cstat[2]) * 10);
382		break;
383	case ELMTYP_THERM:
384		if (cstat[2]) {
385			sesutil_print(&style, "Temperature: {:temperature/%d}{Uw:C}",
386			    cstat[2] - TEMPERATURE_OFFSET);
387		} else {
388			sesutil_print(&style, "Temperature: -{q:temperature/reserved}");
389		}
390		break;
391	case ELMTYP_VOM:
392		sesutil_print(&style, "Voltage: {:voltage/%.2f}{Uw:V}",
393		    be16dec(cstat + 2) / 100.0);
394		break;
395	}
396	if (style) {
397		xo_close_container("extra_status");
398	}
399}
400
401static int
402objmap(int argc, char **argv __unused)
403{
404	encioc_string_t stri;
405	encioc_elm_devnames_t e_devname;
406	encioc_elm_status_t e_status;
407	encioc_elm_desc_t e_desc;
408	encioc_element_t *e_ptr;
409	glob_t g;
410	int fd;
411	unsigned int j, nobj;
412	size_t i;
413	char str[32];
414
415	if (argc != 1) {
416		usage(stderr, "map");
417	}
418
419	/* Get the list of ses devices */
420	if (glob(uflag, 0, NULL, &g) == GLOB_NOMATCH) {
421		globfree(&g);
422		xo_errx(EXIT_FAILURE, "No SES devices found");
423	}
424	xo_set_version(SESUTIL_XO_VERSION);
425	xo_open_container("sesutil");
426	xo_open_list("enclosures");
427	for (i = 0; i < g.gl_pathc; i++) {
428		/* ensure we only got numbers after ses */
429		if (strspn(g.gl_pathv[i] + 8, "0123456789") !=
430		    strlen(g.gl_pathv[i] + 8)) {
431			continue;
432		}
433		if ((fd = open(g.gl_pathv[i], O_RDWR)) < 0) {
434			/*
435			 * Don't treat non-access errors as critical if we are
436			 * accessing all devices
437			 */
438			if (errno == EACCES && g.gl_pathc > 1) {
439				xo_err(EXIT_FAILURE, "unable to access SES device");
440			}
441			xo_warn("unable to access SES device: %s", g.gl_pathv[i]);
442			continue;
443		}
444
445		if (ioctl(fd, ENCIOC_GETNELM, (caddr_t) &nobj) < 0) {
446			close(fd);
447			xo_err(EXIT_FAILURE, "ENCIOC_GETNELM");
448		}
449
450		e_ptr = calloc(nobj, sizeof(encioc_element_t));
451		if (e_ptr == NULL) {
452			close(fd);
453			xo_err(EXIT_FAILURE, "calloc()");
454		}
455
456		if (ioctl(fd, ENCIOC_GETELMMAP, (caddr_t) e_ptr) < 0) {
457			close(fd);
458			xo_err(EXIT_FAILURE, "ENCIOC_GETELMMAP");
459		}
460
461		xo_open_instance("enclosures");
462		xo_emit("{t:enc/%s}:\n", g.gl_pathv[i] + 5);
463		stri.bufsiz = sizeof(str);
464		stri.buf = &str[0];
465		if (ioctl(fd, ENCIOC_GETENCNAME, (caddr_t) &stri) == 0)
466			xo_emit("\tEnclosure Name: {t:name/%s}\n", stri.buf);
467		stri.bufsiz = sizeof(str);
468		stri.buf = &str[0];
469		if (ioctl(fd, ENCIOC_GETENCID, (caddr_t) &stri) == 0)
470			xo_emit("\tEnclosure ID: {t:id/%s}\n", stri.buf);
471
472		xo_open_list("elements");
473		for (j = 0; j < nobj; j++) {
474			/* Get the status of the element */
475			memset(&e_status, 0, sizeof(e_status));
476			e_status.elm_idx = e_ptr[j].elm_idx;
477			if (ioctl(fd, ENCIOC_GETELMSTAT,
478			    (caddr_t) &e_status) < 0) {
479				close(fd);
480				xo_err(EXIT_FAILURE, "ENCIOC_GETELMSTAT");
481			}
482			/* Get the description of the element */
483			memset(&e_desc, 0, sizeof(e_desc));
484			e_desc.elm_idx = e_ptr[j].elm_idx;
485			e_desc.elm_desc_len = UINT16_MAX;
486			e_desc.elm_desc_str = calloc(UINT16_MAX, sizeof(char));
487			if (e_desc.elm_desc_str == NULL) {
488				close(fd);
489				xo_err(EXIT_FAILURE, "calloc()");
490			}
491			if (ioctl(fd, ENCIOC_GETELMDESC,
492			    (caddr_t) &e_desc) < 0) {
493				close(fd);
494				xo_err(EXIT_FAILURE, "ENCIOC_GETELMDESC");
495			}
496			/* Get the device name(s) of the element */
497			memset(&e_devname, 0, sizeof(e_devname));
498			e_devname.elm_idx = e_ptr[j].elm_idx;
499			e_devname.elm_names_size = 128;
500			e_devname.elm_devnames = calloc(128, sizeof(char));
501			if (e_devname.elm_devnames == NULL) {
502				close(fd);
503				xo_err(EXIT_FAILURE, "calloc()");
504			}
505			if (ioctl(fd, ENCIOC_GETELMDEVNAMES,
506			    (caddr_t) &e_devname) <0) {
507				/* We don't care if this fails */
508				e_devname.elm_devnames[0] = '\0';
509			}
510			xo_open_instance("elements");
511			xo_emit("\tElement {:id/%u}, Type: {:type/%s}\n", e_ptr[j].elm_idx,
512			    geteltnm(e_ptr[j].elm_type));
513			xo_emit("\t\tStatus: {:status/%s} ({q:status_code/0x%02x 0x%02x 0x%02x 0x%02x})\n",
514			    scode2ascii(e_status.cstat[0]), e_status.cstat[0],
515			    e_status.cstat[1], e_status.cstat[2],
516			    e_status.cstat[3]);
517			if (e_desc.elm_desc_len > 0) {
518				xo_emit("\t\tDescription: {:description/%s}\n",
519				    e_desc.elm_desc_str);
520			}
521			if (e_devname.elm_names_len > 0) {
522				xo_emit("\t\tDevice Names: {:device_names/%s}\n",
523				    e_devname.elm_devnames);
524			}
525			print_extra_status(e_ptr[j].elm_type, e_status.cstat, PRINT_STYLE_DASHED);
526			xo_close_instance("elements");
527			free(e_devname.elm_devnames);
528		}
529		xo_close_list("elements");
530		free(e_ptr);
531		close(fd);
532	}
533	globfree(&g);
534	xo_close_list("enclosures");
535	xo_close_container("sesutil");
536	xo_finish();
537
538	return (EXIT_SUCCESS);
539}
540
541/*
542 * Get rid of the 'passN' devices, unless there's nothing else to show.
543 */
544static void
545skip_pass_devices(char *devnames, size_t devnameslen)
546{
547	char *dev, devs[128], passes[128], *tmp;
548
549	devs[0] = passes[0] = '\0';
550	tmp = devnames;
551
552	while ((dev = strsep(&tmp, ",")) != NULL) {
553		if (strncmp(dev, "pass", 4) == 0) {
554			if (passes[0] != '\0')
555				strlcat(passes, ",", sizeof(passes));
556			strlcat(passes, dev, sizeof(passes));
557		} else {
558			if (devs[0] != '\0')
559				strlcat(devs, ",", sizeof(devs));
560			strlcat(devs, dev, sizeof(devs));
561		}
562	}
563	strlcpy(devnames, devs, devnameslen);
564	if (devnames[0] == '\0')
565		strlcpy(devnames, passes, devnameslen);
566}
567
568static void
569fetch_device_details(char *devnames, char **model, char **serial, off_t *size)
570{
571	char ident[DISK_IDENT_SIZE];
572	struct diocgattr_arg arg;
573	char *device, *tmp;
574	off_t mediasize;
575	int fd;
576
577	tmp = strdup(devnames);
578	if (tmp == NULL)
579		err(1, "strdup");
580
581	device = strsep(&tmp, ",");
582	asprintf(&tmp, "/dev/%s", device);
583	fd = open(tmp, O_RDONLY);
584	if (fd < 0) {
585		/*
586		 * This can happen with a disk so broken it cannot
587		 * be probed by GEOM.
588		 */
589		*model = strdup("?");
590		*serial = strdup("?");
591		*size = -1;
592		return;
593	}
594
595	strlcpy(arg.name, "GEOM::descr", sizeof(arg.name));
596	arg.len = sizeof(arg.value.str);
597	if (ioctl(fd, DIOCGATTR, &arg) == 0)
598		*model = strdup(arg.value.str);
599	else
600		*model = NULL;
601
602	if (ioctl(fd, DIOCGIDENT, ident) == 0)
603		*serial = strdup(ident);
604	else
605		*serial = NULL;
606
607	if (ioctl(fd, DIOCGMEDIASIZE, &mediasize) == 0)
608		*size = mediasize;
609	else
610		*size = -1;
611}
612
613static void
614show_device(int fd, int elm_idx, encioc_elm_status_t e_status, encioc_elm_desc_t e_desc)
615{
616	encioc_elm_devnames_t e_devname;
617	char *model, *serial;
618	off_t size;
619
620	/* Get the device name(s) of the element */
621	memset(&e_devname, 0, sizeof(e_devname));
622	e_devname.elm_idx = elm_idx;
623	e_devname.elm_names_size = 128;
624	e_devname.elm_devnames = calloc(128, sizeof(char));
625	if (e_devname.elm_devnames == NULL) {
626		close(fd);
627		xo_err(EXIT_FAILURE, "calloc()");
628	}
629
630	if (ioctl(fd, ENCIOC_GETELMDEVNAMES,
631	    (caddr_t) &e_devname) < 0) {
632		/* We don't care if this fails */
633		e_devname.elm_devnames[0] = '\0';
634		model = NULL;
635		serial = NULL;
636		size = -1;
637	} else {
638		skip_pass_devices(e_devname.elm_devnames, 128);
639		fetch_device_details(e_devname.elm_devnames, &model, &serial, &size);
640	}
641	xo_open_instance("elements");
642	xo_emit("{e:type/device_slot}");
643	xo_emit("{d:description/%-8s} ", e_desc.elm_desc_len > 0 ? e_desc.elm_desc_str : "-");
644	xo_emit("{e:description/%-8s}", e_desc.elm_desc_len > 0 ? e_desc.elm_desc_str : "");
645	xo_emit("{d:device_names/%-7s} ", e_devname.elm_names_len > 0 ? e_devname.elm_devnames : "-");
646	xo_emit("{e:device_names/%s}", e_devname.elm_names_len > 0 ? e_devname.elm_devnames : "");
647	xo_emit("{d:model/%-25s} ", model ? model : "-");
648	xo_emit("{e:model/%s}", model ? model : "");
649	xo_emit("{d:serial/%-20s} ", serial != NULL ? serial : "-");
650	xo_emit("{e:serial/%s}", serial != NULL ? serial : "");
651	if (e_status.cstat[0] == SES_OBJSTAT_OK && size >= 0) {
652		xo_emit("{h,hn-1000:size/%ld}{e:status/%s}",
653		    size, scode2ascii(e_status.cstat[0]));
654	} else {
655		xo_emit("{:status/%s}", scode2ascii(e_status.cstat[0]));
656	}
657	print_extra_status(ELMTYP_ARRAY_DEV, e_status.cstat, PRINT_STYLE_CSV);
658	xo_emit("\n");
659	xo_close_instance("elements");
660	free(e_devname.elm_devnames);
661}
662
663static void
664show_therm(encioc_elm_status_t e_status, encioc_elm_desc_t e_desc)
665{
666
667	if (e_desc.elm_desc_len <= 0) {
668		/* We don't have a label to display; might as well skip it. */
669		return;
670	}
671
672	if (e_status.cstat[2] == 0) {
673		/* No temperature to show. */
674		return;
675	}
676
677	xo_open_instance("elements");
678	xo_emit("{e:type/temperature_sensor}");
679	xo_emit("{:description/%s}: {:temperature/%d}{Uw:C}",
680	    e_desc.elm_desc_str, e_status.cstat[2] - TEMPERATURE_OFFSET);
681	xo_close_instance("elements");
682}
683
684static void
685show_vom(encioc_elm_status_t e_status, encioc_elm_desc_t e_desc)
686{
687
688	if (e_desc.elm_desc_len <= 0) {
689		/* We don't have a label to display; might as well skip it. */
690		return;
691	}
692
693	if (e_status.cstat[2] == 0) {
694		/* No voltage to show. */
695		return;
696	}
697
698	xo_open_instance("elements");
699	xo_emit("{e:type/voltage_sensor}");
700	xo_emit("{:description/%s}: {:voltage/%.2f}{Uw:V}",
701	    e_desc.elm_desc_str, be16dec(e_status.cstat + 2) / 100.0);
702	xo_close_instance("elements");
703}
704
705static int
706show(int argc, char **argv __unused)
707{
708	encioc_string_t stri;
709	encioc_elm_status_t e_status;
710	encioc_elm_desc_t e_desc;
711	encioc_element_t *e_ptr;
712	glob_t g;
713	elm_type_t prev_type;
714	int fd;
715	unsigned int j, nobj;
716	size_t i;
717	bool first_ses;
718	char str[32];
719
720	if (argc != 1) {
721		usage(stderr, "map");
722	}
723
724	first_ses = true;
725
726	/* Get the list of ses devices */
727	if (glob(uflag, 0, NULL, &g) == GLOB_NOMATCH) {
728		globfree(&g);
729		xo_errx(EXIT_FAILURE, "No SES devices found");
730	}
731	xo_set_version(SESUTIL_XO_VERSION);
732	xo_open_container("sesutil");
733	xo_open_list("enclosures");
734	for (i = 0; i < g.gl_pathc; i++) {
735		/* ensure we only got numbers after ses */
736		if (strspn(g.gl_pathv[i] + 8, "0123456789") !=
737		    strlen(g.gl_pathv[i] + 8)) {
738			continue;
739		}
740		if ((fd = open(g.gl_pathv[i], O_RDWR)) < 0) {
741			/*
742			 * Don't treat non-access errors as critical if we are
743			 * accessing all devices
744			 */
745			if (errno == EACCES && g.gl_pathc > 1) {
746				xo_err(EXIT_FAILURE, "unable to access SES device");
747			}
748			xo_warn("unable to access SES device: %s", g.gl_pathv[i]);
749			continue;
750		}
751
752		if (ioctl(fd, ENCIOC_GETNELM, (caddr_t) &nobj) < 0) {
753			close(fd);
754			xo_err(EXIT_FAILURE, "ENCIOC_GETNELM");
755		}
756
757		e_ptr = calloc(nobj, sizeof(encioc_element_t));
758		if (e_ptr == NULL) {
759			close(fd);
760			xo_err(EXIT_FAILURE, "calloc()");
761		}
762
763		if (ioctl(fd, ENCIOC_GETELMMAP, (caddr_t) e_ptr) < 0) {
764			close(fd);
765			xo_err(EXIT_FAILURE, "ENCIOC_GETELMMAP");
766		}
767
768		xo_open_instance("enclosures");
769
770		if (first_ses)
771			first_ses = false;
772		else
773			xo_emit("\n");
774
775		xo_emit("{t:enc/%s}: ", g.gl_pathv[i] + 5);
776		stri.bufsiz = sizeof(str);
777		stri.buf = &str[0];
778		if (ioctl(fd, ENCIOC_GETENCNAME, (caddr_t) &stri) == 0)
779			xo_emit("<{t:name/%s}>; ", stri.buf);
780		stri.bufsiz = sizeof(str);
781		stri.buf = &str[0];
782		if (ioctl(fd, ENCIOC_GETENCID, (caddr_t) &stri) == 0)
783			xo_emit("ID: {t:id/%s}", stri.buf);
784		xo_emit("\n");
785
786		xo_open_list("elements");
787		prev_type = -1;
788		for (j = 0; j < nobj; j++) {
789			/* Get the status of the element */
790			memset(&e_status, 0, sizeof(e_status));
791			e_status.elm_idx = e_ptr[j].elm_idx;
792			if (ioctl(fd, ENCIOC_GETELMSTAT,
793			    (caddr_t) &e_status) < 0) {
794				close(fd);
795				xo_err(EXIT_FAILURE, "ENCIOC_GETELMSTAT");
796			}
797
798			/*
799			 * Skip "Unsupported" elements; those usually precede
800			 * the actual device entries and are not particularly
801			 * interesting.
802			 */
803			if (e_status.cstat[0] == SES_OBJSTAT_UNSUPPORTED)
804				continue;
805
806			/* Get the description of the element */
807			memset(&e_desc, 0, sizeof(e_desc));
808			e_desc.elm_idx = e_ptr[j].elm_idx;
809			e_desc.elm_desc_len = UINT16_MAX;
810			e_desc.elm_desc_str = calloc(UINT16_MAX, sizeof(char));
811			if (e_desc.elm_desc_str == NULL) {
812				close(fd);
813				xo_err(EXIT_FAILURE, "calloc()");
814			}
815			if (ioctl(fd, ENCIOC_GETELMDESC,
816			    (caddr_t) &e_desc) < 0) {
817				close(fd);
818				xo_err(EXIT_FAILURE, "ENCIOC_GETELMDESC");
819			}
820
821			switch (e_ptr[j].elm_type) {
822			case ELMTYP_DEVICE:
823			case ELMTYP_ARRAY_DEV:
824				if (e_ptr[j].elm_type != prev_type)
825					xo_emit("Desc     Dev     Model                     Ident                Size/Status\n");
826
827				show_device(fd, e_ptr[j].elm_idx, e_status, e_desc);
828				prev_type = e_ptr[j].elm_type;
829				break;
830			case ELMTYP_THERM:
831				if (e_ptr[j].elm_type != prev_type)
832					xo_emit("\nTemperatures: ");
833				else
834					xo_emit(", ");
835				prev_type = e_ptr[j].elm_type;
836				show_therm(e_status, e_desc);
837				break;
838			case ELMTYP_VOM:
839				if (e_ptr[j].elm_type != prev_type)
840					xo_emit("\nVoltages: ");
841				else
842					xo_emit(", ");
843				prev_type = e_ptr[j].elm_type;
844				show_vom(e_status, e_desc);
845				break;
846			default:
847				/*
848				 * Ignore stuff not interesting to the user.
849				 */
850				break;
851			}
852		}
853		if (prev_type != (elm_type_t)-1 &&
854		    prev_type != ELMTYP_DEVICE && prev_type != ELMTYP_ARRAY_DEV)
855			xo_emit("\n");
856		xo_close_list("elements");
857		free(e_ptr);
858		close(fd);
859	}
860	globfree(&g);
861	xo_close_list("enclosures");
862	xo_close_container("sesutil");
863	xo_finish();
864
865	return (EXIT_SUCCESS);
866}
867
868static int
869encstatus(int argc, char **argv __unused)
870{
871	glob_t g;
872	int fd, status;
873	size_t i, e;
874	u_char estat;
875
876	status = 0;
877	if (argc != 1) {
878		usage(stderr, "status");
879	}
880
881	/* Get the list of ses devices */
882	if (glob(uflag, 0, NULL, &g) == GLOB_NOMATCH) {
883		globfree(&g);
884		xo_errx(EXIT_FAILURE, "No SES devices found");
885	}
886
887	xo_set_version(SESUTIL_XO_VERSION);
888	xo_open_container("sesutil");
889	xo_open_list("enclosures");
890	for (i = 0; i < g.gl_pathc; i++) {
891		/* ensure we only got numbers after ses */
892		if (strspn(g.gl_pathv[i] + 8, "0123456789") !=
893		    strlen(g.gl_pathv[i] + 8)) {
894			continue;
895		}
896		if ((fd = open(g.gl_pathv[i], O_RDWR)) < 0) {
897			/*
898			 * Don't treat non-access errors as critical if we are
899			 * accessing all devices
900			 */
901			if (errno == EACCES && g.gl_pathc > 1) {
902				xo_err(EXIT_FAILURE, "unable to access SES device");
903			}
904			xo_warn("unable to access SES device: %s", g.gl_pathv[i]);
905			continue;
906		}
907
908		if (ioctl(fd, ENCIOC_GETENCSTAT, (caddr_t) &estat) < 0) {
909			xo_err(EXIT_FAILURE, "ENCIOC_GETENCSTAT");
910			close(fd);
911		}
912
913		xo_open_instance("enclosures");
914		xo_emit("{:enc/%s}: ", g.gl_pathv[i] + 5);
915		e = 0;
916		if (estat == 0) {
917			if (status == 0) {
918				status = 1;
919			}
920			xo_emit("{q:status/OK}");
921		} else {
922			if (estat & SES_ENCSTAT_INFO) {
923				xo_emit("{lq:status/INFO}");
924				e++;
925			}
926			if (estat & SES_ENCSTAT_NONCRITICAL) {
927				if (e)
928					xo_emit(",");
929				xo_emit("{lq:status/NONCRITICAL}");
930				e++;
931			}
932			if (estat & SES_ENCSTAT_CRITICAL) {
933				if (e)
934					xo_emit(",");
935				xo_emit("{lq:status/CRITICAL}");
936				e++;
937				status = -1;
938			}
939			if (estat & SES_ENCSTAT_UNRECOV) {
940				if (e)
941					xo_emit(",");
942				xo_emit("{lq:status/UNRECOV}");
943				e++;
944				status = -1;
945			}
946		}
947		xo_close_instance("enclosures");
948		xo_emit("\n");
949		close(fd);
950	}
951	globfree(&g);
952
953	xo_close_list("enclosures");
954	xo_close_container("sesutil");
955	xo_finish();
956
957	if (status == 1) {
958		return (EXIT_SUCCESS);
959	} else {
960		return (EXIT_FAILURE);
961	}
962}
963
964int
965main(int argc, char **argv)
966{
967	int i, ch;
968	struct command *cmd = NULL;
969
970	argc = xo_parse_args(argc, argv);
971	if (argc < 0)
972		exit(1);
973
974	uflag = "/dev/ses[0-9]*";
975	while ((ch = getopt_long(argc, argv, "u:", NULL, NULL)) != -1) {
976		switch (ch) {
977		case 'u':
978			uflag = optarg;
979			break;
980		case '?':
981		default:
982			usage(stderr, NULL);
983		}
984	}
985	argc -= optind;
986	argv += optind;
987
988	if (argc < 1) {
989		warnx("Missing command");
990		usage(stderr, NULL);
991	}
992
993	for (i = 0; i < nbcmds; i++) {
994		if (strcmp(argv[0], cmds[i].name) == 0) {
995			cmd = &cmds[i];
996			break;
997		}
998	}
999
1000	if (cmd == NULL) {
1001		warnx("unknown command %s", argv[0]);
1002		usage(stderr, NULL);
1003	}
1004
1005	return (cmd->exec(argc, argv));
1006}
1007