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