Home | History | Annotate | Line # | Download | only in sysmon
sysmon_envsys.c revision 1.77
      1 /*	$NetBSD: sysmon_envsys.c,v 1.77 2008/01/02 03:06:02 dyoung 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.77 2008/01/02 03:06:02 dyoung 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 
    524 	return sme;
    525 }
    526 
    527 /*
    528  * sysmon_envsys_destroy:
    529  *
    530  * 	+ Removes all sensors from the tail queue and frees the
    531  * 	  sysmon_envsys object.
    532  */
    533 void
    534 sysmon_envsys_destroy(struct sysmon_envsys *sme)
    535 {
    536 	envsys_data_t *edata;
    537 
    538 	KASSERT(sme != NULL);
    539 
    540 	while (!TAILQ_EMPTY(&sme->sme_sensors_list)) {
    541 		edata = TAILQ_FIRST(&sme->sme_sensors_list);
    542 		TAILQ_REMOVE(&sme->sme_sensors_list, edata, sensors_head);
    543 	}
    544 
    545 	kmem_free(sme, sizeof(*sme));
    546 }
    547 
    548 /*
    549  * sysmon_envsys_sensor_attach:
    550  *
    551  * 	+ Attachs a sensor into a sysmon_envsys device checking that units
    552  * 	  is set to a valid type and description is unique and not empty.
    553  */
    554 int
    555 sysmon_envsys_sensor_attach(struct sysmon_envsys *sme, envsys_data_t *edata)
    556 {
    557 	const struct sme_description_table *sdt_units;
    558 	envsys_data_t *oedata;
    559 	int i;
    560 
    561 	KASSERT(sme != NULL || edata != NULL);
    562 
    563 	/*
    564 	 * Find the correct units for this sensor.
    565 	 */
    566 	sdt_units = sme_get_description_table(SME_DESC_UNITS);
    567 	for (i = 0; sdt_units[i].type != -1; i++)
    568 		if (sdt_units[i].type == edata->units)
    569 			break;
    570 
    571 	if (strcmp(sdt_units[i].desc, "unknown") == 0)
    572 		return EINVAL;
    573 
    574 	/*
    575 	 * Check that description is not empty or duplicate.
    576 	 */
    577 	if (strlen(edata->desc) == 0)
    578 		return EINVAL;
    579 
    580 	mutex_enter(&sme_mtx);
    581 	TAILQ_FOREACH(oedata, &sme->sme_sensors_list, sensors_head) {
    582 		if (strcmp(oedata->desc, edata->desc) == 0) {
    583 			mutex_exit(&sme_mtx);
    584 			return EEXIST;
    585 		}
    586 	}
    587 	/*
    588 	 * Ok, the sensor has been added into the device queue.
    589 	 */
    590 	TAILQ_INSERT_TAIL(&sme->sme_sensors_list, edata, sensors_head);
    591 
    592 	/*
    593 	 * Give the sensor a index position.
    594 	 */
    595 	edata->sensor = sme->sme_nsensors;
    596 	sme->sme_nsensors++;
    597 	mutex_exit(&sme_mtx);
    598 
    599 	return 0;
    600 }
    601 
    602 /*
    603  * sysmon_envsys_sensor_detach:
    604  *
    605  * 	+ Detachs a sensor from a sysmon_envsys device and decrements the
    606  * 	  sensors count on success.
    607  */
    608 int
    609 sysmon_envsys_sensor_detach(struct sysmon_envsys *sme, envsys_data_t *edata)
    610 {
    611 	envsys_data_t *oedata;
    612 	bool found = false;
    613 
    614 	KASSERT(sme != NULL || edata != NULL);
    615 
    616 	/*
    617 	 * Check the sensor is already on the list.
    618 	 */
    619 	mutex_enter(&sme_mtx);
    620 	TAILQ_FOREACH(oedata, &sme->sme_sensors_list, sensors_head) {
    621 		if (oedata->sensor == edata->sensor) {
    622 			found = true;
    623 			break;
    624 		}
    625 	}
    626 
    627 	if (!found) {
    628 		mutex_exit(&sme_mtx);
    629 		return EINVAL;
    630 	}
    631 
    632 	/*
    633 	 * remove it and decrement the sensors count.
    634 	 */
    635 	TAILQ_REMOVE(&sme->sme_sensors_list, edata, sensors_head);
    636 	sme->sme_nsensors--;
    637 	mutex_exit(&sme_mtx);
    638 
    639 	return 0;
    640 }
    641 
    642 
    643 /*
    644  * sysmon_envsys_register:
    645  *
    646  *	+ Register a sysmon envsys device.
    647  *	+ Create array of dictionaries for a device.
    648  */
    649 int
    650 sysmon_envsys_register(struct sysmon_envsys *sme)
    651 {
    652 	struct sme_evdrv {
    653 		SLIST_ENTRY(sme_evdrv) evdrv_head;
    654 		sme_event_drv_t *evdrv;
    655 	};
    656 	SLIST_HEAD(, sme_evdrv) sme_evdrv_list;
    657 	struct sme_evdrv *sme_evdrv = NULL;
    658 	struct sysmon_envsys *lsme;
    659 	prop_dictionary_t dict, dict2;
    660 	prop_array_t array;
    661 	envsys_data_t *edata = NULL;
    662 	int i, error = 0;
    663 
    664 	KASSERT(sme != NULL);
    665 	KASSERT(sme->sme_name != NULL);
    666 
    667 	/*
    668 	 * sanity check: if SME_DISABLE_REFRESH is not set,
    669 	 * the sme_refresh function callback must be non NULL.
    670 	 */
    671 	if ((sme->sme_flags & SME_DISABLE_REFRESH) == 0)
    672 		if (!sme->sme_refresh)
    673 			return EINVAL;
    674 
    675 	/*
    676 	 * If the list of sensors is empty, there's no point to continue...
    677 	 */
    678 	if (TAILQ_EMPTY(&sme->sme_sensors_list)) {
    679 		DPRINTF(("%s: sensors list empty for %s\n", __func__,
    680 		    sme->sme_name));
    681 		return ENOTSUP;
    682 	}
    683 
    684 	/*
    685 	 * create the device array.
    686 	 */
    687 	array = prop_array_create();
    688 	if (!array)
    689 		return ENOMEM;
    690 
    691 	/*
    692 	 * Initialize the singly linked list for driver events.
    693 	 */
    694 	SLIST_INIT(&sme_evdrv_list);
    695 
    696 	/*
    697 	 * Iterate over all sensors and create a dictionary per sensor.
    698 	 * We must respect the order in which the sensors were added.
    699 	 */
    700 	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
    701 		dict = prop_dictionary_create();
    702 		if (!dict) {
    703 			error = ENOMEM;
    704 			goto out2;
    705 		}
    706 
    707 		/*
    708 		 * Create all objects in sensor's dictionary.
    709 		 */
    710 		sme_evdrv = kmem_zalloc(sizeof(*sme_evdrv), KM_SLEEP);
    711 		sme_evdrv->evdrv = sme_add_sensor_dictionary(sme,
    712 					array, dict, edata);
    713 		if (sme_evdrv->evdrv)
    714 			SLIST_INSERT_HEAD(&sme_evdrv_list,
    715 					  sme_evdrv, evdrv_head);
    716 	}
    717 
    718 	/*
    719 	 * Check if requested sysmon_envsys device is valid
    720 	 * and does not exist already in the list.
    721 	 */
    722 	mutex_enter(&sme_mtx);
    723 	LIST_FOREACH(lsme, &sysmon_envsys_list, sme_list) {
    724 	       if (strcmp(lsme->sme_name, sme->sme_name) == 0) {
    725 		       error = EEXIST;
    726 		       goto out;
    727 	       }
    728 	}
    729 
    730 	/*
    731 	 * If the array does not contain any object (sensor), there's
    732 	 * no need to attach the driver.
    733 	 */
    734 	if (prop_array_count(array) == 0) {
    735 		error = EINVAL;
    736 		DPRINTF(("%s: empty array for '%s'\n", __func__,
    737 		    sme->sme_name));
    738 		goto out;
    739 	}
    740 
    741 	/*
    742 	 * Add the dictionary for the global properties of this device.
    743 	 */
    744 	dict2 = prop_dictionary_create();
    745 	if (!dict2) {
    746 		error = ENOMEM;
    747 		goto out;
    748 	}
    749 
    750 	error = sme_add_property_dictionary(sme, array, dict2);
    751 	if (error) {
    752 		prop_object_release(dict2);
    753 		goto out;
    754 	}
    755 
    756 	/*
    757 	 * Add the array into the global dictionary for the driver.
    758 	 *
    759 	 * <dict>
    760 	 * 	<key>foo0</key>
    761 	 * 	<array>
    762 	 * 		...
    763 	 */
    764 	if (!prop_dictionary_set(sme_propd, sme->sme_name, array)) {
    765 		error = EINVAL;
    766 		DPRINTF(("%s: prop_dictionary_set for '%s'\n", __func__,
    767 		    sme->sme_name));
    768 		goto out;
    769 	}
    770 	/*
    771 	 * Add the device into the list.
    772 	 */
    773 	LIST_INSERT_HEAD(&sysmon_envsys_list, sme, sme_list);
    774 	sme->sme_fsensor = sysmon_envsys_next_sensor_index;
    775 	sysmon_envsys_next_sensor_index += sme->sme_nsensors;
    776 out:
    777 	mutex_exit(&sme_mtx);
    778 
    779 	/*
    780 	 * No errors? register the events that were set in the driver.
    781 	 */
    782 	if (error == 0) {
    783 		i = 0;
    784 		SLIST_FOREACH(sme_evdrv, &sme_evdrv_list, evdrv_head) {
    785 			if (i == 0)
    786 				sysmon_task_queue_init();
    787 			sysmon_task_queue_sched(0,
    788 			    sme_event_drvadd, sme_evdrv->evdrv);
    789 		}
    790 		DPRINTF(("%s: driver '%s' registered (nsens=%d)\n",
    791 		    __func__, sme->sme_name, sme->sme_nsensors));
    792 	}
    793 
    794 out2:
    795 	while (!SLIST_EMPTY(&sme_evdrv_list)) {
    796 		sme_evdrv = SLIST_FIRST(&sme_evdrv_list);
    797 		SLIST_REMOVE_HEAD(&sme_evdrv_list, evdrv_head);
    798 		kmem_free(sme_evdrv, sizeof(*sme_evdrv));
    799 	}
    800 	if (!error)
    801 		return 0;
    802 
    803 	/*
    804 	 * Ugh... something wasn't right; unregister all events and sensors
    805 	 * previously assigned and destroy the array with all its objects.
    806 	 */
    807 	DPRINTF(("%s: failed to register '%s' (%d)\n", __func__,
    808 	    sme->sme_name, error));
    809 	if (error != EEXIST) {
    810 		mutex_enter(&sme_mtx);
    811 		sme_event_unregister_all(sme);
    812 		while (!TAILQ_EMPTY(&sme->sme_sensors_list)) {
    813 			edata = TAILQ_FIRST(&sme->sme_sensors_list);
    814 			TAILQ_REMOVE(&sme->sme_sensors_list, edata,
    815 			    sensors_head);
    816 		}
    817 		mutex_exit(&sme_mtx);
    818 	}
    819 	sysmon_envsys_destroy_plist(array);
    820 	return error;
    821 }
    822 
    823 /*
    824  * sysmon_envsys_destroy_plist:
    825  *
    826  * 	+ Remove all objects from the array of dictionaries that is
    827  * 	  created in a sysmon envsys device.
    828  */
    829 static void
    830 sysmon_envsys_destroy_plist(prop_array_t array)
    831 {
    832 	prop_object_iterator_t iter, iter2;
    833 	prop_dictionary_t dict;
    834 	prop_object_t obj;
    835 
    836 	KASSERT(array != NULL);
    837 
    838 	DPRINTFOBJ(("%s: objects in array=%d\n", __func__,
    839 	    prop_array_count(array)));
    840 
    841 	iter = prop_array_iterator(array);
    842 	if (!iter)
    843 		return;
    844 
    845 	while ((dict = prop_object_iterator_next(iter))) {
    846 		KASSERT(prop_object_type(dict) == PROP_TYPE_DICTIONARY);
    847 		iter2 = prop_dictionary_iterator(dict);
    848 		if (!iter2)
    849 			goto out;
    850 		DPRINTFOBJ(("%s: iterating over dictionary\n", __func__));
    851 		while ((obj = prop_object_iterator_next(iter2)) != NULL) {
    852 			DPRINTFOBJ(("%s: obj=%s\n", __func__,
    853 			    prop_dictionary_keysym_cstring_nocopy(obj)));
    854 			prop_dictionary_remove(dict,
    855 			    prop_dictionary_keysym_cstring_nocopy(obj));
    856 			prop_object_iterator_reset(iter2);
    857 		}
    858 		prop_object_iterator_release(iter2);
    859 		DPRINTFOBJ(("%s: objects in dictionary:%d\n",
    860 		    __func__, prop_dictionary_count(dict)));
    861 		prop_object_release(dict);
    862 	}
    863 
    864 out:
    865 	prop_object_iterator_release(iter);
    866 	prop_object_release(array);
    867 }
    868 
    869 /*
    870  * sysmon_envsys_unregister:
    871  *
    872  *	+ Unregister a sysmon envsys device.
    873  */
    874 void
    875 sysmon_envsys_unregister(struct sysmon_envsys *sme)
    876 {
    877 	prop_array_t array;
    878 
    879 	KASSERT(sme != NULL);
    880 
    881 	mutex_enter(&sme_mtx);
    882 	/*
    883 	 * Wait for device to be available.
    884 	 */
    885 	while (sme->sme_flags & SME_FLAG_BUSY)
    886 		cv_wait(&sme_cv, &sme_mtx);
    887 	/*
    888 	 * Stop the callout.
    889 	 */
    890 	callout_stop(&sme->sme_callout);
    891 	/*
    892 	 * Decrement global sensors counter (only useful for compatibility).
    893 	 */
    894 	sysmon_envsys_next_sensor_index -= sme->sme_nsensors;
    895 	/*
    896 	 * Unregister all events associated with this device.
    897 	 */
    898 	sme_event_unregister_all(sme);
    899 	LIST_REMOVE(sme, sme_list);
    900 	mutex_exit(&sme_mtx);
    901 	/*
    902 	 * Remove the device (and all its objects) from the global dictionary.
    903 	 */
    904 	array = prop_dictionary_get(sme_propd, sme->sme_name);
    905 	if (array && prop_object_type(array) == PROP_TYPE_ARRAY) {
    906 		prop_dictionary_remove(sme_propd, sme->sme_name);
    907 		sysmon_envsys_destroy_plist(array);
    908 	}
    909 	/*
    910 	 * And finally destroy the sysmon_envsys object.
    911 	 */
    912 	sysmon_envsys_destroy(sme);
    913 }
    914 
    915 /*
    916  * sysmon_envsys_find:
    917  *
    918  *	+ Find a sysmon envsys device and mark it as busy if found.
    919  */
    920 struct sysmon_envsys *
    921 sysmon_envsys_find(const char *name)
    922 {
    923 	struct sysmon_envsys *sme;
    924 
    925 	KASSERT(mutex_owned(&sme_mtx));
    926 
    927 again:
    928 	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
    929 			if (strcmp(sme->sme_name, name) == 0) {
    930 				if (sme->sme_flags & SME_FLAG_BUSY) {
    931 					cv_wait(&sme_cv, &sme_mtx);
    932 					goto again;
    933 				}
    934 				sme->sme_flags |= SME_FLAG_BUSY;
    935 				break;
    936 			}
    937 	}
    938 	return sme;
    939 }
    940 
    941 /*
    942  * sysmon_envsys_acquire:
    943  *
    944  * 	+ Acquire priviledge to a sysmon envsys device (locked).
    945  */
    946 void
    947 sysmon_envsys_acquire(struct sysmon_envsys *sme)
    948 {
    949 	KASSERT(mutex_owned(&sme_mtx));
    950 
    951 	while (sme->sme_flags & SME_FLAG_BUSY)
    952 		cv_wait(&sme_cv, &sme_mtx);
    953 
    954 	sme->sme_flags |= SME_FLAG_BUSY;
    955 }
    956 
    957 /*
    958  * sysmon_envsys_release:
    959  *
    960  * 	+ Release a sysmon envsys device (locked).
    961  */
    962 void
    963 sysmon_envsys_release(struct sysmon_envsys *sme)
    964 {
    965 	KASSERT(mutex_owned(&sme_mtx));
    966 
    967 	sme->sme_flags &= ~SME_FLAG_BUSY;
    968 	cv_broadcast(&sme_cv);
    969 }
    970 
    971 /* compatibility function */
    972 struct sysmon_envsys *
    973 sysmon_envsys_find_40(u_int idx)
    974 {
    975 	struct sysmon_envsys *sme;
    976 
    977 	KASSERT(mutex_owned(&sme_mtx));
    978 
    979 	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
    980 		if (idx >= sme->sme_fsensor &&
    981 	    	    idx < (sme->sme_fsensor + sme->sme_nsensors)) {
    982 			sme->sme_flags |= SME_FLAG_BUSY;
    983 			break;
    984 		}
    985 	}
    986 	return sme;
    987 }
    988 
    989 /*
    990  * sme_sensor_dictionary_get:
    991  *
    992  * 	+ Returns a dictionary of a device specified by its index
    993  * 	  position.
    994  */
    995 prop_dictionary_t
    996 sme_sensor_dictionary_get(prop_array_t array, const char *index)
    997 {
    998 	prop_object_iterator_t iter;
    999 	prop_dictionary_t dict;
   1000 	prop_object_t obj;
   1001 
   1002 	KASSERT(array != NULL || index != NULL);
   1003 
   1004 	iter = prop_array_iterator(array);
   1005 	if (!iter)
   1006 		return NULL;
   1007 
   1008 	while ((dict = prop_object_iterator_next(iter))) {
   1009 		obj = prop_dictionary_get(dict, "index");
   1010 		if (prop_string_equals_cstring(obj, index))
   1011 			break;
   1012 	}
   1013 
   1014 	prop_object_iterator_release(iter);
   1015 	return dict;
   1016 }
   1017 
   1018 /*
   1019  * sme_remove_userprops:
   1020  *
   1021  * 	+ Remove all properties from all devices that were set by
   1022  * 	  the ENVSYS_SETDICTIONARY ioctl.
   1023  */
   1024 static void
   1025 sme_remove_userprops(void)
   1026 {
   1027 	struct sysmon_envsys *sme;
   1028 	prop_array_t array;
   1029 	prop_dictionary_t sdict;
   1030 	envsys_data_t *edata = NULL;
   1031 	char tmp[ENVSYS_DESCLEN];
   1032 	int ptype;
   1033 
   1034 	mutex_enter(&sme_mtx);
   1035 	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
   1036 		sysmon_envsys_acquire(sme);
   1037 		array = prop_dictionary_get(sme_propd, sme->sme_name);
   1038 
   1039 		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
   1040 			(void)snprintf(tmp, sizeof(tmp), "sensor%d",
   1041 				       edata->sensor);
   1042 			sdict = sme_sensor_dictionary_get(array, tmp);
   1043 			KASSERT(sdict != NULL);
   1044 
   1045 			if (edata->upropset & USERPROP_BATTCAP) {
   1046 				prop_dictionary_remove(sdict,
   1047 				    "critical-capacity");
   1048 				ptype = PENVSYS_EVENT_BATT_USERCAP;
   1049 				sme_event_unregister(sme, edata->desc, ptype);
   1050 			}
   1051 
   1052 			if (edata->upropset & USERPROP_CRITMAX) {
   1053 				prop_dictionary_remove(sdict,
   1054 				    "critical-max");
   1055 				ptype = PENVSYS_EVENT_USER_CRITMAX;
   1056 				sme_event_unregister(sme, edata->desc, ptype);
   1057 			}
   1058 
   1059 			if (edata->upropset & USERPROP_CRITMIN) {
   1060 				prop_dictionary_remove(sdict,
   1061 				    "critical-min");
   1062 				ptype = PENVSYS_EVENT_USER_CRITMIN;
   1063 				sme_event_unregister(sme, edata->desc, ptype);
   1064 			}
   1065 
   1066 			if (edata->upropset & USERPROP_RFACT) {
   1067 				(void)sme_sensor_upint32(sdict, "rfact", 0);
   1068 				edata->rfact = 0;
   1069 			}
   1070 
   1071 			if (edata->upropset & USERPROP_DESC)
   1072 				(void)sme_sensor_upstring(sdict,
   1073 			  	    "description", edata->desc);
   1074 
   1075 			if (edata->upropset)
   1076 				edata->upropset = 0;
   1077 		}
   1078 
   1079 		/*
   1080 		 * Restore default timeout value.
   1081 		 */
   1082 		sme->sme_events_timeout = SME_EVENTS_DEFTIMEOUT;
   1083 		sysmon_envsys_release(sme);
   1084 	}
   1085 	mutex_exit(&sme_mtx);
   1086 }
   1087 
   1088 /*
   1089  * sme_add_property_dictionary:
   1090  *
   1091  * 	+ Add global properties into a device.
   1092  */
   1093 static int
   1094 sme_add_property_dictionary(struct sysmon_envsys *sme, prop_array_t array,
   1095 			    prop_dictionary_t dict)
   1096 {
   1097 	prop_dictionary_t pdict;
   1098 	int error = 0;
   1099 
   1100 	pdict = prop_dictionary_create();
   1101 	if (!pdict)
   1102 		return EINVAL;
   1103 
   1104 	/*
   1105 	 * Add the 'refresh-timeout' object into the 'device-properties'
   1106 	 * dictionary. We use by default 30 seconds.
   1107 	 *
   1108 	 * 	...
   1109 	 * 	<dict>
   1110 	 * 		<key>device-properties</key>
   1111 	 * 		<dict>
   1112 	 * 			<key>refresh-timeout</key>
   1113 	 * 			<integer>120</integer<
   1114 	 * 		</dict<
   1115 	 * 	</dict>
   1116 	 * 	...
   1117 	 *
   1118 	 */
   1119 	if (!sme->sme_events_timeout)
   1120 		sme->sme_events_timeout = SME_EVENTS_DEFTIMEOUT;
   1121 
   1122 	if (!prop_dictionary_set_uint64(pdict, "refresh-timeout",
   1123 					sme->sme_events_timeout)) {
   1124 		error = EINVAL;
   1125 		goto out;
   1126 	}
   1127 
   1128 	if (!prop_dictionary_set(dict, "device-properties", pdict)) {
   1129 		error = EINVAL;
   1130 		goto out;
   1131 	}
   1132 
   1133 	/*
   1134 	 * Add the device dictionary into the sysmon envsys array.
   1135 	 */
   1136 	if (!prop_array_add(array, dict))
   1137 		error = EINVAL;
   1138 
   1139 out:
   1140 	prop_object_release(pdict);
   1141 	return error;
   1142 }
   1143 
   1144 /*
   1145  * sme_add_sensor_dictionary:
   1146  *
   1147  * 	+ Adds the sensor objects into the dictionary and returns a pointer
   1148  * 	  to a sme_event_drv_t object if a monitoring flag was set
   1149  * 	  (or NULL otherwise).
   1150  */
   1151 sme_event_drv_t *
   1152 sme_add_sensor_dictionary(struct sysmon_envsys *sme, prop_array_t array,
   1153 		    	  prop_dictionary_t dict, envsys_data_t *edata)
   1154 {
   1155 	const struct sme_description_table *sdt, *sdt_units;
   1156 	sme_event_drv_t *sme_evdrv_t = NULL;
   1157 	int i, j;
   1158 	char indexstr[ENVSYS_DESCLEN];
   1159 
   1160 	/*
   1161 	 * Find the correct units for this sensor.
   1162 	 */
   1163 	sdt_units = sme_get_description_table(SME_DESC_UNITS);
   1164 	for (i = 0; sdt_units[i].type != -1; i++)
   1165 		if (sdt_units[i].type == edata->units)
   1166 			break;
   1167 
   1168 	/*
   1169 	 * Add the index sensor string.
   1170 	 *
   1171 	 * 		...
   1172 	 * 		<key>index</eyr
   1173 	 * 		<string>sensor0</string>
   1174 	 * 		...
   1175 	 */
   1176 	(void)snprintf(indexstr, sizeof(indexstr), "sensor%d", edata->sensor);
   1177 	if (sme_sensor_upstring(dict, "index", indexstr))
   1178 		goto bad;
   1179 
   1180 	/*
   1181 	 * 		...
   1182 	 * 		<key>type</key>
   1183 	 * 		<string>foo</string>
   1184 	 * 		<key>description</key>
   1185 	 * 		<string>blah blah</string>
   1186 	 * 		...
   1187 	 */
   1188 	if (sme_sensor_upstring(dict, "type", sdt_units[i].desc))
   1189 		goto bad;
   1190 
   1191 	if (sme_sensor_upstring(dict, "description", edata->desc))
   1192 		goto bad;
   1193 
   1194 	/*
   1195 	 * Add sensor's state description.
   1196 	 *
   1197 	 * 		...
   1198 	 * 		<key>state</key>
   1199 	 * 		<string>valid</string>
   1200 	 * 		...
   1201 	 */
   1202 	sdt = sme_get_description_table(SME_DESC_STATES);
   1203 	for (j = 0; sdt[j].type != -1; j++)
   1204 		if (sdt[j].type == edata->state)
   1205 			break;
   1206 
   1207 	DPRINTF(("%s: sensor desc=%s type=%d state=%d\n",
   1208 	    __func__, edata->desc, edata->units, edata->state));
   1209 
   1210 	if (sme_sensor_upstring(dict, "state", sdt[j].desc))
   1211 		goto bad;
   1212 
   1213 	/*
   1214 	 * Add the monitoring boolean object:
   1215 	 *
   1216 	 * 		...
   1217 	 * 		<key>monitoring-supported</key>
   1218 	 * 		<true/>
   1219 	 *		...
   1220 	 *
   1221 	 * always false on Battery {capacity,charge}, Drive and Indicator types.
   1222 	 * They cannot be monitored.
   1223 	 *
   1224 	 */
   1225 	if ((edata->flags & ENVSYS_FMONNOTSUPP) ||
   1226 	    (edata->units == ENVSYS_INDICATOR) ||
   1227 	    (edata->units == ENVSYS_DRIVE) ||
   1228 	    (edata->units == ENVSYS_BATTERY_CAPACITY) ||
   1229 	    (edata->units == ENVSYS_BATTERY_CHARGE)) {
   1230 		if (sme_sensor_upbool(dict, "monitoring-supported", false))
   1231 			goto out;
   1232 	} else {
   1233 		if (sme_sensor_upbool(dict, "monitoring-supported", true))
   1234 			goto out;
   1235 	}
   1236 
   1237 	/*
   1238 	 * Add the percentage boolean object, true if ENVSYS_FPERCENT
   1239 	 * is set or false otherwise.
   1240 	 *
   1241 	 * 		...
   1242 	 * 		<key>want-percentage</key>
   1243 	 * 		<true/>
   1244 	 * 		...
   1245 	 */
   1246 	if (edata->flags & ENVSYS_FPERCENT)
   1247 		if (sme_sensor_upbool(dict, "want-percentage", true))
   1248 			goto out;
   1249 
   1250 	/*
   1251 	 * Add the allow-rfact boolean object, true if
   1252 	 * ENVSYS_FCHANGERFACT if set or false otherwise.
   1253 	 *
   1254 	 * 		...
   1255 	 * 		<key>allow-rfact</key>
   1256 	 * 		<true/>
   1257 	 * 		...
   1258 	 */
   1259 	if (edata->units == ENVSYS_SVOLTS_DC ||
   1260 	    edata->units == ENVSYS_SVOLTS_AC) {
   1261 		if (edata->flags & ENVSYS_FCHANGERFACT) {
   1262 			if (sme_sensor_upbool(dict, "allow-rfact", true))
   1263 				goto out;
   1264 		} else {
   1265 			if (sme_sensor_upbool(dict, "allow-rfact", false))
   1266 				goto out;
   1267 		}
   1268 	}
   1269 
   1270 	/*
   1271 	 * Add the object for battery capacity sensors:
   1272 	 *
   1273 	 * 		...
   1274 	 * 		<key>battery-capacity</key>
   1275 	 * 		<string>NORMAL</string>
   1276 	 * 		...
   1277 	 */
   1278 	if (edata->units == ENVSYS_BATTERY_CAPACITY) {
   1279 		sdt = sme_get_description_table(SME_DESC_BATTERY_CAPACITY);
   1280 		for (j = 0; sdt[j].type != -1; j++)
   1281 			if (sdt[j].type == edata->value_cur)
   1282 				break;
   1283 
   1284 		if (sme_sensor_upstring(dict, "battery-capacity", sdt[j].desc))
   1285 			goto out;
   1286 	}
   1287 
   1288 	/*
   1289 	 * Add the drive-state object for drive sensors:
   1290 	 *
   1291 	 * 		...
   1292 	 * 		<key>drive-state</key>
   1293 	 * 		<string>drive is online</string>
   1294 	 * 		...
   1295 	 */
   1296 	if (edata->units == ENVSYS_DRIVE) {
   1297 		sdt = sme_get_description_table(SME_DESC_DRIVE_STATES);
   1298 		for (j = 0; sdt[j].type != -1; j++)
   1299 			if (sdt[j].type == edata->value_cur)
   1300 				break;
   1301 
   1302 		if (sme_sensor_upstring(dict, "drive-state", sdt[j].desc))
   1303 			goto out;
   1304 	}
   1305 
   1306 	/*
   1307 	 * Add the following objects if sensor is enabled...
   1308 	 */
   1309 	if (edata->state == ENVSYS_SVALID) {
   1310 		/*
   1311 		 * Add the following objects:
   1312 		 *
   1313 		 * 	...
   1314 		 * 	<key>rpms</key>
   1315 		 * 	<integer>2500</integer>
   1316 		 * 	<key>rfact</key>
   1317 		 * 	<integer>10000</integer>
   1318 		 * 	<key>cur-value</key>
   1319 	 	 * 	<integer>1250</integer>
   1320 	 	 * 	<key>min-value</key>
   1321 	 	 * 	<integer>800</integer>
   1322 	 	 * 	<key>max-value</integer>
   1323 	 	 * 	<integer>3000</integer>
   1324 	 	 * 	<key>avg-value</integer>
   1325 	 	 * 	<integer>1400</integer>
   1326 	 	 * 	...
   1327 	 	 */
   1328 		if (edata->units == ENVSYS_SFANRPM)
   1329 			if (sme_sensor_upuint32(dict, "rpms", edata->rpms))
   1330 				goto out;
   1331 
   1332 		if (edata->units == ENVSYS_SVOLTS_AC ||
   1333 	    	    edata->units == ENVSYS_SVOLTS_DC)
   1334 			if (sme_sensor_upint32(dict, "rfact", edata->rfact))
   1335 				goto out;
   1336 
   1337 		if (sme_sensor_upint32(dict, "cur-value", edata->value_cur))
   1338 			goto out;
   1339 
   1340 		if (edata->flags & ENVSYS_FVALID_MIN) {
   1341 			if (sme_sensor_upint32(dict,
   1342 					       "min-value",
   1343 					       edata->value_min))
   1344 			goto out;
   1345 		}
   1346 
   1347 		if (edata->flags & ENVSYS_FVALID_MAX) {
   1348 			if (sme_sensor_upint32(dict,
   1349 					       "max-value",
   1350 					       edata->value_max))
   1351 			goto out;
   1352 		}
   1353 
   1354 		if (edata->flags & ENVSYS_FVALID_AVG) {
   1355 			if (sme_sensor_upint32(dict,
   1356 					       "avg-value",
   1357 					       edata->value_avg))
   1358 			goto out;
   1359 		}
   1360 	}
   1361 
   1362 	/*
   1363 	 * 	...
   1364 	 * </dict>
   1365 	 *
   1366 	 * Add the dictionary into the array.
   1367 	 *
   1368 	 */
   1369 	if (!prop_array_add(array, dict)) {
   1370 		DPRINTF(("%s: prop_array_add\n", __func__));
   1371 		goto bad;
   1372 	}
   1373 
   1374 	/*
   1375 	 * Register a new event if a monitoring flag was set.
   1376 	 */
   1377 	if (edata->monitor) {
   1378 		sme_evdrv_t = kmem_zalloc(sizeof(*sme_evdrv_t), KM_SLEEP);
   1379 		sme_evdrv_t->sed_sdict = dict;
   1380 		sme_evdrv_t->sed_edata = edata;
   1381 		sme_evdrv_t->sed_sme = sme;
   1382 		sme_evdrv_t->sed_powertype = sdt_units[i].crittype;
   1383 	}
   1384 
   1385 out:
   1386 	return sme_evdrv_t;
   1387 
   1388 bad:
   1389 	prop_object_release(dict);
   1390 	return NULL;
   1391 }
   1392 
   1393 /*
   1394  * sme_update_dictionary:
   1395  *
   1396  * 	+ Update per-sensor dictionaries with new values if there were
   1397  * 	  changes, otherwise the object in dictionary is untouched.
   1398  */
   1399 int
   1400 sme_update_dictionary(struct sysmon_envsys *sme)
   1401 {
   1402 	const struct sme_description_table *sdt;
   1403 	envsys_data_t *edata;
   1404 	prop_object_t array, dict, obj, obj2;
   1405 	int j, error = 0;
   1406 
   1407 	KASSERT(mutex_owned(&sme_mtx));
   1408 
   1409 	/*
   1410 	 * Retrieve the array of dictionaries in device.
   1411 	 */
   1412 	array = prop_dictionary_get(sme_propd, sme->sme_name);
   1413 	if (prop_object_type(array) != PROP_TYPE_ARRAY) {
   1414 		DPRINTF(("%s: not an array (%s)\n", __func__, sme->sme_name));
   1415 		return EINVAL;
   1416 	}
   1417 
   1418 	/*
   1419 	 * Get the last dictionary on the array, this contains the
   1420 	 * 'device-properties' sub-dictionary.
   1421 	 */
   1422 	obj = prop_array_get(array, prop_array_count(array) - 1);
   1423 	if (!obj || prop_object_type(obj) != PROP_TYPE_DICTIONARY) {
   1424 		DPRINTF(("%s: not a device-properties dictionary\n", __func__));
   1425 		return EINVAL;
   1426 	}
   1427 
   1428 	obj2 = prop_dictionary_get(obj, "device-properties");
   1429 	if (!obj2)
   1430 		return EINVAL;
   1431 
   1432 	/*
   1433 	 * Update the 'refresh-timeout' property.
   1434 	 */
   1435 	if (!prop_dictionary_set_uint64(obj2, "refresh-timeout",
   1436 					sme->sme_events_timeout))
   1437 		return EINVAL;
   1438 
   1439 	/*
   1440 	 * - iterate over all sensors.
   1441 	 * - fetch new data.
   1442 	 * - check if data in dictionary is different than new data.
   1443 	 * - update dictionary if there were changes.
   1444 	 */
   1445 	DPRINTF(("%s: updating '%s' with nsensors=%d\n", __func__,
   1446 	    sme->sme_name, sme->sme_nsensors));
   1447 
   1448 	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
   1449 		/*
   1450 		 * refresh sensor data via sme_refresh only if the
   1451 		 * flag is not set.
   1452 		 */
   1453 		if ((sme->sme_flags & SME_DISABLE_REFRESH) == 0)
   1454 			(*sme->sme_refresh)(sme, edata);
   1455 
   1456 		/*
   1457 		 * retrieve sensor's dictionary.
   1458 		 */
   1459 		dict = prop_array_get(array, edata->sensor);
   1460 		if (prop_object_type(dict) != PROP_TYPE_DICTIONARY) {
   1461 			DPRINTF(("%s: not a dictionary (%d:%s)\n",
   1462 			    __func__, edata->sensor, sme->sme_name));
   1463 			return EINVAL;
   1464 		}
   1465 
   1466 		/*
   1467 		 * update sensor's state.
   1468 		 */
   1469 		sdt = sme_get_description_table(SME_DESC_STATES);
   1470 		for (j = 0; sdt[j].type != -1; j++)
   1471 			if (sdt[j].type == edata->state)
   1472 				break;
   1473 
   1474 		DPRINTFOBJ(("%s: state=%s type=%d flags=%d "
   1475 		    "units=%d sensor=%d\n", __func__, sdt[j].desc,
   1476 		    sdt[j].type, edata->flags, edata->units, edata->sensor));
   1477 
   1478 		error = sme_sensor_upstring(dict, "state", sdt[j].desc);
   1479 		if (error)
   1480 			break;
   1481 
   1482 		/*
   1483 		 * update sensor's type.
   1484 		 */
   1485 		sdt = sme_get_description_table(SME_DESC_UNITS);
   1486 		for (j = 0; sdt[j].type != -1; j++)
   1487 			if (sdt[j].type == edata->units)
   1488 				break;
   1489 
   1490 		error = sme_sensor_upstring(dict, "type", sdt[j].desc);
   1491 		if (error)
   1492 			break;
   1493 
   1494 		/*
   1495 		 * update sensor's current value.
   1496 		 */
   1497 		error = sme_sensor_upint32(dict,
   1498 					   "cur-value",
   1499 					   edata->value_cur);
   1500 		if (error)
   1501 			break;
   1502 
   1503 		/*
   1504 		 * Battery charge, Integer and Indicator types do not
   1505 		 * need the following objects, so skip them.
   1506 		 */
   1507 		if (edata->units == ENVSYS_INTEGER ||
   1508 		    edata->units == ENVSYS_INDICATOR ||
   1509 		    edata->units == ENVSYS_BATTERY_CHARGE)
   1510 			continue;
   1511 
   1512 		/*
   1513 		 * update sensor flags.
   1514 		 */
   1515 		if (edata->flags & ENVSYS_FPERCENT) {
   1516 			error = sme_sensor_upbool(dict,
   1517 						  "want-percentage",
   1518 						  true);
   1519 			if (error)
   1520 				break;
   1521 		}
   1522 
   1523 		/*
   1524 		 * update sensor's {avg,max,min}-value.
   1525 		 */
   1526 		if (edata->flags & ENVSYS_FVALID_MAX) {
   1527 			error = sme_sensor_upint32(dict,
   1528 						   "max-value",
   1529 						   edata->value_max);
   1530 			if (error)
   1531 				break;
   1532 		}
   1533 
   1534 		if (edata->flags & ENVSYS_FVALID_MIN) {
   1535 			error = sme_sensor_upint32(dict,
   1536 						   "min-value",
   1537 						   edata->value_min);
   1538 			if (error)
   1539 				break;
   1540 		}
   1541 
   1542 		if (edata->flags & ENVSYS_FVALID_AVG) {
   1543 			error = sme_sensor_upint32(dict,
   1544 						   "avg-value",
   1545 						   edata->value_avg);
   1546 			if (error)
   1547 				break;
   1548 		}
   1549 
   1550 		/*
   1551 		 * update 'rpms' only for ENVSYS_SFANRPM sensors.
   1552 		 */
   1553 		if (edata->units == ENVSYS_SFANRPM) {
   1554 			error = sme_sensor_upuint32(dict,
   1555 						    "rpms",
   1556 						    edata->rpms);
   1557 			if (error)
   1558 				break;
   1559 		}
   1560 
   1561 		/*
   1562 		 * update 'rfact' only for ENVSYS_SVOLTS_[AD]C sensors.
   1563 		 */
   1564 		if (edata->units == ENVSYS_SVOLTS_AC ||
   1565 		    edata->units == ENVSYS_SVOLTS_DC) {
   1566 			error = sme_sensor_upint32(dict,
   1567 						   "rfact",
   1568 						   edata->rfact);
   1569 			if (error)
   1570 				break;
   1571 		}
   1572 
   1573 		/*
   1574 		 * update 'drive-state' only for ENVSYS_DRIVE sensors.
   1575 		 */
   1576 		if (edata->units == ENVSYS_DRIVE) {
   1577 			sdt = sme_get_description_table(SME_DESC_DRIVE_STATES);
   1578 			for (j = 0; sdt[j].type != -1; j++)
   1579 				if (sdt[j].type == edata->value_cur)
   1580 					break;
   1581 
   1582 			error = sme_sensor_upstring(dict,
   1583 						    "drive-state",
   1584 						    sdt[j].desc);
   1585 			if (error)
   1586 				break;
   1587 		}
   1588 
   1589 		/*
   1590 		 * update 'battery-capacity' only for ENVSYS_BATTERY_CAPACITY
   1591 		 * sensors.
   1592 		 */
   1593 		if (edata->units == ENVSYS_BATTERY_CAPACITY) {
   1594 			sdt =
   1595 			  sme_get_description_table(SME_DESC_BATTERY_CAPACITY);
   1596 			for (j = 0; sdt[j].type != -1; j++)
   1597 				if (sdt[j].type == edata->value_cur)
   1598 					break;
   1599 
   1600 			error = sme_sensor_upstring(dict,
   1601 						    "battery-capacity",
   1602 						    sdt[j].desc);
   1603 			if (error)
   1604 				break;
   1605 		}
   1606 	}
   1607 
   1608 	return error;
   1609 }
   1610 
   1611 /*
   1612  * sme_userset_dictionary:
   1613  *
   1614  * 	+ Parse the userland dictionary and run the appropiate tasks
   1615  * 	  that were specified.
   1616  */
   1617 int
   1618 sme_userset_dictionary(struct sysmon_envsys *sme, prop_dictionary_t udict,
   1619 		       prop_array_t array)
   1620 {
   1621 	const struct sme_description_table *sdt;
   1622 	envsys_data_t *edata;
   1623 	prop_dictionary_t dict, tdict = NULL;
   1624 	prop_object_t obj, obj1, obj2, tobj = NULL;
   1625 	uint64_t refresh_timo = 0;
   1626 	int32_t critval;
   1627 	int i, error = 0;
   1628 	const char *blah;
   1629 	bool targetfound = false;
   1630 
   1631 	KASSERT(mutex_owned(&sme_mtx));
   1632 
   1633 	/*
   1634 	 * The user wanted to change the refresh timeout value for this
   1635 	 * device.
   1636 	 *
   1637 	 * Get the 'device-properties' object from the userland dictionary.
   1638 	 */
   1639 	obj = prop_dictionary_get(udict, "device-properties");
   1640 	if (obj && prop_object_type(obj) == PROP_TYPE_DICTIONARY) {
   1641 		/*
   1642 		 * Get the 'refresh-timeout' property for this device.
   1643 		 */
   1644 		obj1 = prop_dictionary_get(obj, "refresh-timeout");
   1645 		if (obj1 && prop_object_type(obj1) == PROP_TYPE_NUMBER) {
   1646 			targetfound = true;
   1647 			refresh_timo =
   1648 			    prop_number_unsigned_integer_value(obj1);
   1649 			if (refresh_timo < 1)
   1650 				error = EINVAL;
   1651 			else
   1652 				sme->sme_events_timeout = refresh_timo;
   1653 		}
   1654 		goto out;
   1655 
   1656 	} else if (!obj) {
   1657 		/*
   1658 		 * Get sensor's index from userland dictionary.
   1659 		 */
   1660 		obj = prop_dictionary_get(udict, "index");
   1661 		if (!obj)
   1662 			goto out;
   1663 		if (prop_object_type(obj) != PROP_TYPE_STRING) {
   1664 			DPRINTF(("%s: 'index' not a string\n", __func__));
   1665 			return EINVAL;
   1666 		}
   1667 	} else
   1668 		return EINVAL;
   1669 
   1670 	/*
   1671 	 * iterate over the sensors to find the right one.
   1672 	 */
   1673 	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
   1674 		/*
   1675 		 * Get a dictionary and check if it's our sensor by checking
   1676 		 * at its index position.
   1677 		 */
   1678 		dict = prop_array_get(array, edata->sensor);
   1679 		obj1 = prop_dictionary_get(dict, "index");
   1680 
   1681 		/*
   1682 		 * is it our sensor?
   1683 		 */
   1684 		if (!prop_string_equals(obj1, obj))
   1685 			continue;
   1686 
   1687 		/*
   1688 		 * Check if a new description operation was
   1689 		 * requested by the user and set new description.
   1690 		 */
   1691 		obj2 = prop_dictionary_get(udict, "description");
   1692 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_STRING) {
   1693 			targetfound = true;
   1694 			blah = prop_string_cstring_nocopy(obj2);
   1695 
   1696 			/*
   1697 			 * Check for duplicate description.
   1698 			 */
   1699 			for (i = 0; i < sme->sme_nsensors; i++) {
   1700 				if (i == edata->sensor)
   1701 					continue;
   1702 				tdict = prop_array_get(array, i);
   1703 				tobj =
   1704 				    prop_dictionary_get(tdict, "description");
   1705 				if (prop_string_equals(obj2, tobj))
   1706 					return EEXIST;
   1707 			}
   1708 
   1709 			/*
   1710 			 * Update the object in dictionary.
   1711 			 */
   1712 			error = sme_sensor_upstring(dict,
   1713 						    "description",
   1714 						    blah);
   1715 			if (error)
   1716 				return error;
   1717 
   1718 			DPRINTF(("%s: sensor%d changed desc to: %s\n",
   1719 			    __func__, edata->sensor, blah));
   1720 			edata->upropset |= USERPROP_DESC;
   1721 		}
   1722 
   1723 		/*
   1724 		 * did the user want to change the rfact?
   1725 		 */
   1726 		obj2 = prop_dictionary_get(udict, "rfact");
   1727 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
   1728 			targetfound = true;
   1729 			if (edata->flags & ENVSYS_FCHANGERFACT) {
   1730 				edata->rfact = prop_number_integer_value(obj2);
   1731 				edata->upropset |= USERPROP_RFACT;
   1732 				DPRINTF(("%s: sensor%d changed rfact to %d\n",
   1733 				    __func__, edata->sensor, edata->rfact));
   1734 			} else
   1735 				return ENOTSUP;
   1736 		}
   1737 
   1738 		sdt = sme_get_description_table(SME_DESC_UNITS);
   1739 		for (i = 0; sdt[i].type != -1; i++)
   1740 			if (sdt[i].type == edata->units)
   1741 				break;
   1742 
   1743 		/*
   1744 		 * did the user want to set a critical capacity event?
   1745 		 *
   1746 		 * NOTE: if sme_event_register returns EEXIST that means
   1747 		 * the object is already there, but this is not a real
   1748 		 * error, because the object might be updated.
   1749 		 */
   1750 		obj2 = prop_dictionary_get(udict, "critical-capacity");
   1751 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
   1752 			targetfound = true;
   1753 			if ((edata->flags & ENVSYS_FMONNOTSUPP) ||
   1754 			    (edata->flags & ENVSYS_FPERCENT) == 0)
   1755 				return ENOTSUP;
   1756 
   1757 			critval = prop_number_integer_value(obj2);
   1758 			error = sme_event_register(dict,
   1759 					      edata,
   1760 					      sme,
   1761 					      "critical-capacity",
   1762 					      critval,
   1763 					      PENVSYS_EVENT_BATT_USERCAP,
   1764 					      sdt[i].crittype);
   1765 			if (error == EEXIST)
   1766 				error = 0;
   1767 			if (error)
   1768 				goto out;
   1769 			else if (!error)
   1770 				edata->upropset |= USERPROP_BATTCAP;
   1771 		}
   1772 
   1773 		/*
   1774 		 * did the user want to set a critical max event?
   1775 		 */
   1776 		obj2 = prop_dictionary_get(udict, "critical-max");
   1777 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
   1778 			targetfound = true;
   1779 			if (edata->units == ENVSYS_INDICATOR ||
   1780 			    edata->flags & ENVSYS_FMONNOTSUPP)
   1781 				return ENOTSUP;
   1782 
   1783 			critval = prop_number_integer_value(obj2);
   1784 			error = sme_event_register(dict,
   1785 					      edata,
   1786 					      sme,
   1787 					      "critical-max",
   1788 					      critval,
   1789 					      PENVSYS_EVENT_USER_CRITMAX,
   1790 					      sdt[i].crittype);
   1791 			if (error == EEXIST)
   1792 				error = 0;
   1793 			if (error)
   1794 				goto out;
   1795 			else if (!error)
   1796 				edata->upropset |= USERPROP_CRITMAX;
   1797 		}
   1798 
   1799 		/*
   1800 		 * did the user want to set a critical min event?
   1801 		 */
   1802 		obj2 = prop_dictionary_get(udict, "critical-min");
   1803 		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
   1804 			targetfound = true;
   1805 			if (edata->units == ENVSYS_INDICATOR ||
   1806 			    edata->flags & ENVSYS_FMONNOTSUPP)
   1807 				return ENOTSUP;
   1808 
   1809 			critval = prop_number_integer_value(obj2);
   1810 			error = sme_event_register(dict,
   1811 					      edata,
   1812 					      sme,
   1813 					      "critical-min",
   1814 					      critval,
   1815 					      PENVSYS_EVENT_USER_CRITMIN,
   1816 					      sdt[i].crittype);
   1817 			if (error == EEXIST)
   1818 				error = 0;
   1819 			if (error)
   1820 				goto out;
   1821 			else if (!error)
   1822 				edata->upropset |= USERPROP_CRITMIN;
   1823 		}
   1824 
   1825 		/*
   1826 		 * All objects in dictionary were processed.
   1827 		 */
   1828 		break;
   1829 	}
   1830 
   1831 out:
   1832 	/*
   1833 	 * invalid target? return the error.
   1834 	 */
   1835 	if (!targetfound)
   1836 		error = EINVAL;
   1837 
   1838 	return error;
   1839 }
   1840