xref: /netbsd-src/usr.sbin/envstat/envstat.c (revision 1b9578b8c2c1f848eeb16dabbfd7d1f0d9fdefbd)
1 /* $NetBSD: envstat.c,v 1.88 2011/06/07 17:24:32 pgoyette Exp $ */
2 
3 /*-
4  * Copyright (c) 2007, 2008 Juan Romero Pardines.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 #ifndef lint
30 __RCSID("$NetBSD: envstat.c,v 1.88 2011/06/07 17:24:32 pgoyette Exp $");
31 #endif /* not lint */
32 
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <stdbool.h>
36 #include <stdarg.h>
37 #include <stdint.h>
38 #include <string.h>
39 #include <unistd.h>
40 #include <fcntl.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <paths.h>
44 #include <syslog.h>
45 #include <sys/envsys.h>
46 #include <sys/ioctl.h>
47 #include <sys/types.h>
48 #include <sys/queue.h>
49 #include <prop/proplib.h>
50 
51 #include "envstat.h"
52 #include "prog_ops.h"
53 
54 #define ENVSYS_DFLAG	0x00000001	/* list registered devices */
55 #define ENVSYS_FFLAG	0x00000002	/* show temp in farenheit */
56 #define ENVSYS_LFLAG	0x00000004	/* list sensors */
57 #define ENVSYS_XFLAG	0x00000008	/* externalize dictionary */
58 #define ENVSYS_IFLAG 	0x00000010	/* skip invalid sensors */
59 #define ENVSYS_SFLAG	0x00000020	/* remove all properties set */
60 #define ENVSYS_TFLAG	0x00000040	/* make statistics */
61 #define ENVSYS_KFLAG	0x00000100	/* show temp in kelvin */
62 
63 /* Sensors */
64 typedef struct envsys_sensor {
65 	SIMPLEQ_ENTRY(envsys_sensor) entries;
66 	int32_t	cur_value;
67 	int32_t	max_value;
68 	int32_t	min_value;
69 	int32_t	critmin_value;
70 	int32_t	critmax_value;
71 	int32_t	warnmin_value;
72 	int32_t	warnmax_value;
73 	char	desc[ENVSYS_DESCLEN];
74 	char	type[ENVSYS_DESCLEN];
75 	char	drvstate[ENVSYS_DESCLEN];
76 	char	battcap[ENVSYS_DESCLEN];
77 	char 	dvname[ENVSYS_DESCLEN];
78 	bool	invalid;
79 	bool	visible;
80 	bool	percentage;
81 } *sensor_t;
82 
83 /* Sensor statistics */
84 typedef struct envsys_sensor_stats {
85 	SIMPLEQ_ENTRY(envsys_sensor_stats) entries;
86 	int32_t	max;
87 	int32_t	min;
88 	int32_t avg;
89 	char	desc[ENVSYS_DESCLEN];
90 } *sensor_stats_t;
91 
92 /* Device properties */
93 typedef struct envsys_dvprops {
94 	uint64_t	refresh_timo;
95 	/* more members could be added in the future */
96 } *dvprops_t;
97 
98 /* A simple queue to manage all sensors */
99 static SIMPLEQ_HEAD(, envsys_sensor) sensors_list =
100     SIMPLEQ_HEAD_INITIALIZER(sensors_list);
101 
102 /* A simple queue to manage statistics for all sensors */
103 static SIMPLEQ_HEAD(, envsys_sensor_stats) sensor_stats_list =
104     SIMPLEQ_HEAD_INITIALIZER(sensor_stats_list);
105 
106 static unsigned int 	interval, flags, width;
107 static char 		*mydevname, *sensors;
108 static bool 		statistics;
109 static u_int		header_passes;
110 
111 static int 		parse_dictionary(int);
112 static int 		send_dictionary(FILE *);
113 static int 		find_sensors(prop_array_t, const char *, dvprops_t);
114 static void 		print_sensors(void);
115 static int 		check_sensors(char *);
116 static int 		usage(void);
117 
118 static int		sysmonfd; /* fd of /dev/sysmon */
119 
120 int main(int argc, char **argv)
121 {
122 	prop_dictionary_t dict;
123 	int c, rval = 0;
124 	char *endptr, *configfile = NULL;
125 	FILE *cf;
126 
127 	if (prog_init && prog_init() == -1)
128 		err(1, "init failed");
129 
130 	setprogname(argv[0]);
131 
132 	while ((c = getopt(argc, argv, "c:Dd:fIi:klrSs:Tw:Wx")) != -1) {
133 		switch (c) {
134 		case 'c':	/* configuration file */
135 			configfile = strdup(optarg);
136 			if (configfile == NULL)
137 				err(EXIT_FAILURE, "strdup");
138 			break;
139 		case 'D':	/* list registered devices */
140 			flags |= ENVSYS_DFLAG;
141 			break;
142 		case 'd':	/* show sensors of a specific device */
143 			mydevname = strdup(optarg);
144 			if (mydevname == NULL)
145 				err(EXIT_FAILURE, "strdup");
146 			break;
147 		case 'f':	/* display temperature in Farenheit */
148 			flags |= ENVSYS_FFLAG;
149 			break;
150 		case 'I':	/* Skips invalid sensors */
151 			flags |= ENVSYS_IFLAG;
152 			break;
153 		case 'i':	/* wait time between intervals */
154 			interval = (unsigned int)strtoul(optarg, &endptr, 10);
155 			if (*endptr != '\0')
156 				errx(EXIT_FAILURE, "bad interval '%s'", optarg);
157 			break;
158 		case 'k':	/* display temperature in Kelvin */
159 			flags |= ENVSYS_KFLAG;
160 			break;
161 		case 'l':	/* list sensors */
162 			flags |= ENVSYS_LFLAG;
163 			break;
164 		case 'r':
165 			/*
166 			 * This flag is noop.. it's only here for
167 			 * compatibility with the old implementation.
168 			 */
169 			break;
170 		case 'S':
171 			flags |= ENVSYS_SFLAG;
172 			break;
173 		case 's':	/* only show specified sensors */
174 			sensors = strdup(optarg);
175 			if (sensors == NULL)
176 				err(EXIT_FAILURE, "strdup");
177 			break;
178 		case 'T':	/* make statistics */
179 			flags |= ENVSYS_TFLAG;
180 			break;
181 		case 'w':	/* width value for the lines */
182 			width = (unsigned int)strtoul(optarg, &endptr, 10);
183 			if (*endptr != '\0')
184 				errx(EXIT_FAILURE, "bad width '%s'", optarg);
185 			break;
186 		case 'x':	/* print the dictionary in raw format */
187 			flags |= ENVSYS_XFLAG;
188 			break;
189 		case 'W':	/* No longer used, retained for campatability */
190 			break;
191 		case '?':
192 		default:
193 			usage();
194 			/* NOTREACHED */
195 		}
196 	}
197 
198 	argc -= optind;
199 	argv += optind;
200 
201 	if (argc > 0)
202 		usage();
203 
204 	/* Check if we want to make statistics */
205 	if (flags & ENVSYS_TFLAG) {
206 		if (!interval)
207 			errx(EXIT_FAILURE,
208 		    	    "-T cannot be used without an interval (-i)");
209 		else
210 			statistics = true;
211 	}
212 
213 	if (mydevname && sensors)
214 		errx(EXIT_FAILURE, "-d flag cannot be used with -s");
215 
216 	/* Open the device in ro mode */
217 	if ((sysmonfd = prog_open(_PATH_SYSMON, O_RDONLY)) == -1)
218 		err(EXIT_FAILURE, "%s", _PATH_SYSMON);
219 
220 	/* Print dictionary in raw mode */
221 	if (flags & ENVSYS_XFLAG) {
222 		rval = prop_dictionary_recv_ioctl(sysmonfd,
223 						  ENVSYS_GETDICTIONARY,
224 						  &dict);
225 		if (rval)
226 			errx(EXIT_FAILURE, "%s", strerror(rval));
227 
228 		config_dict_dump(dict);
229 
230 	/* Remove all properties set in dictionary */
231 	} else if (flags & ENVSYS_SFLAG) {
232 		/* Close the ro descriptor */
233 		(void)prog_close(sysmonfd);
234 
235 		/* open the fd in rw mode */
236 		if ((sysmonfd = prog_open(_PATH_SYSMON, O_RDWR)) == -1)
237 			err(EXIT_FAILURE, "%s", _PATH_SYSMON);
238 
239 		dict = prop_dictionary_create();
240 		if (!dict)
241 			err(EXIT_FAILURE, "prop_dictionary_create");
242 
243 		rval = prop_dictionary_set_bool(dict,
244 						"envsys-remove-props",
245 					        true);
246 		if (!rval)
247 			err(EXIT_FAILURE, "prop_dict_set_bool");
248 
249 		/* send the dictionary to the kernel now */
250 		rval = prop_dictionary_send_ioctl(dict, sysmonfd,
251 		    ENVSYS_REMOVEPROPS);
252 		if (rval)
253 			warnx("%s", strerror(rval));
254 
255 	/* Set properties in dictionary */
256 	} else if (configfile) {
257 		/*
258 		 * Parse the configuration file.
259 		 */
260 		if ((cf = fopen(configfile, "r")) == NULL) {
261 			syslog(LOG_ERR, "fopen failed: %s", strerror(errno));
262 			errx(EXIT_FAILURE, "%s", strerror(errno));
263 		}
264 
265 		rval = send_dictionary(cf);
266 		(void)fclose(cf);
267 
268 	/* Show sensors with interval */
269 	} else if (interval) {
270 		for (;;) {
271 			rval = parse_dictionary(sysmonfd);
272 			if (rval)
273 				break;
274 
275 			(void)fflush(stdout);
276 			(void)sleep(interval);
277 		}
278 	/* Show sensors without interval */
279 	} else {
280 		rval = parse_dictionary(sysmonfd);
281 	}
282 
283 	if (sensors)
284 		free(sensors);
285 	if (mydevname)
286 		free(mydevname);
287 	(void)prog_close(sysmonfd);
288 
289 	return rval ? EXIT_FAILURE : EXIT_SUCCESS;
290 }
291 
292 static int
293 send_dictionary(FILE *cf)
294 {
295 	prop_dictionary_t kdict, udict;
296 	int error = 0;
297 
298 	/* Retrieve dictionary from kernel */
299 	error = prop_dictionary_recv_ioctl(sysmonfd,
300 	    ENVSYS_GETDICTIONARY, &kdict);
301       	if (error)
302 		return error;
303 
304 	config_parse(cf, kdict);
305 
306 	/*
307 	 * Dictionary built by the parser from the configuration file.
308 	 */
309 	udict = config_dict_parsed();
310 
311 	/*
312 	 * Close the read only descriptor and open a new one read write.
313 	 */
314 	(void)prog_close(sysmonfd);
315 	if ((sysmonfd = prog_open(_PATH_SYSMON, O_RDWR)) == -1) {
316 		error = errno;
317 		warn("%s", _PATH_SYSMON);
318 		return error;
319 	}
320 
321 	/*
322 	 * Send our sensor properties dictionary to the kernel then.
323 	 */
324 	error = prop_dictionary_send_ioctl(udict,
325 	    sysmonfd, ENVSYS_SETDICTIONARY);
326 	if (error)
327 		warnx("%s", strerror(error));
328 
329 	prop_object_release(udict);
330 	return error;
331 }
332 
333 static sensor_stats_t
334 find_stats_sensor(const char *desc)
335 {
336 	sensor_stats_t stats;
337 
338 	/*
339 	 * If we matched a sensor by its description return it, otherwise
340 	 * allocate a new one.
341 	 */
342 	SIMPLEQ_FOREACH(stats, &sensor_stats_list, entries)
343 		if (strcmp(stats->desc, desc) == 0)
344 			return stats;
345 
346 	stats = calloc(1, sizeof(*stats));
347 	if (stats == NULL)
348 		return NULL;
349 
350 	(void)strlcpy(stats->desc, desc, sizeof(stats->desc));
351 	stats->min = INT32_MAX;
352 	stats->max = INT32_MIN;
353 	SIMPLEQ_INSERT_TAIL(&sensor_stats_list, stats, entries);
354 
355 	return stats;
356 }
357 
358 static int
359 parse_dictionary(int fd)
360 {
361 	sensor_t sensor = NULL;
362 	dvprops_t edp = NULL;
363 	prop_array_t array;
364 	prop_dictionary_t dict;
365 	prop_object_iterator_t iter;
366 	prop_object_t obj;
367 	const char *dnp = NULL;
368 	int rval = 0;
369 
370 	/* receive dictionary from kernel */
371 	rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict);
372 	if (rval)
373 		return rval;
374 
375 	/* No drivers registered? */
376 	if (prop_dictionary_count(dict) == 0) {
377 		warnx("no drivers registered");
378 		goto out;
379 	}
380 
381 	if (mydevname) {
382 		/* -d flag specified, print sensors only for this device */
383 		obj = prop_dictionary_get(dict, mydevname);
384 		if (prop_object_type(obj) != PROP_TYPE_ARRAY) {
385 			warnx("unknown device `%s'", mydevname);
386 			rval = EINVAL;
387 			goto out;
388 		}
389 
390 		rval = find_sensors(obj, mydevname, NULL);
391 		if (rval)
392 			goto out;
393 
394 	} else {
395 		/* print sensors for all devices registered */
396 		iter = prop_dictionary_iterator(dict);
397 		if (iter == NULL) {
398 			rval = EINVAL;
399 			goto out;
400 		}
401 
402 		/* iterate over the dictionary returned by the kernel */
403 		while ((obj = prop_object_iterator_next(iter)) != NULL) {
404 			array = prop_dictionary_get_keysym(dict, obj);
405 			if (prop_object_type(array) != PROP_TYPE_ARRAY) {
406 				warnx("no sensors found");
407 				rval = EINVAL;
408 				goto out;
409 			}
410 
411 			edp = calloc(1, sizeof(*edp));
412 			if (!edp) {
413 				rval = ENOMEM;
414 				goto out;
415 			}
416 
417 			dnp = prop_dictionary_keysym_cstring_nocopy(obj);
418 			rval = find_sensors(array, dnp, edp);
419 			if (rval)
420 				goto out;
421 
422 			if (((flags & ENVSYS_LFLAG) == 0) &&
423 			    (flags & ENVSYS_DFLAG)) {
424 				(void)printf("%s (checking events every ",
425 				    dnp);
426 				if (edp->refresh_timo == 1)
427 					(void)printf("second)\n");
428 				else
429 					(void)printf("%d seconds)\n",
430 					    (int)edp->refresh_timo);
431 			}
432 
433 			free(edp);
434 			edp = NULL;
435 		}
436 		prop_object_iterator_release(iter);
437 	}
438 
439 	/* print sensors now */
440 	if (sensors) {
441 		char *str = strdup(sensors);
442 		if (!str) {
443 			rval = ENOMEM;
444 			goto out;
445 		}
446 		rval = check_sensors(str);
447 		free(str);
448 	}
449 	if ((flags & ENVSYS_LFLAG) == 0 && (flags & ENVSYS_DFLAG) == 0)
450 		print_sensors();
451 	if (interval)
452 		(void)printf("\n");
453 
454 out:
455 	while ((sensor = SIMPLEQ_FIRST(&sensors_list))) {
456 		SIMPLEQ_REMOVE_HEAD(&sensors_list, entries);
457 		free(sensor);
458 	}
459 	if (edp)
460 		free(edp);
461 	prop_object_release(dict);
462 	return rval;
463 }
464 
465 static int
466 find_sensors(prop_array_t array, const char *dvname, dvprops_t edp)
467 {
468 	prop_object_iterator_t iter;
469 	prop_object_t obj, obj1, obj2;
470 	prop_string_t state, desc = NULL;
471 	sensor_t sensor = NULL;
472 	sensor_stats_t stats = NULL;
473 
474 	iter = prop_array_iterator(array);
475 	if (!iter)
476 		return ENOMEM;
477 
478 	/* iterate over the array of dictionaries */
479 	while ((obj = prop_object_iterator_next(iter)) != NULL) {
480 		/* get the refresh-timeout property */
481 		obj2 = prop_dictionary_get(obj, "device-properties");
482 		if (obj2) {
483 			if (!edp)
484 				continue;
485 			if (!prop_dictionary_get_uint64(obj2,
486 							"refresh-timeout",
487 							&edp->refresh_timo))
488 				continue;
489 		}
490 
491 		/* new sensor coming */
492 		sensor = calloc(1, sizeof(*sensor));
493 		if (sensor == NULL) {
494 			prop_object_iterator_release(iter);
495 			return ENOMEM;
496 		}
497 
498 		/* copy device name */
499 		(void)strlcpy(sensor->dvname, dvname, sizeof(sensor->dvname));
500 
501 		/* description string */
502 		desc = prop_dictionary_get(obj, "description");
503 		if (desc) {
504 			/* copy description */
505 			(void)strlcpy(sensor->desc,
506 			    prop_string_cstring_nocopy(desc),
507 		    	    sizeof(sensor->desc));
508 		} else {
509 			free(sensor);
510 			continue;
511 		}
512 
513 		/* type string */
514 		obj1  = prop_dictionary_get(obj, "type");
515 		if (obj1) {
516 			/* copy type */
517 			(void)strlcpy(sensor->type,
518 		    	    prop_string_cstring_nocopy(obj1),
519 		    	    sizeof(sensor->type));
520 		} else {
521 			free(sensor);
522 			continue;
523 		}
524 
525 		/* check sensor's state */
526 		state = prop_dictionary_get(obj, "state");
527 
528 		/* mark sensors with invalid/unknown state */
529 		if ((prop_string_equals_cstring(state, "invalid") ||
530 		     prop_string_equals_cstring(state, "unknown")))
531 			sensor->invalid = true;
532 
533 		/* get current drive state string */
534 		obj1 = prop_dictionary_get(obj, "drive-state");
535 		if (obj1) {
536 			(void)strlcpy(sensor->drvstate,
537 			    prop_string_cstring_nocopy(obj1),
538 			    sizeof(sensor->drvstate));
539 		}
540 
541 		/* get current battery capacity string */
542 		obj1 = prop_dictionary_get(obj, "battery-capacity");
543 		if (obj1) {
544 			(void)strlcpy(sensor->battcap,
545 			    prop_string_cstring_nocopy(obj1),
546 			    sizeof(sensor->battcap));
547 		}
548 
549 		/* get current value */
550 		obj1 = prop_dictionary_get(obj, "cur-value");
551 		if (obj1)
552 			sensor->cur_value = prop_number_integer_value(obj1);
553 
554 		/* get max value */
555 		obj1 = prop_dictionary_get(obj, "max-value");
556 		if (obj1)
557 			sensor->max_value = prop_number_integer_value(obj1);
558 
559 		/* get min value */
560 		obj1 = prop_dictionary_get(obj, "min-value");
561 		if (obj1)
562 			sensor->min_value = prop_number_integer_value(obj1);
563 
564 		/* get percentage flag */
565 		obj1 = prop_dictionary_get(obj, "want-percentage");
566 		if (obj1)
567 			sensor->percentage = prop_bool_true(obj1);
568 
569 		/* get critical max value if available */
570 		obj1 = prop_dictionary_get(obj, "critical-max");
571 		if (obj1)
572 			sensor->critmax_value = prop_number_integer_value(obj1);
573 
574 		/* get maximum capacity value if available */
575 		obj1 = prop_dictionary_get(obj, "maximum-capacity");
576 		if (obj1)
577 			sensor->critmax_value = prop_number_integer_value(obj1);
578 
579 		/* get critical min value if available */
580 		obj1 = prop_dictionary_get(obj, "critical-min");
581 		if (obj1)
582 			sensor->critmin_value = prop_number_integer_value(obj1);
583 
584 		/* get critical capacity value if available */
585 		obj1 = prop_dictionary_get(obj, "critical-capacity");
586 		if (obj1)
587 			sensor->critmin_value = prop_number_integer_value(obj1);
588 
589 		/* get warning max value if available */
590 		obj1 = prop_dictionary_get(obj, "warning-max");
591 		if (obj1)
592 			sensor->warnmax_value = prop_number_integer_value(obj1);
593 
594 		/* get high capacity value if available */
595 		obj1 = prop_dictionary_get(obj, "high-capacity");
596 		if (obj1)
597 			sensor->warnmax_value = prop_number_integer_value(obj1);
598 
599 		/* get warning min value if available */
600 		obj1 = prop_dictionary_get(obj, "warning-min");
601 		if (obj1)
602 			sensor->warnmin_value = prop_number_integer_value(obj1);
603 
604 		/* get warning capacity value if available */
605 		obj1 = prop_dictionary_get(obj, "warning-capacity");
606 		if (obj1)
607 			sensor->warnmin_value = prop_number_integer_value(obj1);
608 
609 		/* print sensor names if -l was given */
610 		if (flags & ENVSYS_LFLAG) {
611 			if (width)
612 				(void)printf("%*s\n", width,
613 				    prop_string_cstring_nocopy(desc));
614 			else
615 				(void)printf("%s\n",
616 				    prop_string_cstring_nocopy(desc));
617 		}
618 
619 		/* Add the sensor into the list */
620 		SIMPLEQ_INSERT_TAIL(&sensors_list, sensor, entries);
621 
622 		/* Collect statistics if flag enabled */
623 		if (statistics) {
624 			/* ignore sensors not relevant for statistics */
625 			if ((strcmp(sensor->type, "Indicator") == 0) ||
626 			    (strcmp(sensor->type, "Battery charge") == 0) ||
627 			    (strcmp(sensor->type, "Drive") == 0))
628 				continue;
629 
630 			/* ignore invalid data */
631 			if (sensor->invalid)
632 				continue;
633 
634 			/* find or allocate a new statistics sensor */
635 			stats = find_stats_sensor(sensor->desc);
636 			if (stats == NULL) {
637 				free(sensor);
638 				prop_object_iterator_release(iter);
639 				return ENOMEM;
640 			}
641 
642 			/* update data */
643 			if (sensor->cur_value > stats->max)
644 				stats->max = sensor->cur_value;
645 
646 			if (sensor->cur_value < stats->min)
647 				stats->min = sensor->cur_value;
648 
649 			/* compute avg value */
650 			stats->avg =
651 			    (sensor->cur_value + stats->max + stats->min) / 3;
652 		}
653 	}
654 
655 	/* free memory */
656 	prop_object_iterator_release(iter);
657 	return 0;
658 }
659 
660 static int
661 check_sensors(char *str)
662 {
663 	sensor_t sensor = NULL;
664 	char *dvstring, *sstring, *p, *last;
665 	bool sensor_found = false;
666 
667 	/*
668 	 * Parse device name and sensor description and find out
669 	 * if the sensor is valid.
670 	 */
671 	for ((p = strtok_r(str, ",", &last)); p;
672 	     (p = strtok_r(NULL, ",", &last))) {
673 		/* get device name */
674 		dvstring = strtok(p, ":");
675 		if (dvstring == NULL) {
676 			warnx("missing device name");
677 			return EINVAL;
678 		}
679 
680 		/* get sensor description */
681 		sstring = strtok(NULL, ":");
682 		if (sstring == NULL) {
683 			warnx("missing sensor description");
684 			return EINVAL;
685 		}
686 
687 		SIMPLEQ_FOREACH(sensor, &sensors_list, entries) {
688 			/* skip until we match device */
689 			if (strcmp(dvstring, sensor->dvname))
690 				continue;
691 			if (strcmp(sstring, sensor->desc) == 0) {
692 				sensor->visible = true;
693 				sensor_found = true;
694 				break;
695 			}
696 		}
697 		if (sensor_found == false) {
698 			warnx("unknown sensor `%s' for device `%s'",
699 		       	    sstring, dvstring);
700 			return EINVAL;
701 		}
702 		sensor_found = false;
703 	}
704 
705 	/* check if all sensors were ok, and error out if not */
706 	SIMPLEQ_FOREACH(sensor, &sensors_list, entries)
707 		if (sensor->visible)
708 			return 0;
709 
710 	warnx("no sensors selected to display");
711 	return EINVAL;
712 }
713 
714 static void
715 print_sensors(void)
716 {
717 	sensor_t sensor;
718 	sensor_stats_t stats = NULL;
719 	size_t maxlen = 0, ilen;
720 	double temp = 0;
721 	const char *invalid = "N/A", *degrees, *tmpstr, *stype;
722 	const char *a, *b, *c, *d, *e, *units;
723 
724 	tmpstr = stype = d = e = NULL;
725 
726 	/* find the longest description */
727 	SIMPLEQ_FOREACH(sensor, &sensors_list, entries)
728 		if (strlen(sensor->desc) > maxlen)
729 			maxlen = strlen(sensor->desc);
730 
731 	if (width)
732 		maxlen = width;
733 
734 	/*
735 	 * Print a header at the bottom only once showing different
736 	 * members if the statistics flag is set or not.
737 	 *
738 	 * As bonus if -s is set, only print this header every 10 iterations
739 	 * to avoid redundancy... like vmstat(1).
740 	 */
741 
742 	a = "Current";
743 	units = "Unit";
744 	if (statistics) {
745 		b = "Max";
746 		c = "Min";
747 		d = "Avg";
748 	} else {
749 		b = "CritMax";
750 		c = "WarnMax";
751 		d = "WarnMin";
752 		e = "CritMin";
753 	}
754 
755 	if (!sensors || (!header_passes && sensors) ||
756 	    (header_passes == 10 && sensors)) {
757 		if (statistics)
758 			(void)printf("%s%*s  %9s %8s %8s %8s %6s\n",
759 			    mydevname ? "" : "  ", (int)maxlen,
760 			    "", a, b, c, d, units);
761 		else
762 			(void)printf("%s%*s  %9s %8s %8s %8s %8s %5s\n",
763 			    mydevname ? "" : "  ", (int)maxlen,
764 			    "", a, b, c, d, e, units);
765 		if (sensors && header_passes == 10)
766 			header_passes = 0;
767 	}
768 	if (sensors)
769 		header_passes++;
770 
771 	/* print the sensors */
772 	SIMPLEQ_FOREACH(sensor, &sensors_list, entries) {
773 		/* skip sensors that were not marked as visible */
774 		if (sensors && !sensor->visible)
775 			continue;
776 
777 		/* skip invalid sensors if -I is set */
778 		if ((flags & ENVSYS_IFLAG) && sensor->invalid)
779 			continue;
780 
781 		/* print device name */
782 		if (!mydevname) {
783 			if (tmpstr == NULL || strcmp(tmpstr, sensor->dvname))
784 				printf("[%s]\n", sensor->dvname);
785 
786 			tmpstr = sensor->dvname;
787 		}
788 
789 		/* find out the statistics sensor */
790 		if (statistics) {
791 			stats = find_stats_sensor(sensor->desc);
792 			if (stats == NULL) {
793 				/* No statistics for this sensor */
794 				continue;
795 			}
796 		}
797 
798 		/* print sensor description */
799 		(void)printf("%s%*.*s", mydevname ? "" : "  ", (int)maxlen,
800 		    (int)maxlen, sensor->desc);
801 
802 		/* print invalid string */
803 		if (sensor->invalid) {
804 			(void)printf(": %9s\n", invalid);
805 			continue;
806 		}
807 
808 		/*
809 		 * Indicator and Battery charge sensors.
810 		 */
811 		if ((strcmp(sensor->type, "Indicator") == 0) ||
812 		    (strcmp(sensor->type, "Battery charge") == 0)) {
813 
814 			(void)printf(":%10s", sensor->cur_value ? "ON" : "OFF");
815 
816 /* convert and print a temp value in degC, degF, or Kelvin */
817 #define PRINTTEMP(a)						\
818 do {								\
819 	if (a) {						\
820 		temp = ((a) / 1000000.0);			\
821 		if (flags & ENVSYS_FFLAG) {			\
822 			temp = temp * (9.0 / 5.0) - 459.67;	\
823 			degrees = "degF";			\
824 		} else if (flags & ENVSYS_KFLAG) {		\
825 			degrees = "K";				\
826 		} else {					\
827 			temp = temp - 273.15;			\
828 			degrees = "degC";			\
829 		}						\
830 		(void)printf("%*.3f ", (int)ilen, temp);	\
831 		ilen = 8;					\
832 	} else							\
833 		ilen += 9;					\
834 } while (/* CONSTCOND */ 0)
835 
836 		/* temperatures */
837 		} else if (strcmp(sensor->type, "Temperature") == 0) {
838 
839 			ilen = 10;
840 			degrees = "";
841 			(void)printf(":");
842 			PRINTTEMP(sensor->cur_value);
843 			stype = degrees;
844 
845 			if (statistics) {
846 				/* show statistics if flag set */
847 				PRINTTEMP(stats->max);
848 				PRINTTEMP(stats->min);
849 				PRINTTEMP(stats->avg);
850 				ilen += 2;
851 			} else {
852 				PRINTTEMP(sensor->critmax_value);
853 				PRINTTEMP(sensor->warnmax_value);
854 				PRINTTEMP(sensor->warnmin_value);
855 				PRINTTEMP(sensor->critmin_value);
856 			}
857 			(void)printf("%*s", (int)ilen - 4, stype);
858 #undef PRINTTEMP
859 
860 		/* fans */
861 		} else if (strcmp(sensor->type, "Fan") == 0) {
862 			stype = "RPM";
863 
864 			(void)printf(":%10u ", sensor->cur_value);
865 
866 			ilen = 8;
867 			if (statistics) {
868 				/* show statistics if flag set */
869 				(void)printf("%8u %8u %8u ",
870 				    stats->max, stats->min, stats->avg);
871 				ilen += 2;
872 			} else {
873 				if (sensor->critmax_value) {
874 					(void)printf("%*u ", (int)ilen,
875 					    sensor->critmax_value);
876 					ilen = 8;
877 				} else
878 					ilen += 9;
879 
880 				if (sensor->warnmax_value) {
881 					(void)printf("%*u ", (int)ilen,
882 					    sensor->warnmax_value);
883 					ilen = 8;
884 				} else
885 					ilen += 9;
886 
887 				if (sensor->warnmin_value) {
888 					(void)printf("%*u ", (int)ilen,
889 					    sensor->warnmin_value);
890 					ilen = 8;
891 				} else
892 					ilen += 9;
893 
894 				if (sensor->critmin_value) {
895 					(void)printf( "%*u ", (int)ilen,
896 					    sensor->critmin_value);
897 					ilen = 8;
898 				} else
899 					ilen += 9;
900 
901 			}
902 
903 			(void)printf("%*s", (int)ilen - 4, stype);
904 
905 		/* integers */
906 		} else if (strcmp(sensor->type, "Integer") == 0) {
907 
908 			stype = "none";
909 
910 			(void)printf(":%10d ", sensor->cur_value);
911 
912 			ilen = 8;
913 
914 /* Print percentage of max_value */
915 #define PRINTPCT(a)							\
916 do {									\
917 	if (sensor->max_value) {					\
918 		(void)printf("%*.3f%%", (int)ilen,			\
919 			((a) * 100.0) / sensor->max_value);		\
920 		ilen = 8;						\
921 	} else								\
922 		ilen += 9;						\
923 } while ( /* CONSTCOND*/ 0 )
924 
925 /* Print an integer sensor value */
926 #define PRINTINT(a)							\
927 do {									\
928 	(void)printf("%*u ", (int)ilen, (a));				\
929 	ilen = 8;							\
930 } while ( /* CONSTCOND*/ 0 )
931 
932 			if (!statistics) {
933 				if (sensor->percentage) {
934 					PRINTPCT(sensor->critmax_value);
935 					PRINTPCT(sensor->warnmax_value);
936 					PRINTPCT(sensor->warnmin_value);
937 					PRINTPCT(sensor->critmin_value);
938 				} else {
939 					PRINTINT(sensor->critmax_value);
940 					PRINTINT(sensor->warnmax_value);
941 					PRINTINT(sensor->warnmin_value);
942 					PRINTINT(sensor->critmin_value);
943 				}
944 			} else {
945 				if (sensor->percentage) {
946 					PRINTPCT(stats->max);
947 					PRINTPCT(stats->min);
948 					PRINTPCT(stats->avg);
949 				} else {
950 					PRINTINT(stats->max);
951 					PRINTINT(stats->min);
952 					PRINTINT(stats->avg);
953 				}
954 				ilen += 2;
955 			}
956 
957 			(void)printf("%*s", (int)ilen - 4, stype);
958 
959 #undef PRINTINT
960 #undef PRINTPCT
961 
962 		/* drives  */
963 		} else if (strcmp(sensor->type, "Drive") == 0) {
964 
965 			(void)printf(":%10s", sensor->drvstate);
966 
967 		/* Battery capacity */
968 		} else if (strcmp(sensor->type, "Battery capacity") == 0) {
969 
970 			(void)printf(":%10s", sensor->battcap);
971 
972 		/* everything else */
973 		} else {
974 			if (strcmp(sensor->type, "Voltage DC") == 0)
975 				stype = "V";
976 			else if (strcmp(sensor->type, "Voltage AC") == 0)
977 				stype = "VAC";
978 			else if (strcmp(sensor->type, "Ampere") == 0)
979 				stype = "A";
980 			else if (strcmp(sensor->type, "Watts") == 0)
981 				stype = "W";
982 			else if (strcmp(sensor->type, "Ohms") == 0)
983 				stype = "Ohms";
984 			else if (strcmp(sensor->type, "Watt hour") == 0)
985 				stype = "Wh";
986 			else if (strcmp(sensor->type, "Ampere hour") == 0)
987 				stype = "Ah";
988 			else
989 				stype = "?";
990 
991 			(void)printf(":%10.3f ",
992 			    sensor->cur_value / 1000000.0);
993 
994 			ilen = 8;
995 
996 /* Print percentage of max_value */
997 #define PRINTPCT(a)							\
998 do {									\
999 	if ((a) && sensor->max_value) {					\
1000 		(void)printf("%*.3f%%", (int)ilen,			\
1001 			((a) * 100.0) / sensor->max_value);		\
1002 		ilen = 8;						\
1003 	} else								\
1004 		ilen += 9;						\
1005 } while ( /* CONSTCOND*/ 0 )
1006 
1007 /* Print a generic sensor value */
1008 #define PRINTVAL(a)							\
1009 do {									\
1010 	if ((a)) {							\
1011 		(void)printf("%*.3f ", (int)ilen, (a) / 1000000.0);	\
1012 		ilen = 8;						\
1013 	} else								\
1014 		ilen += 9;						\
1015 } while ( /* CONSTCOND*/ 0 )
1016 
1017 			if (!statistics) {
1018 				if (sensor->percentage) {
1019 					PRINTPCT(sensor->critmax_value);
1020 					PRINTPCT(sensor->warnmax_value);
1021 					PRINTPCT(sensor->warnmin_value);
1022 					PRINTPCT(sensor->critmin_value);
1023 				} else {
1024 
1025 					PRINTVAL(sensor->critmax_value);
1026 					PRINTVAL(sensor->warnmax_value);
1027 					PRINTVAL(sensor->warnmin_value);
1028 					PRINTVAL(sensor->critmin_value);
1029 				}
1030 			} else {
1031 				if (sensor->percentage) {
1032 					PRINTPCT(stats->max);
1033 					PRINTPCT(stats->min);
1034 					PRINTPCT(stats->avg);
1035 				} else {
1036 					PRINTVAL(stats->max);
1037 					PRINTVAL(stats->min);
1038 					PRINTVAL(stats->avg);
1039 				}
1040 				ilen += 2;
1041 			}
1042 #undef PRINTPCT
1043 #undef PRINTVAL
1044 
1045 			(void)printf("%*s", (int)ilen - 3, stype);
1046 
1047 			if (sensor->percentage && sensor->max_value) {
1048 				(void)printf(" (%5.2f%%)",
1049 				    (sensor->cur_value * 100.0) /
1050 				    sensor->max_value);
1051 			}
1052 		}
1053 		(void)printf("\n");
1054 	}
1055 }
1056 
1057 static int
1058 usage(void)
1059 {
1060 	(void)fprintf(stderr, "Usage: %s [-DfIklrSTx] ", getprogname());
1061 	(void)fprintf(stderr, "[-c file] [-d device] [-i interval] ");
1062 	(void)fprintf(stderr, "[-s device:sensor,...] [-w width]\n");
1063 	exit(EXIT_FAILURE);
1064 	/* NOTREACHED */
1065 }
1066