xref: /netbsd-src/sys/dev/sysmon/sysmon_envsys.c (revision 7fb0f92c04844032d93e4861786a3caa0d753621)
1 /*	$NetBSD: sysmon_envsys.c,v 1.98 2010/03/24 12:15:54 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 /*-
29  * Copyright (c) 2000 Zembu Labs, Inc.
30  * All rights reserved.
31  *
32  * Author: Jason R. Thorpe <thorpej@zembu.com>
33  *
34  * Redistribution and use in source and binary forms, with or without
35  * modification, are permitted provided that the following conditions
36  * are met:
37  * 1. Redistributions of source code must retain the above copyright
38  *    notice, this list of conditions and the following disclaimer.
39  * 2. Redistributions in binary form must reproduce the above copyright
40  *    notice, this list of conditions and the following disclaimer in the
41  *    documentation and/or other materials provided with the distribution.
42  * 3. All advertising materials mentioning features or use of this software
43  *    must display the following acknowledgement:
44  *	This product includes software developed by Zembu Labs, Inc.
45  * 4. Neither the name of Zembu Labs nor the names of its employees may
46  *    be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY ZEMBU LABS, INC. ``AS IS'' AND ANY EXPRESS
50  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WAR-
51  * RANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DIS-
52  * CLAIMED.  IN NO EVENT SHALL ZEMBU LABS BE LIABLE FOR ANY DIRECT, INDIRECT,
53  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
54  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
55  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
56  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
57  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
58  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59  */
60 
61 /*
62  * Environmental sensor framework for sysmon, exported to userland
63  * with proplib(3).
64  */
65 
66 #include <sys/cdefs.h>
67 __KERNEL_RCSID(0, "$NetBSD: sysmon_envsys.c,v 1.98 2010/03/24 12:15:54 pgoyette Exp $");
68 
69 #include <sys/param.h>
70 #include <sys/types.h>
71 #include <sys/conf.h>
72 #include <sys/errno.h>
73 #include <sys/fcntl.h>
74 #include <sys/kernel.h>
75 #include <sys/systm.h>
76 #include <sys/proc.h>
77 #include <sys/mutex.h>
78 #include <sys/kmem.h>
79 
80 /* #define ENVSYS_DEBUG */
81 #include <dev/sysmon/sysmonvar.h>
82 #include <dev/sysmon/sysmon_envsysvar.h>
83 #include <dev/sysmon/sysmon_taskq.h>
84 
85 kmutex_t sme_global_mtx;
86 
87 static prop_dictionary_t sme_propd;
88 static uint32_t sysmon_envsys_next_sensor_index;
89 static struct sysmon_envsys *sysmon_envsys_find_40(u_int);
90 
91 static void sysmon_envsys_destroy_plist(prop_array_t);
92 static void sme_remove_userprops(void);
93 static int sme_add_property_dictionary(struct sysmon_envsys *, prop_array_t,
94 				       prop_dictionary_t);
95 static sme_event_drv_t * sme_add_sensor_dictionary(struct sysmon_envsys *,
96 	prop_array_t, prop_dictionary_t, envsys_data_t *);
97 static void sme_initial_refresh(void *);
98 static uint32_t sme_get_max_value(struct sysmon_envsys *,
99      bool (*)(const envsys_data_t*), bool);
100 
101 /*
102  * sysmon_envsys_init:
103  *
104  * 	+ Initialize global mutex, dictionary and the linked list.
105  */
106 void
107 sysmon_envsys_init(void)
108 {
109 	LIST_INIT(&sysmon_envsys_list);
110 	mutex_init(&sme_global_mtx, MUTEX_DEFAULT, IPL_NONE);
111 	sme_propd = prop_dictionary_create();
112 }
113 
114 /*
115  * sysmonopen_envsys:
116  *
117  *	+ Open the system monitor device.
118  */
119 int
120 sysmonopen_envsys(dev_t dev, int flag, int mode, struct lwp *l)
121 {
122 	return 0;
123 }
124 
125 /*
126  * sysmonclose_envsys:
127  *
128  *	+ Close the system monitor device.
129  */
130 int
131 sysmonclose_envsys(dev_t dev, int flag, int mode, struct lwp *l)
132 {
133 	return 0;
134 }
135 
136 /*
137  * sysmonioctl_envsys:
138  *
139  *	+ Perform a sysmon envsys control request.
140  */
141 int
142 sysmonioctl_envsys(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
143 {
144 	struct sysmon_envsys *sme = NULL;
145 	int error = 0;
146 	u_int oidx;
147 
148 	switch (cmd) {
149 	/*
150 	 * To update the global dictionary with latest data from devices.
151 	 */
152 	case ENVSYS_GETDICTIONARY:
153 	    {
154 		struct plistref *plist = (struct plistref *)data;
155 
156 		/*
157 		 * Update dictionaries on all sysmon envsys devices
158 		 * registered.
159 		 */
160 		mutex_enter(&sme_global_mtx);
161 		LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
162 			sysmon_envsys_acquire(sme, false);
163 			error = sme_update_dictionary(sme);
164 			if (error) {
165 				DPRINTF(("%s: sme_update_dictionary, "
166 				    "error=%d\n", __func__, error));
167 				sysmon_envsys_release(sme, false);
168 				mutex_exit(&sme_global_mtx);
169 				return error;
170 			}
171 			sysmon_envsys_release(sme, false);
172 		}
173 		mutex_exit(&sme_global_mtx);
174 		/*
175 		 * Copy global dictionary to userland.
176 		 */
177 		error = prop_dictionary_copyout_ioctl(plist, cmd, sme_propd);
178 		break;
179 	    }
180 	/*
181 	 * To set properties on multiple devices.
182 	 */
183 	case ENVSYS_SETDICTIONARY:
184 	    {
185 		const struct plistref *plist = (const struct plistref *)data;
186 		prop_dictionary_t udict;
187 		prop_object_iterator_t iter, iter2;
188 		prop_object_t obj, obj2;
189 		prop_array_t array_u, array_k;
190 		const char *devname = NULL;
191 
192 		if ((flag & FWRITE) == 0)
193 			return EPERM;
194 
195 		/*
196 		 * Get dictionary from userland.
197 		 */
198 		error = prop_dictionary_copyin_ioctl(plist, cmd, &udict);
199 		if (error) {
200 			DPRINTF(("%s: copyin_ioctl error=%d\n",
201 			    __func__, error));
202 			break;
203 		}
204 
205 		iter = prop_dictionary_iterator(udict);
206 		if (!iter) {
207 			prop_object_release(udict);
208 			return ENOMEM;
209 		}
210 
211 		/*
212 		 * Iterate over the userland dictionary and process
213 		 * the list of devices.
214 		 */
215 		while ((obj = prop_object_iterator_next(iter))) {
216 			array_u = prop_dictionary_get_keysym(udict, obj);
217 			if (prop_object_type(array_u) != PROP_TYPE_ARRAY) {
218 				prop_object_iterator_release(iter);
219 				prop_object_release(udict);
220 				return EINVAL;
221 			}
222 
223 			devname = prop_dictionary_keysym_cstring_nocopy(obj);
224 			DPRINTF(("%s: processing the '%s' array requests\n",
225 			    __func__, devname));
226 
227 			/*
228 			 * find the correct sme device.
229 			 */
230 			sme = sysmon_envsys_find(devname);
231 			if (!sme) {
232 				DPRINTF(("%s: NULL sme\n", __func__));
233 				prop_object_iterator_release(iter);
234 				prop_object_release(udict);
235 				return EINVAL;
236 			}
237 
238 			/*
239 			 * Find the correct array object with the string
240 			 * supplied by the userland dictionary.
241 			 */
242 			array_k = prop_dictionary_get(sme_propd, devname);
243 			if (prop_object_type(array_k) != PROP_TYPE_ARRAY) {
244 				DPRINTF(("%s: array device failed\n",
245 				    __func__));
246 				sysmon_envsys_release(sme, false);
247 				prop_object_iterator_release(iter);
248 				prop_object_release(udict);
249 				return EINVAL;
250 			}
251 
252 			iter2 = prop_array_iterator(array_u);
253 			if (!iter2) {
254 				sysmon_envsys_release(sme, false);
255 				prop_object_iterator_release(iter);
256 				prop_object_release(udict);
257 				return ENOMEM;
258 			}
259 
260 			/*
261 			 * Iterate over the array of dictionaries to
262 			 * process the list of sensors and properties.
263 			 */
264 			while ((obj2 = prop_object_iterator_next(iter2))) {
265 				/*
266 				 * do the real work now.
267 				 */
268 				error = sme_userset_dictionary(sme,
269 							       obj2,
270 							       array_k);
271 				if (error) {
272 					sysmon_envsys_release(sme, false);
273 					prop_object_iterator_release(iter2);
274 					prop_object_iterator_release(iter);
275 					prop_object_release(udict);
276 					return error;
277 				}
278 			}
279 
280 			sysmon_envsys_release(sme, false);
281 			prop_object_iterator_release(iter2);
282 		}
283 
284 		prop_object_iterator_release(iter);
285 		prop_object_release(udict);
286 		break;
287 	    }
288 	/*
289 	 * To remove all properties from all devices registered.
290 	 */
291 	case ENVSYS_REMOVEPROPS:
292 	    {
293 		const struct plistref *plist = (const struct plistref *)data;
294 		prop_dictionary_t udict;
295 		prop_object_t obj;
296 
297 		if ((flag & FWRITE) == 0)
298 			return EPERM;
299 
300 		error = prop_dictionary_copyin_ioctl(plist, cmd, &udict);
301 		if (error) {
302 			DPRINTF(("%s: copyin_ioctl error=%d\n",
303 			    __func__, error));
304 			break;
305 		}
306 
307 		obj = prop_dictionary_get(udict, "envsys-remove-props");
308 		if (!obj || !prop_bool_true(obj)) {
309 			DPRINTF(("%s: invalid 'envsys-remove-props'\n",
310 			     __func__));
311 			return EINVAL;
312 		}
313 
314 		prop_object_release(udict);
315 		sme_remove_userprops();
316 
317 		break;
318 	    }
319 	/*
320 	 * Compatibility ioctls with the old interface, only implemented
321 	 * ENVSYS_GTREDATA and ENVSYS_GTREINFO; enough to make old
322 	 * applications work.
323 	 */
324 	case ENVSYS_GTREDATA:
325 	    {
326 		struct envsys_tre_data *tred = (void *)data;
327 		envsys_data_t *edata = NULL;
328 		bool found = false;
329 
330 		tred->validflags = 0;
331 
332 		sme = sysmon_envsys_find_40(tred->sensor);
333 		if (!sme)
334 			break;
335 
336 		oidx = tred->sensor;
337 		tred->sensor = SME_SENSOR_IDX(sme, tred->sensor);
338 
339 		DPRINTFOBJ(("%s: sensor=%d oidx=%d dev=%s nsensors=%d\n",
340 		    __func__, tred->sensor, oidx, sme->sme_name,
341 		    sme->sme_nsensors));
342 
343 		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
344 			if (edata->sensor == tred->sensor) {
345 				found = true;
346 				break;
347 			}
348 		}
349 
350 		if (!found) {
351 			sysmon_envsys_release(sme, false);
352 			error = ENODEV;
353 			break;
354 		}
355 
356 		if (tred->sensor < sme->sme_nsensors) {
357 			if ((sme->sme_flags & SME_DISABLE_REFRESH) == 0 &&
358 			    (sme->sme_flags & SME_POLL_ONLY) == 0) {
359 				mutex_enter(&sme->sme_mtx);
360 				(*sme->sme_refresh)(sme, edata);
361 				mutex_exit(&sme->sme_mtx);
362 			}
363 
364 			/*
365 			 * copy required values to the old interface.
366 			 */
367 			tred->sensor = edata->sensor;
368 			tred->cur.data_us = edata->value_cur;
369 			tred->cur.data_s = edata->value_cur;
370 			tred->max.data_us = edata->value_max;
371 			tred->max.data_s = edata->value_max;
372 			tred->min.data_us = edata->value_min;
373 			tred->min.data_s = edata->value_min;
374 			tred->avg.data_us = edata->value_avg;
375 			tred->avg.data_s = edata->value_avg;
376 			if (edata->units == ENVSYS_BATTERY_CHARGE)
377 				tred->units = ENVSYS_INDICATOR;
378 			else
379 				tred->units = edata->units;
380 
381 			tred->validflags |= ENVSYS_FVALID;
382 			tred->validflags |= ENVSYS_FCURVALID;
383 
384 			if (edata->flags & ENVSYS_FPERCENT) {
385 				tred->validflags |= ENVSYS_FMAXVALID;
386 				tred->validflags |= ENVSYS_FFRACVALID;
387 			}
388 
389 			if (edata->state == ENVSYS_SINVALID) {
390 				tred->validflags &= ~ENVSYS_FCURVALID;
391 				tred->cur.data_us = tred->cur.data_s = 0;
392 			}
393 
394 			DPRINTFOBJ(("%s: sensor=%s tred->cur.data_s=%d\n",
395 			    __func__, edata->desc, tred->cur.data_s));
396 			DPRINTFOBJ(("%s: tred->validflags=%d tred->units=%d"
397 			    " tred->sensor=%d\n", __func__, tred->validflags,
398 			    tred->units, tred->sensor));
399 		}
400 		tred->sensor = oidx;
401 		sysmon_envsys_release(sme, false);
402 
403 		break;
404 	    }
405 	case ENVSYS_GTREINFO:
406 	    {
407 		struct envsys_basic_info *binfo = (void *)data;
408 		envsys_data_t *edata = NULL;
409 		bool found = false;
410 
411 		binfo->validflags = 0;
412 
413 		sme = sysmon_envsys_find_40(binfo->sensor);
414 		if (!sme)
415 			break;
416 
417 		oidx = binfo->sensor;
418 		binfo->sensor = SME_SENSOR_IDX(sme, binfo->sensor);
419 
420 		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
421 			if (edata->sensor == binfo->sensor) {
422 				found = true;
423 				break;
424 			}
425 		}
426 
427 		if (!found) {
428 			sysmon_envsys_release(sme, false);
429 			error = ENODEV;
430 			break;
431 		}
432 
433 		binfo->validflags |= ENVSYS_FVALID;
434 
435 		if (binfo->sensor < sme->sme_nsensors) {
436 			if (edata->units == ENVSYS_BATTERY_CHARGE)
437 				binfo->units = ENVSYS_INDICATOR;
438 			else
439 				binfo->units = edata->units;
440 
441 			/*
442 			 * previously, the ACPI sensor names included the
443 			 * device name. Include that in compatibility code.
444 			 */
445 			if (strncmp(sme->sme_name, "acpi", 4) == 0)
446 				(void)snprintf(binfo->desc, sizeof(binfo->desc),
447 				    "%s %s", sme->sme_name, edata->desc);
448 			else
449 				(void)strlcpy(binfo->desc, edata->desc,
450 				    sizeof(binfo->desc));
451 		}
452 
453 		DPRINTFOBJ(("%s: binfo->units=%d binfo->validflags=%d\n",
454 		    __func__, binfo->units, binfo->validflags));
455 		DPRINTFOBJ(("%s: binfo->desc=%s binfo->sensor=%d\n",
456 		    __func__, binfo->desc, binfo->sensor));
457 
458 		binfo->sensor = oidx;
459 		sysmon_envsys_release(sme, false);
460 
461 		break;
462 	    }
463 	default:
464 		error = ENOTTY;
465 		break;
466 	}
467 
468 	return error;
469 }
470 
471 /*
472  * sysmon_envsys_create:
473  *
474  * 	+ Allocates a new sysmon_envsys object and initializes the
475  * 	  stuff for sensors and events.
476  */
477 struct sysmon_envsys *
478 sysmon_envsys_create(void)
479 {
480 	struct sysmon_envsys *sme;
481 
482 	sme = kmem_zalloc(sizeof(*sme), KM_SLEEP);
483 	TAILQ_INIT(&sme->sme_sensors_list);
484 	LIST_INIT(&sme->sme_events_list);
485 	mutex_init(&sme->sme_mtx, MUTEX_DEFAULT, IPL_NONE);
486 	cv_init(&sme->sme_condvar, "sme_wait");
487 
488 	return sme;
489 }
490 
491 /*
492  * sysmon_envsys_destroy:
493  *
494  * 	+ Removes all sensors from the tail queue, destroys the callout
495  * 	  and frees the sysmon_envsys object.
496  */
497 void
498 sysmon_envsys_destroy(struct sysmon_envsys *sme)
499 {
500 	envsys_data_t *edata;
501 
502 	KASSERT(sme != NULL);
503 
504 	while (!TAILQ_EMPTY(&sme->sme_sensors_list)) {
505 		edata = TAILQ_FIRST(&sme->sme_sensors_list);
506 		TAILQ_REMOVE(&sme->sme_sensors_list, edata, sensors_head);
507 	}
508 	mutex_destroy(&sme->sme_mtx);
509 	cv_destroy(&sme->sme_condvar);
510 	kmem_free(sme, sizeof(*sme));
511 }
512 
513 /*
514  * sysmon_envsys_sensor_attach:
515  *
516  * 	+ Attachs a sensor into a sysmon_envsys device checking that units
517  * 	  is set to a valid type and description is unique and not empty.
518  */
519 int
520 sysmon_envsys_sensor_attach(struct sysmon_envsys *sme, envsys_data_t *edata)
521 {
522 	const struct sme_description_table *sdt_units;
523 	envsys_data_t *oedata;
524 	int i;
525 
526 	KASSERT(sme != NULL || edata != NULL);
527 
528 	/*
529 	 * Find the correct units for this sensor.
530 	 */
531 	sdt_units = sme_get_description_table(SME_DESC_UNITS);
532 	for (i = 0; sdt_units[i].type != -1; i++)
533 		if (sdt_units[i].type == edata->units)
534 			break;
535 
536 	if (strcmp(sdt_units[i].desc, "unknown") == 0)
537 		return EINVAL;
538 
539 	/*
540 	 * Check that description is not empty or duplicate.
541 	 */
542 	if (strlen(edata->desc) == 0)
543 		return EINVAL;
544 
545 	mutex_enter(&sme->sme_mtx);
546 	sysmon_envsys_acquire(sme, true);
547 	TAILQ_FOREACH(oedata, &sme->sme_sensors_list, sensors_head) {
548 		if (strcmp(oedata->desc, edata->desc) == 0) {
549 			sysmon_envsys_release(sme, true);
550 			mutex_exit(&sme->sme_mtx);
551 			return EEXIST;
552 		}
553 	}
554 	/*
555 	 * Ok, the sensor has been added into the device queue.
556 	 */
557 	TAILQ_INSERT_TAIL(&sme->sme_sensors_list, edata, sensors_head);
558 
559 	/*
560 	 * Give the sensor a index position.
561 	 */
562 	edata->sensor = sme->sme_nsensors;
563 	sme->sme_nsensors++;
564 	sysmon_envsys_release(sme, true);
565 	mutex_exit(&sme->sme_mtx);
566 
567 	DPRINTF(("%s: attached #%d (%s), units=%d (%s)\n",
568 	    __func__, edata->sensor, edata->desc,
569 	    sdt_units[i].type, sdt_units[i].desc));
570 
571 	return 0;
572 }
573 
574 /*
575  * sysmon_envsys_sensor_detach:
576  *
577  * 	+ Detachs a sensor from a sysmon_envsys device and decrements the
578  * 	  sensors count on success.
579  */
580 int
581 sysmon_envsys_sensor_detach(struct sysmon_envsys *sme, envsys_data_t *edata)
582 {
583 	envsys_data_t *oedata;
584 	bool found = false;
585 
586 	KASSERT(sme != NULL || edata != NULL);
587 
588 	/*
589 	 * Check the sensor is already on the list.
590 	 */
591 	mutex_enter(&sme->sme_mtx);
592 	sysmon_envsys_acquire(sme, true);
593 	TAILQ_FOREACH(oedata, &sme->sme_sensors_list, sensors_head) {
594 		if (oedata->sensor == edata->sensor) {
595 			found = true;
596 			break;
597 		}
598 	}
599 
600 	if (!found) {
601 		sysmon_envsys_release(sme, true);
602 		mutex_exit(&sme->sme_mtx);
603 		return EINVAL;
604 	}
605 
606 	/*
607 	 * remove it and decrement the sensors count.
608 	 */
609 	TAILQ_REMOVE(&sme->sme_sensors_list, edata, sensors_head);
610 	sme->sme_nsensors--;
611 	sysmon_envsys_release(sme, true);
612 	mutex_exit(&sme->sme_mtx);
613 
614 	return 0;
615 }
616 
617 
618 /*
619  * sysmon_envsys_register:
620  *
621  *	+ Register a sysmon envsys device.
622  *	+ Create array of dictionaries for a device.
623  */
624 int
625 sysmon_envsys_register(struct sysmon_envsys *sme)
626 {
627 	struct sme_evdrv {
628 		SLIST_ENTRY(sme_evdrv) evdrv_head;
629 		sme_event_drv_t *evdrv;
630 	};
631 	SLIST_HEAD(, sme_evdrv) sme_evdrv_list;
632 	struct sme_evdrv *evdv = NULL;
633 	struct sysmon_envsys *lsme;
634 	prop_array_t array = NULL;
635 	prop_dictionary_t dict, dict2;
636 	envsys_data_t *edata = NULL;
637 	sme_event_drv_t *this_evdrv;
638 	int nevent;
639 	int error = 0;
640 
641 	KASSERT(sme != NULL);
642 	KASSERT(sme->sme_name != NULL);
643 
644 	/*
645 	 * Check if requested sysmon_envsys device is valid
646 	 * and does not exist already in the list.
647 	 */
648 	mutex_enter(&sme_global_mtx);
649 	LIST_FOREACH(lsme, &sysmon_envsys_list, sme_list) {
650 	       if (strcmp(lsme->sme_name, sme->sme_name) == 0) {
651 		       mutex_exit(&sme_global_mtx);
652 		       return EEXIST;
653 	       }
654 	}
655 	mutex_exit(&sme_global_mtx);
656 
657 	/*
658 	 * sanity check: if SME_DISABLE_REFRESH is not set,
659 	 * the sme_refresh function callback must be non NULL.
660 	 */
661 	if ((sme->sme_flags & SME_DISABLE_REFRESH) == 0)
662 		if (!sme->sme_refresh)
663 			return EINVAL;
664 
665 	/*
666 	 * If the list of sensors is empty, there's no point to continue...
667 	 */
668 	if (TAILQ_EMPTY(&sme->sme_sensors_list)) {
669 		DPRINTF(("%s: sensors list empty for %s\n", __func__,
670 		    sme->sme_name));
671 		return ENOTSUP;
672 	}
673 
674 	/*
675 	 * Initialize the singly linked list for driver events.
676 	 */
677 	SLIST_INIT(&sme_evdrv_list);
678 
679 	array = prop_array_create();
680 	if (!array)
681 		return ENOMEM;
682 
683 	/*
684 	 * Iterate over all sensors and create a dictionary per sensor.
685 	 * We must respect the order in which the sensors were added.
686 	 */
687 	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
688 		dict = prop_dictionary_create();
689 		if (!dict) {
690 			error = ENOMEM;
691 			goto out2;
692 		}
693 
694 		/*
695 		 * Create all objects in sensor's dictionary.
696 		 */
697 		this_evdrv = sme_add_sensor_dictionary(sme, array,
698 						       dict, edata);
699 		if (this_evdrv) {
700 			evdv = kmem_zalloc(sizeof(*evdv), KM_SLEEP);
701 			evdv->evdrv = this_evdrv;
702 			SLIST_INSERT_HEAD(&sme_evdrv_list, evdv, evdrv_head);
703 		}
704 	}
705 
706 	/*
707 	 * If the array does not contain any object (sensor), there's
708 	 * no need to attach the driver.
709 	 */
710 	if (prop_array_count(array) == 0) {
711 		error = EINVAL;
712 		DPRINTF(("%s: empty array for '%s'\n", __func__,
713 		    sme->sme_name));
714 		goto out;
715 	}
716 
717 	/*
718 	 * Add the dictionary for the global properties of this device.
719 	 */
720 	dict2 = prop_dictionary_create();
721 	if (!dict2) {
722 		error = ENOMEM;
723 		goto out;
724 	}
725 
726 	error = sme_add_property_dictionary(sme, array, dict2);
727 	if (error) {
728 		prop_object_release(dict2);
729 		goto out;
730 	}
731 
732 	/*
733 	 * Add the array into the global dictionary for the driver.
734 	 *
735 	 * <dict>
736 	 * 	<key>foo0</key>
737 	 * 	<array>
738 	 * 		...
739 	 */
740 	mutex_enter(&sme_global_mtx);
741 	if (!prop_dictionary_set(sme_propd, sme->sme_name, array)) {
742 		error = EINVAL;
743 		DPRINTF(("%s: prop_dictionary_set for '%s'\n", __func__,
744 		    sme->sme_name));
745 		goto out;
746 	}
747 
748 	/*
749 	 * Add the device into the list.
750 	 */
751 	LIST_INSERT_HEAD(&sysmon_envsys_list, sme, sme_list);
752 	sme->sme_fsensor = sysmon_envsys_next_sensor_index;
753 	sysmon_envsys_next_sensor_index += sme->sme_nsensors;
754 	mutex_exit(&sme_global_mtx);
755 
756 out:
757 	/*
758 	 * No errors?  Make an initial data refresh if was requested,
759 	 * then register the events that were set in the driver.  Do
760 	 * the refresh first in case it is needed to establish the
761 	 * limits or max_value needed by some events.
762 	 */
763 	if (error == 0) {
764 		nevent = 0;
765 		sysmon_task_queue_init();
766 
767 		if (sme->sme_flags & SME_INIT_REFRESH) {
768 			sysmon_task_queue_sched(0, sme_initial_refresh, sme);
769 			DPRINTF(("%s: scheduled initial refresh for '%s'\n",
770 				__func__, sme->sme_name));
771 		}
772 		SLIST_FOREACH(evdv, &sme_evdrv_list, evdrv_head) {
773 			sysmon_task_queue_sched(0,
774 			    sme_event_drvadd, evdv->evdrv);
775 			nevent++;
776 		}
777 		DPRINTF(("%s: driver '%s' registered (nsens=%d nevent=%d)\n",
778 		    __func__, sme->sme_name, sme->sme_nsensors, nevent));
779 	}
780 
781 out2:
782 	while (!SLIST_EMPTY(&sme_evdrv_list)) {
783 		evdv = SLIST_FIRST(&sme_evdrv_list);
784 		SLIST_REMOVE_HEAD(&sme_evdrv_list, evdrv_head);
785 		kmem_free(evdv, sizeof(*evdv));
786 	}
787 	if (!error)
788 		return 0;
789 
790 	/*
791 	 * Ugh... something wasn't right; unregister all events and sensors
792 	 * previously assigned and destroy the array with all its objects.
793 	 */
794 	DPRINTF(("%s: failed to register '%s' (%d)\n", __func__,
795 	    sme->sme_name, error));
796 
797 	sme_event_unregister_all(sme);
798 	while (!TAILQ_EMPTY(&sme->sme_sensors_list)) {
799 		edata = TAILQ_FIRST(&sme->sme_sensors_list);
800 		TAILQ_REMOVE(&sme->sme_sensors_list, edata, sensors_head);
801 	}
802 	sysmon_envsys_destroy_plist(array);
803 	return error;
804 }
805 
806 /*
807  * sysmon_envsys_destroy_plist:
808  *
809  * 	+ Remove all objects from the array of dictionaries that is
810  * 	  created in a sysmon envsys device.
811  */
812 static void
813 sysmon_envsys_destroy_plist(prop_array_t array)
814 {
815 	prop_object_iterator_t iter, iter2;
816 	prop_dictionary_t dict;
817 	prop_object_t obj;
818 
819 	KASSERT(array != NULL);
820 	KASSERT(prop_object_type(array) == PROP_TYPE_ARRAY);
821 
822 	DPRINTFOBJ(("%s: objects in array=%d\n", __func__,
823 	    prop_array_count(array)));
824 
825 	iter = prop_array_iterator(array);
826 	if (!iter)
827 		return;
828 
829 	while ((dict = prop_object_iterator_next(iter))) {
830 		KASSERT(prop_object_type(dict) == PROP_TYPE_DICTIONARY);
831 		iter2 = prop_dictionary_iterator(dict);
832 		if (!iter2)
833 			goto out;
834 		DPRINTFOBJ(("%s: iterating over dictionary\n", __func__));
835 		while ((obj = prop_object_iterator_next(iter2)) != NULL) {
836 			DPRINTFOBJ(("%s: obj=%s\n", __func__,
837 			    prop_dictionary_keysym_cstring_nocopy(obj)));
838 			prop_dictionary_remove(dict,
839 			    prop_dictionary_keysym_cstring_nocopy(obj));
840 			prop_object_iterator_reset(iter2);
841 		}
842 		prop_object_iterator_release(iter2);
843 		DPRINTFOBJ(("%s: objects in dictionary:%d\n",
844 		    __func__, prop_dictionary_count(dict)));
845 		prop_object_release(dict);
846 	}
847 
848 out:
849 	prop_object_iterator_release(iter);
850 	prop_object_release(array);
851 }
852 
853 /*
854  * sysmon_envsys_unregister:
855  *
856  *	+ Unregister a sysmon envsys device.
857  */
858 void
859 sysmon_envsys_unregister(struct sysmon_envsys *sme)
860 {
861 	prop_array_t array;
862 
863 	KASSERT(sme != NULL);
864 
865 	/*
866 	 * Unregister all events associated with device.
867 	 */
868 	sme_event_unregister_all(sme);
869 	/*
870 	 * Decrement global sensors counter (only used for compatibility
871 	 * with previous API) and remove the device from the list.
872 	 */
873 	mutex_enter(&sme_global_mtx);
874 	sysmon_envsys_next_sensor_index -= sme->sme_nsensors;
875 	LIST_REMOVE(sme, sme_list);
876 	mutex_exit(&sme_global_mtx);
877 
878 	/*
879 	 * Remove the device (and all its objects) from the global dictionary.
880 	 */
881 	array = prop_dictionary_get(sme_propd, sme->sme_name);
882 	if (array && prop_object_type(array) == PROP_TYPE_ARRAY) {
883 		mutex_enter(&sme_global_mtx);
884 		prop_dictionary_remove(sme_propd, sme->sme_name);
885 		mutex_exit(&sme_global_mtx);
886 		sysmon_envsys_destroy_plist(array);
887 	}
888 	/*
889 	 * And finally destroy the sysmon_envsys object.
890 	 */
891 	sysmon_envsys_destroy(sme);
892 }
893 
894 /*
895  * sysmon_envsys_find:
896  *
897  *	+ Find a sysmon envsys device and mark it as busy
898  *	  once it's available.
899  */
900 struct sysmon_envsys *
901 sysmon_envsys_find(const char *name)
902 {
903 	struct sysmon_envsys *sme;
904 
905 	mutex_enter(&sme_global_mtx);
906 	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
907 		if (strcmp(sme->sme_name, name) == 0) {
908 			sysmon_envsys_acquire(sme, false);
909 			break;
910 		}
911 	}
912 	mutex_exit(&sme_global_mtx);
913 
914 	return sme;
915 }
916 
917 /*
918  * Compatibility function with the old API.
919  */
920 struct sysmon_envsys *
921 sysmon_envsys_find_40(u_int idx)
922 {
923 	struct sysmon_envsys *sme;
924 
925 	mutex_enter(&sme_global_mtx);
926 	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
927 		if (idx >= sme->sme_fsensor &&
928 	    	    idx < (sme->sme_fsensor + sme->sme_nsensors)) {
929 			sysmon_envsys_acquire(sme, false);
930 			break;
931 		}
932 	}
933 	mutex_exit(&sme_global_mtx);
934 
935 	return sme;
936 }
937 
938 /*
939  * sysmon_envsys_acquire:
940  *
941  * 	+ Wait until a sysmon envsys device is available and mark
942  * 	  it as busy.
943  */
944 void
945 sysmon_envsys_acquire(struct sysmon_envsys *sme, bool locked)
946 {
947 	KASSERT(sme != NULL);
948 
949 	if (locked) {
950 		while (sme->sme_flags & SME_FLAG_BUSY)
951 			cv_wait(&sme->sme_condvar, &sme->sme_mtx);
952 		sme->sme_flags |= SME_FLAG_BUSY;
953 	} else {
954 		mutex_enter(&sme->sme_mtx);
955 		while (sme->sme_flags & SME_FLAG_BUSY)
956 			cv_wait(&sme->sme_condvar, &sme->sme_mtx);
957 		sme->sme_flags |= SME_FLAG_BUSY;
958 		mutex_exit(&sme->sme_mtx);
959 	}
960 }
961 
962 /*
963  * sysmon_envsys_release:
964  *
965  * 	+ Unmark a sysmon envsys device as busy, and notify
966  * 	  waiters.
967  */
968 void
969 sysmon_envsys_release(struct sysmon_envsys *sme, bool locked)
970 {
971 	KASSERT(sme != NULL);
972 
973 	if (locked) {
974 		sme->sme_flags &= ~SME_FLAG_BUSY;
975 		cv_broadcast(&sme->sme_condvar);
976 	} else {
977 		mutex_enter(&sme->sme_mtx);
978 		sme->sme_flags &= ~SME_FLAG_BUSY;
979 		cv_broadcast(&sme->sme_condvar);
980 		mutex_exit(&sme->sme_mtx);
981 	}
982 }
983 
984 /*
985  * sme_initial_refresh:
986  *
987  * 	+ Do an initial refresh of the sensors in a device just after
988  * 	  interrupts are enabled in the autoconf(9) process.
989  *
990  */
991 static void
992 sme_initial_refresh(void *arg)
993 {
994 	struct sysmon_envsys *sme = arg;
995 	envsys_data_t *edata;
996 
997 	mutex_enter(&sme->sme_mtx);
998 	sysmon_envsys_acquire(sme, true);
999 	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head)
1000 		if ((sme->sme_flags & SME_DISABLE_REFRESH) == 0)
1001 			(*sme->sme_refresh)(sme, edata);
1002 	sysmon_envsys_release(sme, true);
1003 	mutex_exit(&sme->sme_mtx);
1004 }
1005 
1006 /*
1007  * sme_sensor_dictionary_get:
1008  *
1009  * 	+ Returns a dictionary of a device specified by its index
1010  * 	  position.
1011  */
1012 prop_dictionary_t
1013 sme_sensor_dictionary_get(prop_array_t array, const char *index)
1014 {
1015 	prop_object_iterator_t iter;
1016 	prop_dictionary_t dict;
1017 	prop_object_t obj;
1018 
1019 	KASSERT(array != NULL || index != NULL);
1020 
1021 	iter = prop_array_iterator(array);
1022 	if (!iter)
1023 		return NULL;
1024 
1025 	while ((dict = prop_object_iterator_next(iter))) {
1026 		obj = prop_dictionary_get(dict, "index");
1027 		if (prop_string_equals_cstring(obj, index))
1028 			break;
1029 	}
1030 
1031 	prop_object_iterator_release(iter);
1032 	return dict;
1033 }
1034 
1035 /*
1036  * sme_remove_userprops:
1037  *
1038  * 	+ Remove all properties from all devices that were set by
1039  * 	  the ENVSYS_SETDICTIONARY ioctl.
1040  */
1041 static void
1042 sme_remove_userprops(void)
1043 {
1044 	struct sysmon_envsys *sme;
1045 	prop_array_t array;
1046 	prop_dictionary_t sdict;
1047 	envsys_data_t *edata = NULL;
1048 	char tmp[ENVSYS_DESCLEN];
1049 	int ptype;
1050 
1051 	mutex_enter(&sme_global_mtx);
1052 	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
1053 		sysmon_envsys_acquire(sme, false);
1054 		array = prop_dictionary_get(sme_propd, sme->sme_name);
1055 
1056 		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
1057 			(void)snprintf(tmp, sizeof(tmp), "sensor%d",
1058 				       edata->sensor);
1059 			sdict = sme_sensor_dictionary_get(array, tmp);
1060 			KASSERT(sdict != NULL);
1061 
1062 			ptype = 0;
1063 			if (edata->upropset & PROP_BATTCAP) {
1064 				prop_dictionary_remove(sdict,
1065 				    "critical-capacity");
1066 				ptype = PENVSYS_EVENT_CAPACITY;
1067 			}
1068 
1069 			if (edata->upropset & PROP_BATTWARN) {
1070 				prop_dictionary_remove(sdict,
1071 				    "warning-capacity");
1072 				ptype = PENVSYS_EVENT_CAPACITY;
1073 			}
1074 
1075 			if (edata->upropset & PROP_BATTHIGH) {
1076 				prop_dictionary_remove(sdict,
1077 				    "high-capacity");
1078 				ptype = PENVSYS_EVENT_CAPACITY;
1079 			}
1080 
1081 			if (edata->upropset & PROP_BATTMAX) {
1082 				prop_dictionary_remove(sdict,
1083 				    "maximum-capacity");
1084 				ptype = PENVSYS_EVENT_CAPACITY;
1085 			}
1086 			if (ptype != 0)
1087 				sme_event_unregister(sme, edata->desc, ptype);
1088 
1089 			ptype = 0;
1090 			if (edata->upropset & PROP_WARNMAX) {
1091 				prop_dictionary_remove(sdict, "warning-max");
1092 				ptype = PENVSYS_EVENT_LIMITS;
1093 			}
1094 
1095 			if (edata->upropset & PROP_WARNMIN) {
1096 				prop_dictionary_remove(sdict, "warning-min");
1097 				ptype = PENVSYS_EVENT_LIMITS;
1098 			}
1099 
1100 			if (edata->upropset & PROP_CRITMAX) {
1101 				prop_dictionary_remove(sdict, "critical-max");
1102 				ptype = PENVSYS_EVENT_LIMITS;
1103 			}
1104 
1105 			if (edata->upropset & PROP_CRITMIN) {
1106 				prop_dictionary_remove(sdict, "critical-min");
1107 				ptype = PENVSYS_EVENT_LIMITS;
1108 			}
1109 			if (ptype != 0)
1110 				sme_event_unregister(sme, edata->desc, ptype);
1111 
1112 			if (edata->upropset & PROP_RFACT) {
1113 				(void)sme_sensor_upint32(sdict, "rfact", 0);
1114 				edata->rfact = 0;
1115 			}
1116 
1117 			if (edata->upropset & PROP_DESC)
1118 				(void)sme_sensor_upstring(sdict,
1119 			  	    "description", edata->desc);
1120 
1121 			if (edata->upropset)
1122 				edata->upropset = 0;
1123 		}
1124 
1125 		/*
1126 		 * Restore default timeout value.
1127 		 */
1128 		sme->sme_events_timeout = SME_EVENTS_DEFTIMEOUT;
1129 		sysmon_envsys_release(sme, false);
1130 	}
1131 	mutex_exit(&sme_global_mtx);
1132 }
1133 
1134 /*
1135  * sme_add_property_dictionary:
1136  *
1137  * 	+ Add global properties into a device.
1138  */
1139 static int
1140 sme_add_property_dictionary(struct sysmon_envsys *sme, prop_array_t array,
1141 			    prop_dictionary_t dict)
1142 {
1143 	prop_dictionary_t pdict;
1144 	int error = 0;
1145 
1146 	pdict = prop_dictionary_create();
1147 	if (!pdict)
1148 		return EINVAL;
1149 
1150 	/*
1151 	 * Add the 'refresh-timeout' object into the 'device-properties'
1152 	 * dictionary. We use by default 30 seconds.
1153 	 *
1154 	 * 	...
1155 	 * 	<dict>
1156 	 * 		<key>device-properties</key>
1157 	 * 		<dict>
1158 	 * 			<key>refresh-timeout</key>
1159 	 * 			<integer>120</integer<
1160 	 * 		</dict<
1161 	 * 	</dict>
1162 	 * 	...
1163 	 *
1164 	 */
1165 	if (!sme->sme_events_timeout)
1166 		sme->sme_events_timeout = SME_EVENTS_DEFTIMEOUT;
1167 
1168 	if (!prop_dictionary_set_uint64(pdict, "refresh-timeout",
1169 					sme->sme_events_timeout)) {
1170 		error = EINVAL;
1171 		goto out;
1172 	}
1173 
1174 	if (!prop_dictionary_set(dict, "device-properties", pdict)) {
1175 		error = EINVAL;
1176 		goto out;
1177 	}
1178 
1179 	/*
1180 	 * Add the device dictionary into the sysmon envsys array.
1181 	 */
1182 	if (!prop_array_add(array, dict))
1183 		error = EINVAL;
1184 
1185 out:
1186 	prop_object_release(pdict);
1187 	return error;
1188 }
1189 
1190 /*
1191  * sme_add_sensor_dictionary:
1192  *
1193  * 	+ Adds the sensor objects into the dictionary and returns a pointer
1194  * 	  to a sme_event_drv_t object if a monitoring flag was set
1195  * 	  (or NULL otherwise).
1196  */
1197 static sme_event_drv_t *
1198 sme_add_sensor_dictionary(struct sysmon_envsys *sme, prop_array_t array,
1199 		    	  prop_dictionary_t dict, envsys_data_t *edata)
1200 {
1201 	const struct sme_description_table *sdt, *sdt_units;
1202 	sme_event_drv_t *sme_evdrv_t = NULL;
1203 	int i, j;
1204 	char indexstr[ENVSYS_DESCLEN];
1205 
1206 	/*
1207 	 * Find the correct units for this sensor.
1208 	 */
1209 	sdt_units = sme_get_description_table(SME_DESC_UNITS);
1210 	for (i = 0; sdt_units[i].type != -1; i++)
1211 		if (sdt_units[i].type == edata->units)
1212 			break;
1213 
1214 	/*
1215 	 * Add the index sensor string.
1216 	 *
1217 	 * 		...
1218 	 * 		<key>index</eyr
1219 	 * 		<string>sensor0</string>
1220 	 * 		...
1221 	 */
1222 	(void)snprintf(indexstr, sizeof(indexstr), "sensor%d", edata->sensor);
1223 	if (sme_sensor_upstring(dict, "index", indexstr))
1224 		goto bad;
1225 
1226 	/*
1227 	 * 		...
1228 	 * 		<key>type</key>
1229 	 * 		<string>foo</string>
1230 	 * 		<key>description</key>
1231 	 * 		<string>blah blah</string>
1232 	 * 		...
1233 	 */
1234 	if (sme_sensor_upstring(dict, "type", sdt_units[i].desc))
1235 		goto bad;
1236 
1237 	if (sme_sensor_upstring(dict, "description", edata->desc))
1238 		goto bad;
1239 
1240 	/*
1241 	 * Add sensor's state description.
1242 	 *
1243 	 * 		...
1244 	 * 		<key>state</key>
1245 	 * 		<string>valid</string>
1246 	 * 		...
1247 	 */
1248 	sdt = sme_get_description_table(SME_DESC_STATES);
1249 	for (j = 0; sdt[j].type != -1; j++)
1250 		if (sdt[j].type == edata->state)
1251 			break;
1252 
1253 	DPRINTF(("%s: sensor desc=%s type=%d state=%d\n",
1254 	    __func__, edata->desc, edata->units, edata->state));
1255 
1256 	if (sme_sensor_upstring(dict, "state", sdt[j].desc))
1257 		goto bad;
1258 
1259 	/*
1260 	 * Add the monitoring boolean object:
1261 	 *
1262 	 * 		...
1263 	 * 		<key>monitoring-supported</key>
1264 	 * 		<true/>
1265 	 *		...
1266 	 *
1267 	 * always false on Battery {capacity,charge}, Drive and Indicator types.
1268 	 * They cannot be monitored.
1269 	 *
1270 	 */
1271 	if ((edata->flags & ENVSYS_FMONNOTSUPP) ||
1272 	    (edata->units == ENVSYS_INDICATOR) ||
1273 	    (edata->units == ENVSYS_DRIVE) ||
1274 	    (edata->units == ENVSYS_BATTERY_CAPACITY) ||
1275 	    (edata->units == ENVSYS_BATTERY_CHARGE)) {
1276 		if (sme_sensor_upbool(dict, "monitoring-supported", false))
1277 			goto out;
1278 	} else {
1279 		if (sme_sensor_upbool(dict, "monitoring-supported", true))
1280 			goto out;
1281 	}
1282 
1283 	/*
1284 	 * Add the percentage boolean object, true if ENVSYS_FPERCENT
1285 	 * is set or false otherwise.
1286 	 *
1287 	 * 		...
1288 	 * 		<key>want-percentage</key>
1289 	 * 		<true/>
1290 	 * 		...
1291 	 */
1292 	if (edata->flags & ENVSYS_FPERCENT)
1293 		if (sme_sensor_upbool(dict, "want-percentage", true))
1294 			goto out;
1295 
1296 	/*
1297 	 * Add the allow-rfact boolean object, true if
1298 	 * ENVSYS_FCHANGERFACT if set or false otherwise.
1299 	 *
1300 	 * 		...
1301 	 * 		<key>allow-rfact</key>
1302 	 * 		<true/>
1303 	 * 		...
1304 	 */
1305 	if (edata->units == ENVSYS_SVOLTS_DC ||
1306 	    edata->units == ENVSYS_SVOLTS_AC) {
1307 		if (edata->flags & ENVSYS_FCHANGERFACT) {
1308 			if (sme_sensor_upbool(dict, "allow-rfact", true))
1309 				goto out;
1310 		} else {
1311 			if (sme_sensor_upbool(dict, "allow-rfact", false))
1312 				goto out;
1313 		}
1314 	}
1315 
1316 	/*
1317 	 * Add the object for battery capacity sensors:
1318 	 *
1319 	 * 		...
1320 	 * 		<key>battery-capacity</key>
1321 	 * 		<string>NORMAL</string>
1322 	 * 		...
1323 	 */
1324 	if (edata->units == ENVSYS_BATTERY_CAPACITY) {
1325 		sdt = sme_get_description_table(SME_DESC_BATTERY_CAPACITY);
1326 		for (j = 0; sdt[j].type != -1; j++)
1327 			if (sdt[j].type == edata->value_cur)
1328 				break;
1329 
1330 		if (sme_sensor_upstring(dict, "battery-capacity", sdt[j].desc))
1331 			goto out;
1332 	}
1333 
1334 	/*
1335 	 * Add the drive-state object for drive sensors:
1336 	 *
1337 	 * 		...
1338 	 * 		<key>drive-state</key>
1339 	 * 		<string>drive is online</string>
1340 	 * 		...
1341 	 */
1342 	if (edata->units == ENVSYS_DRIVE) {
1343 		sdt = sme_get_description_table(SME_DESC_DRIVE_STATES);
1344 		for (j = 0; sdt[j].type != -1; j++)
1345 			if (sdt[j].type == edata->value_cur)
1346 				break;
1347 
1348 		if (sme_sensor_upstring(dict, "drive-state", sdt[j].desc))
1349 			goto out;
1350 	}
1351 
1352 	/*
1353 	 * Add the following objects if sensor is enabled...
1354 	 */
1355 	if (edata->state == ENVSYS_SVALID) {
1356 		/*
1357 		 * Add the following objects:
1358 		 *
1359 		 * 	...
1360 		 * 	<key>rpms</key>
1361 		 * 	<integer>2500</integer>
1362 		 * 	<key>rfact</key>
1363 		 * 	<integer>10000</integer>
1364 		 * 	<key>cur-value</key>
1365 	 	 * 	<integer>1250</integer>
1366 	 	 * 	<key>min-value</key>
1367 	 	 * 	<integer>800</integer>
1368 	 	 * 	<key>max-value</integer>
1369 	 	 * 	<integer>3000</integer>
1370 	 	 * 	<key>avg-value</integer>
1371 	 	 * 	<integer>1400</integer>
1372 	 	 * 	...
1373 	 	 */
1374 		if (edata->units == ENVSYS_SFANRPM)
1375 			if (sme_sensor_upuint32(dict, "rpms", edata->rpms))
1376 				goto out;
1377 
1378 		if (edata->units == ENVSYS_SVOLTS_AC ||
1379 	    	    edata->units == ENVSYS_SVOLTS_DC)
1380 			if (sme_sensor_upint32(dict, "rfact", edata->rfact))
1381 				goto out;
1382 
1383 		if (sme_sensor_upint32(dict, "cur-value", edata->value_cur))
1384 			goto out;
1385 
1386 		if (edata->flags & ENVSYS_FVALID_MIN) {
1387 			if (sme_sensor_upint32(dict,
1388 					       "min-value",
1389 					       edata->value_min))
1390 			goto out;
1391 		}
1392 
1393 		if (edata->flags & ENVSYS_FVALID_MAX) {
1394 			if (sme_sensor_upint32(dict,
1395 					       "max-value",
1396 					       edata->value_max))
1397 			goto out;
1398 		}
1399 
1400 		if (edata->flags & ENVSYS_FVALID_AVG) {
1401 			if (sme_sensor_upint32(dict,
1402 					       "avg-value",
1403 					       edata->value_avg))
1404 			goto out;
1405 		}
1406 	}
1407 
1408 	/*
1409 	 * 	...
1410 	 * </dict>
1411 	 *
1412 	 * Add the dictionary into the array.
1413 	 *
1414 	 */
1415 	if (!prop_array_add(array, dict)) {
1416 		DPRINTF(("%s: prop_array_add\n", __func__));
1417 		goto bad;
1418 	}
1419 
1420 	/*
1421 	 * Register new event(s) if any monitoring flag was set.
1422 	 */
1423 	if (edata->flags & ENVSYS_FMONANY) {
1424 		sme_evdrv_t = kmem_zalloc(sizeof(*sme_evdrv_t), KM_SLEEP);
1425 		sme_evdrv_t->sed_sdict = dict;
1426 		sme_evdrv_t->sed_edata = edata;
1427 		sme_evdrv_t->sed_sme = sme;
1428 		sme_evdrv_t->sed_powertype = sdt_units[i].crittype;
1429 	}
1430 
1431 out:
1432 	return sme_evdrv_t;
1433 
1434 bad:
1435 	prop_object_release(dict);
1436 	return NULL;
1437 }
1438 
1439 /*
1440  * Find the maximum of all currently reported values.
1441  * The provided callback decides wether a sensor is part of the
1442  * maximum calculation (by returning true) or ignored (callback
1443  * returns false). Example usage: callback selects temperature
1444  * sensors in a given thermal zone, the function calculates the
1445  * maximum currently reported temperature in this zone.
1446  * If the parameter "refresh" is true, new values will be aquired
1447  * from the hardware, if not, the last reported value will be used.
1448  */
1449 uint32_t
1450 sysmon_envsys_get_max_value(bool (*predicate)(const envsys_data_t*),
1451 	bool refresh)
1452 {
1453 	struct sysmon_envsys *sme;
1454 	uint32_t maxv, v;
1455 
1456 	maxv = 0;
1457 	mutex_enter(&sme_global_mtx);
1458 	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
1459 		sysmon_envsys_acquire(sme, false);
1460 		v = sme_get_max_value(sme, predicate, refresh);
1461 		sysmon_envsys_release(sme, false);
1462 		if (v > maxv)
1463 			maxv = v;
1464 	}
1465 	mutex_exit(&sme_global_mtx);
1466 	return maxv;
1467 }
1468 
1469 static uint32_t
1470 sme_get_max_value(struct sysmon_envsys *sme,
1471     bool (*predicate)(const envsys_data_t*),
1472     bool refresh)
1473 {
1474 	envsys_data_t *edata;
1475 	uint32_t maxv, v;
1476 
1477 	/*
1478 	 * Iterate over all sensors that match the predicate
1479 	 */
1480 	maxv = 0;
1481 	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
1482 		if (!(*predicate)(edata))
1483 			continue;
1484 
1485 		/*
1486 		 * refresh sensor data via sme_refresh only if the
1487 		 * flag is not set.
1488 		 */
1489 		if (refresh && (sme->sme_flags & SME_DISABLE_REFRESH) == 0) {
1490 			mutex_enter(&sme->sme_mtx);
1491 			(*sme->sme_refresh)(sme, edata);
1492 			mutex_exit(&sme->sme_mtx);
1493 		}
1494 
1495 		v = edata->value_cur;
1496 		if (v > maxv)
1497 			maxv = v;
1498 
1499 	}
1500 
1501 	return maxv;
1502 }
1503 
1504 /*
1505  * sme_update_dictionary:
1506  *
1507  * 	+ Update per-sensor dictionaries with new values if there were
1508  * 	  changes, otherwise the object in dictionary is untouched.
1509  */
1510 int
1511 sme_update_dictionary(struct sysmon_envsys *sme)
1512 {
1513 	const struct sme_description_table *sdt;
1514 	envsys_data_t *edata;
1515 	prop_object_t array, dict, obj, obj2;
1516 	int j, error = 0;
1517 
1518 	/*
1519 	 * Retrieve the array of dictionaries in device.
1520 	 */
1521 	array = prop_dictionary_get(sme_propd, sme->sme_name);
1522 	if (prop_object_type(array) != PROP_TYPE_ARRAY) {
1523 		DPRINTF(("%s: not an array (%s)\n", __func__, sme->sme_name));
1524 		return EINVAL;
1525 	}
1526 
1527 	/*
1528 	 * Get the last dictionary on the array, this contains the
1529 	 * 'device-properties' sub-dictionary.
1530 	 */
1531 	obj = prop_array_get(array, prop_array_count(array) - 1);
1532 	if (!obj || prop_object_type(obj) != PROP_TYPE_DICTIONARY) {
1533 		DPRINTF(("%s: not a device-properties dictionary\n", __func__));
1534 		return EINVAL;
1535 	}
1536 
1537 	obj2 = prop_dictionary_get(obj, "device-properties");
1538 	if (!obj2)
1539 		return EINVAL;
1540 
1541 	/*
1542 	 * Update the 'refresh-timeout' property.
1543 	 */
1544 	if (!prop_dictionary_set_uint64(obj2, "refresh-timeout",
1545 					sme->sme_events_timeout))
1546 		return EINVAL;
1547 
1548 	/*
1549 	 * - iterate over all sensors.
1550 	 * - fetch new data.
1551 	 * - check if data in dictionary is different than new data.
1552 	 * - update dictionary if there were changes.
1553 	 */
1554 	DPRINTF(("%s: updating '%s' with nsensors=%d\n", __func__,
1555 	    sme->sme_name, sme->sme_nsensors));
1556 
1557 	/*
1558 	 * Don't bother with locking when traversing the queue,
1559 	 * the device is already marked as busy; if a sensor
1560 	 * is going to be removed or added it will have to wait.
1561 	 */
1562 	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
1563 		/*
1564 		 * refresh sensor data via sme_refresh only if the
1565 		 * flag is not set.
1566 		 */
1567 		if ((sme->sme_flags & SME_DISABLE_REFRESH) == 0) {
1568 			mutex_enter(&sme->sme_mtx);
1569 			(*sme->sme_refresh)(sme, edata);
1570 			mutex_exit(&sme->sme_mtx);
1571 		}
1572 
1573 		/*
1574 		 * retrieve sensor's dictionary.
1575 		 */
1576 		dict = prop_array_get(array, edata->sensor);
1577 		if (prop_object_type(dict) != PROP_TYPE_DICTIONARY) {
1578 			DPRINTF(("%s: not a dictionary (%d:%s)\n",
1579 			    __func__, edata->sensor, sme->sme_name));
1580 			return EINVAL;
1581 		}
1582 
1583 		/*
1584 		 * update sensor's state.
1585 		 */
1586 		sdt = sme_get_description_table(SME_DESC_STATES);
1587 		for (j = 0; sdt[j].type != -1; j++)
1588 			if (sdt[j].type == edata->state)
1589 				break;
1590 
1591 		DPRINTFOBJ(("%s: sensor #%d type=%d (%s) flags=%d\n",
1592 		    __func__, edata->sensor, sdt[j].type, sdt[j].desc,
1593 		    edata->flags));
1594 
1595 		error = sme_sensor_upstring(dict, "state", sdt[j].desc);
1596 		if (error)
1597 			break;
1598 
1599 		/*
1600 		 * update sensor's type.
1601 		 */
1602 		sdt = sme_get_description_table(SME_DESC_UNITS);
1603 		for (j = 0; sdt[j].type != -1; j++)
1604 			if (sdt[j].type == edata->units)
1605 				break;
1606 
1607 		DPRINTFOBJ(("%s: sensor #%d units=%d (%s)\n",
1608 		    __func__, edata->sensor, sdt[j].type, sdt[j].desc));
1609 
1610 		error = sme_sensor_upstring(dict, "type", sdt[j].desc);
1611 		if (error)
1612 			break;
1613 
1614 		/*
1615 		 * update sensor's current value.
1616 		 */
1617 		error = sme_sensor_upint32(dict,
1618 					   "cur-value",
1619 					   edata->value_cur);
1620 		if (error)
1621 			break;
1622 
1623 		/*
1624 		 * Battery charge, Integer and Indicator types do not
1625 		 * need the following objects, so skip them.
1626 		 */
1627 		if (edata->units == ENVSYS_INTEGER ||
1628 		    edata->units == ENVSYS_INDICATOR ||
1629 		    edata->units == ENVSYS_BATTERY_CHARGE)
1630 			continue;
1631 
1632 		/*
1633 		 * update sensor flags.
1634 		 */
1635 		if (edata->flags & ENVSYS_FPERCENT) {
1636 			error = sme_sensor_upbool(dict,
1637 						  "want-percentage",
1638 						  true);
1639 			if (error)
1640 				break;
1641 		}
1642 
1643 		/*
1644 		 * update sensor's {avg,max,min}-value.
1645 		 */
1646 		if (edata->flags & ENVSYS_FVALID_MAX) {
1647 			error = sme_sensor_upint32(dict,
1648 						   "max-value",
1649 						   edata->value_max);
1650 			if (error)
1651 				break;
1652 		}
1653 
1654 		if (edata->flags & ENVSYS_FVALID_MIN) {
1655 			error = sme_sensor_upint32(dict,
1656 						   "min-value",
1657 						   edata->value_min);
1658 			if (error)
1659 				break;
1660 		}
1661 
1662 		if (edata->flags & ENVSYS_FVALID_AVG) {
1663 			error = sme_sensor_upint32(dict,
1664 						   "avg-value",
1665 						   edata->value_avg);
1666 			if (error)
1667 				break;
1668 		}
1669 
1670 		/*
1671 		 * update 'rpms' only for ENVSYS_SFANRPM sensors.
1672 		 */
1673 		if (edata->units == ENVSYS_SFANRPM) {
1674 			error = sme_sensor_upuint32(dict,
1675 						    "rpms",
1676 						    edata->rpms);
1677 			if (error)
1678 				break;
1679 		}
1680 
1681 		/*
1682 		 * update 'rfact' only for ENVSYS_SVOLTS_[AD]C sensors.
1683 		 */
1684 		if (edata->units == ENVSYS_SVOLTS_AC ||
1685 		    edata->units == ENVSYS_SVOLTS_DC) {
1686 			error = sme_sensor_upint32(dict,
1687 						   "rfact",
1688 						   edata->rfact);
1689 			if (error)
1690 				break;
1691 		}
1692 
1693 		/*
1694 		 * update 'drive-state' only for ENVSYS_DRIVE sensors.
1695 		 */
1696 		if (edata->units == ENVSYS_DRIVE) {
1697 			sdt = sme_get_description_table(SME_DESC_DRIVE_STATES);
1698 			for (j = 0; sdt[j].type != -1; j++)
1699 				if (sdt[j].type == edata->value_cur)
1700 					break;
1701 
1702 			error = sme_sensor_upstring(dict,
1703 						    "drive-state",
1704 						    sdt[j].desc);
1705 			if (error)
1706 				break;
1707 		}
1708 
1709 		/*
1710 		 * update 'battery-capacity' only for ENVSYS_BATTERY_CAPACITY
1711 		 * sensors.
1712 		 */
1713 		if (edata->units == ENVSYS_BATTERY_CAPACITY) {
1714 			sdt =
1715 			  sme_get_description_table(SME_DESC_BATTERY_CAPACITY);
1716 			for (j = 0; sdt[j].type != -1; j++)
1717 				if (sdt[j].type == edata->value_cur)
1718 					break;
1719 
1720 			error = sme_sensor_upstring(dict,
1721 						    "battery-capacity",
1722 						    sdt[j].desc);
1723 			if (error)
1724 				break;
1725 		}
1726 	}
1727 
1728 	return error;
1729 }
1730 
1731 /*
1732  * sme_userset_dictionary:
1733  *
1734  * 	+ Parse the userland dictionary and run the appropiate tasks
1735  * 	  that were specified.
1736  */
1737 int
1738 sme_userset_dictionary(struct sysmon_envsys *sme, prop_dictionary_t udict,
1739 		       prop_array_t array)
1740 {
1741 	const struct sme_description_table *sdt;
1742 	envsys_data_t *edata;
1743 	prop_dictionary_t dict, tdict = NULL;
1744 	prop_object_t obj, obj1, obj2, tobj = NULL;
1745 	uint32_t props;
1746 	uint64_t refresh_timo = 0;
1747 	sysmon_envsys_lim_t lims;
1748 	int i, error = 0;
1749 	const char *blah;
1750 	bool targetfound = false;
1751 
1752 	/*
1753 	 * The user wanted to change the refresh timeout value for this
1754 	 * device.
1755 	 *
1756 	 * Get the 'device-properties' object from the userland dictionary.
1757 	 */
1758 	obj = prop_dictionary_get(udict, "device-properties");
1759 	if (obj && prop_object_type(obj) == PROP_TYPE_DICTIONARY) {
1760 		/*
1761 		 * Get the 'refresh-timeout' property for this device.
1762 		 */
1763 		obj1 = prop_dictionary_get(obj, "refresh-timeout");
1764 		if (obj1 && prop_object_type(obj1) == PROP_TYPE_NUMBER) {
1765 			targetfound = true;
1766 			refresh_timo =
1767 			    prop_number_unsigned_integer_value(obj1);
1768 			if (refresh_timo < 1)
1769 				error = EINVAL;
1770 			else {
1771 				mutex_enter(&sme->sme_mtx);
1772 				sme->sme_events_timeout = refresh_timo;
1773 				mutex_exit(&sme->sme_mtx);
1774 		}
1775 		}
1776 		return error;
1777 
1778 	} else if (!obj) {
1779 		/*
1780 		 * Get sensor's index from userland dictionary.
1781 		 */
1782 		obj = prop_dictionary_get(udict, "index");
1783 		if (!obj)
1784 			return EINVAL;
1785 		if (prop_object_type(obj) != PROP_TYPE_STRING) {
1786 			DPRINTF(("%s: 'index' not a string\n", __func__));
1787 			return EINVAL;
1788 		}
1789 	} else
1790 		return EINVAL;
1791 
1792 	/*
1793 	 * Don't bother with locking when traversing the queue,
1794 	 * the device is already marked as busy; if a sensor
1795 	 * is going to be removed or added it will have to wait.
1796 	 */
1797 	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
1798 		/*
1799 		 * Get a dictionary and check if it's our sensor by checking
1800 		 * at its index position.
1801 		 */
1802 		dict = prop_array_get(array, edata->sensor);
1803 		obj1 = prop_dictionary_get(dict, "index");
1804 
1805 		/*
1806 		 * is it our sensor?
1807 		 */
1808 		if (!prop_string_equals(obj1, obj))
1809 			continue;
1810 
1811 		props = 0;
1812 
1813 		/*
1814 		 * Check if a new description operation was
1815 		 * requested by the user and set new description.
1816 		 */
1817 		obj2 = prop_dictionary_get(udict, "description");
1818 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_STRING) {
1819 			targetfound = true;
1820 			blah = prop_string_cstring_nocopy(obj2);
1821 
1822 			/*
1823 			 * Check for duplicate description.
1824 			 */
1825 			for (i = 0; i < sme->sme_nsensors; i++) {
1826 				if (i == edata->sensor)
1827 					continue;
1828 				tdict = prop_array_get(array, i);
1829 				tobj =
1830 				    prop_dictionary_get(tdict, "description");
1831 				if (prop_string_equals(obj2, tobj)) {
1832 					error = EEXIST;
1833 					goto out;
1834 				}
1835 			}
1836 
1837 			/*
1838 			 * Update the object in dictionary.
1839 			 */
1840 			mutex_enter(&sme->sme_mtx);
1841 			error = sme_sensor_upstring(dict,
1842 						    "description",
1843 						    blah);
1844 			if (error) {
1845 				mutex_exit(&sme->sme_mtx);
1846 				goto out;
1847 			}
1848 
1849 			DPRINTF(("%s: sensor%d changed desc to: %s\n",
1850 			    __func__, edata->sensor, blah));
1851 			edata->upropset |= PROP_DESC;
1852 			mutex_exit(&sme->sme_mtx);
1853 		}
1854 
1855 		/*
1856 		 * did the user want to change the rfact?
1857 		 */
1858 		obj2 = prop_dictionary_get(udict, "rfact");
1859 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
1860 			targetfound = true;
1861 			if (edata->flags & ENVSYS_FCHANGERFACT) {
1862 				mutex_enter(&sme->sme_mtx);
1863 				edata->rfact = prop_number_integer_value(obj2);
1864 				edata->upropset |= PROP_RFACT;
1865 				mutex_exit(&sme->sme_mtx);
1866 				DPRINTF(("%s: sensor%d changed rfact to %d\n",
1867 				    __func__, edata->sensor, edata->rfact));
1868 			} else {
1869 				error = ENOTSUP;
1870 				goto out;
1871 			}
1872 		}
1873 
1874 		sdt = sme_get_description_table(SME_DESC_UNITS);
1875 		for (i = 0; sdt[i].type != -1; i++)
1876 			if (sdt[i].type == edata->units)
1877 				break;
1878 
1879 		/*
1880 		 * did the user want to set a critical capacity event?
1881 		 */
1882 		obj2 = prop_dictionary_get(udict, "critical-capacity");
1883 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
1884 			targetfound = true;
1885 			lims.sel_critmin = prop_number_integer_value(obj2);
1886 			props |= PROP_BATTCAP;
1887 		}
1888 
1889 		/*
1890 		 * did the user want to set a warning capacity event?
1891 		 */
1892 		obj2 = prop_dictionary_get(udict, "warning-capacity");
1893 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
1894 			targetfound = true;
1895 			lims.sel_warnmin = prop_number_integer_value(obj2);
1896 			props |= PROP_BATTWARN;
1897 		}
1898 
1899 		/*
1900 		 * did the user want to set a high capacity event?
1901 		 */
1902 		obj2 = prop_dictionary_get(udict, "high-capacity");
1903 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
1904 			targetfound = true;
1905 			lims.sel_warnmin = prop_number_integer_value(obj2);
1906 			props |= PROP_BATTHIGH;
1907 		}
1908 
1909 		/*
1910 		 * did the user want to set a maximum capacity event?
1911 		 */
1912 		obj2 = prop_dictionary_get(udict, "maximum-capacity");
1913 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
1914 			targetfound = true;
1915 			lims.sel_warnmin = prop_number_integer_value(obj2);
1916 			props |= PROP_BATTMAX;
1917 		}
1918 
1919 		/*
1920 		 * did the user want to set a critical max event?
1921 		 */
1922 		obj2 = prop_dictionary_get(udict, "critical-max");
1923 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
1924 			targetfound = true;
1925 			lims.sel_critmax = prop_number_integer_value(obj2);
1926 			props |= PROP_CRITMAX;
1927 		}
1928 
1929 		/*
1930 		 * did the user want to set a warning max event?
1931 		 */
1932 		obj2 = prop_dictionary_get(udict, "warning-max");
1933 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
1934 			targetfound = true;
1935 			lims.sel_warnmax = prop_number_integer_value(obj2);
1936 			props |= PROP_WARNMAX;
1937 		}
1938 
1939 		/*
1940 		 * did the user want to set a critical min event?
1941 		 */
1942 		obj2 = prop_dictionary_get(udict, "critical-min");
1943 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
1944 			targetfound = true;
1945 			lims.sel_critmin = prop_number_integer_value(obj2);
1946 			props |= PROP_CRITMIN;
1947 		}
1948 
1949 		/*
1950 		 * did the user want to set a warning min event?
1951 		 */
1952 		obj2 = prop_dictionary_get(udict, "warning-min");
1953 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
1954 			targetfound = true;
1955 			lims.sel_warnmin = prop_number_integer_value(obj2);
1956 			props |= PROP_WARNMIN;
1957 		}
1958 
1959 		if (props) {
1960 			if (edata->flags & ENVSYS_FMONNOTSUPP) {
1961 				error = ENOTSUP;
1962 				goto out;
1963 			}
1964 			error = sme_event_register(dict, edata, sme, &lims,
1965 					props,
1966 					(edata->flags & ENVSYS_FPERCENT)?
1967 						PENVSYS_EVENT_CAPACITY:
1968 						PENVSYS_EVENT_LIMITS,
1969 					sdt[i].crittype);
1970 			if (error == EEXIST)
1971 				error = 0;
1972 			if (error)
1973 				goto out;
1974 		}
1975 
1976 		/*
1977 		 * All objects in dictionary were processed.
1978 		 */
1979 		break;
1980 	}
1981 
1982 out:
1983 	/*
1984 	 * invalid target? return the error.
1985 	 */
1986 	if (!targetfound)
1987 		error = EINVAL;
1988 
1989 	return error;
1990 }
1991