Home | History | Annotate | Line # | Download | only in sysmon
sysmon_envsys.c revision 1.73
      1 /*	$NetBSD: sysmon_envsys.c,v 1.73 2007/11/20 17:24:32 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.73 2007/11/20 17:24:32 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' spin lock and the
     99  * 'sme_callout_cv' is used to check that the callout has finished before
    100  * unregistering a sysmon_envsys device.
    101  *
    102  */
    103 
    104 kmutex_t sme_mtx, sme_events_mtx, sme_callout_mtx;
    105 kcondvar_t sme_cv;
    106 
    107 /*
    108  * Types of properties that can be set via userland.
    109  */
    110 enum {
    111 	USERPROP_DESC 		= 0x0001,
    112 	USERPROP_BATTCAP	= 0x0002,
    113 	USERPROP_CRITMAX	= 0x0004,
    114 	USERPROP_CRITMIN	= 0x0008,
    115 	USERPROP_RFACT		= 0x0010
    116 };
    117 
    118 static prop_dictionary_t sme_propd;
    119 static uint32_t sysmon_envsys_next_sensor_index = 0;
    120 static struct sysmon_envsys *sysmon_envsys_find_40(u_int);
    121 
    122 static void sysmon_envsys_destroy_plist(prop_array_t);
    123 static void sme_remove_userprops(void);
    124 static int sme_add_property_dictionary(struct sysmon_envsys *, prop_array_t,
    125 				       prop_dictionary_t);
    126 
    127 /*
    128  * sysmon_envsys_init:
    129  *
    130  * 	+ Initialize global mutexes, dictionary and the linked lists.
    131  */
    132 void
    133 sysmon_envsys_init(void)
    134 {
    135 	LIST_INIT(&sysmon_envsys_list);
    136 	mutex_init(&sme_mtx, MUTEX_DEFAULT, IPL_NONE);
    137 	mutex_init(&sme_events_mtx, MUTEX_DEFAULT, IPL_NONE);
    138 	mutex_init(&sme_callout_mtx, MUTEX_SPIN, IPL_SOFTCLOCK);
    139 	cv_init(&sme_cv, "smeworker");
    140 	sme_propd = prop_dictionary_create();
    141 }
    142 
    143 /*
    144  * sysmonopen_envsys:
    145  *
    146  *	+ Open the system monitor device.
    147  */
    148 int
    149 sysmonopen_envsys(dev_t dev, int flag, int mode, struct lwp *l)
    150 {
    151 	return 0;
    152 }
    153 
    154 /*
    155  * sysmonclose_envsys:
    156  *
    157  *	+ Close the system monitor device.
    158  */
    159 int
    160 sysmonclose_envsys(dev_t dev, int flag, int mode, struct lwp *l)
    161 {
    162 	return 0;
    163 }
    164 
    165 /*
    166  * sysmonioctl_envsys:
    167  *
    168  *	+ Perform a sysmon envsys control request.
    169  */
    170 int
    171 sysmonioctl_envsys(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
    172 {
    173 	struct sysmon_envsys *sme = NULL;
    174 	int error = 0;
    175 	u_int oidx;
    176 
    177 	switch (cmd) {
    178 	/*
    179 	 * To update the global dictionary with latest data from devices.
    180 	 */
    181 	case ENVSYS_GETDICTIONARY:
    182 	    {
    183 		struct plistref *plist = (struct plistref *)data;
    184 
    185 		/*
    186 		 * Update dictionaries on all sysmon envsys devices
    187 		 * registered.
    188 		 */
    189 		mutex_enter(&sme_mtx);
    190 		LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
    191 			sysmon_envsys_acquire(sme);
    192 			error = sme_update_dictionary(sme);
    193 			if (error) {
    194 				DPRINTF(("%s: sme_update_dictionary, "
    195 				    "error=%d\n", __func__, error));
    196 				sysmon_envsys_release(sme);
    197 				mutex_exit(&sme_mtx);
    198 				return error;
    199 			}
    200 			sysmon_envsys_release(sme);
    201 		}
    202 		mutex_exit(&sme_mtx);
    203 		/*
    204 		 * Copy global dictionary to userland.
    205 		 */
    206 		error = prop_dictionary_copyout_ioctl(plist, cmd, sme_propd);
    207 		break;
    208 	    }
    209 	/*
    210 	 * To set properties on multiple devices.
    211 	 */
    212 	case ENVSYS_SETDICTIONARY:
    213 	    {
    214 		const struct plistref *plist = (const struct plistref *)data;
    215 		prop_dictionary_t udict;
    216 		prop_object_iterator_t iter, iter2;
    217 		prop_object_t obj, obj2;
    218 		prop_array_t array_u, array_k;
    219 		const char *devname = NULL;
    220 
    221 		if ((flag & FWRITE) == 0)
    222 			return EPERM;
    223 
    224 		/*
    225 		 * Get dictionary from userland.
    226 		 */
    227 		error = prop_dictionary_copyin_ioctl(plist, cmd, &udict);
    228 		if (error) {
    229 			DPRINTF(("%s: copyin_ioctl error=%d\n",
    230 			    __func__, error));
    231 			break;
    232 		}
    233 
    234 		iter = prop_dictionary_iterator(udict);
    235 		if (!iter) {
    236 			prop_object_release(udict);
    237 			return ENOMEM;
    238 		}
    239 
    240 		/*
    241 		 * Iterate over the userland dictionary and process
    242 		 * the list of devices.
    243 		 */
    244 		while ((obj = prop_object_iterator_next(iter))) {
    245 			array_u = prop_dictionary_get_keysym(udict, obj);
    246 			if (prop_object_type(array_u) != PROP_TYPE_ARRAY) {
    247 				prop_object_iterator_release(iter);
    248 				prop_object_release(udict);
    249 				return EINVAL;
    250 			}
    251 
    252 			devname = prop_dictionary_keysym_cstring_nocopy(obj);
    253 			DPRINTF(("%s: processing the '%s' array requests\n",
    254 			    __func__, devname));
    255 
    256 			/*
    257 			 * find the correct sme device.
    258 			 */
    259 			mutex_enter(&sme_mtx);
    260 			sme = sysmon_envsys_find(devname);
    261 			if (!sme) {
    262 				mutex_exit(&sme_mtx);
    263 				DPRINTF(("%s: NULL sme\n", __func__));
    264 				prop_object_iterator_release(iter);
    265 				prop_object_release(udict);
    266 				return EINVAL;
    267 			}
    268 
    269 			/*
    270 			 * Find the correct array object with the string
    271 			 * supplied by the userland dictionary.
    272 			 */
    273 			array_k = prop_dictionary_get(sme_propd, devname);
    274 			if (prop_object_type(array_k) != PROP_TYPE_ARRAY) {
    275 				DPRINTF(("%s: array device failed\n",
    276 				    __func__));
    277 				sysmon_envsys_release(sme);
    278 				mutex_exit(&sme_mtx);
    279 				prop_object_iterator_release(iter);
    280 				prop_object_release(udict);
    281 				return EINVAL;
    282 			}
    283 
    284 			iter2 = prop_array_iterator(array_u);
    285 			if (!iter2) {
    286 				sysmon_envsys_release(sme);
    287 				mutex_exit(&sme_mtx);
    288 				prop_object_iterator_release(iter);
    289 				prop_object_release(udict);
    290 				return ENOMEM;
    291 			}
    292 
    293 			/*
    294 			 * Iterate over the array of dictionaries to
    295 			 * process the list of sensors and properties.
    296 			 */
    297 			while ((obj2 = prop_object_iterator_next(iter2))) {
    298 				/*
    299 				 * do the real work now.
    300 				 */
    301 				error = sme_userset_dictionary(sme,
    302 							       obj2,
    303 							       array_k);
    304 				if (error) {
    305 					sysmon_envsys_release(sme);
    306 					mutex_exit(&sme_mtx);
    307 					prop_object_iterator_release(iter2);
    308 					prop_object_iterator_release(iter);
    309 					prop_object_release(udict);
    310 					return error;
    311 				}
    312 			}
    313 
    314 			sysmon_envsys_release(sme);
    315 			mutex_exit(&sme_mtx);
    316 			prop_object_iterator_release(iter2);
    317 		}
    318 
    319 		prop_object_iterator_release(iter);
    320 		prop_object_release(udict);
    321 		break;
    322 	    }
    323 	/*
    324 	 * To remove all properties from all devices registered.
    325 	 */
    326 	case ENVSYS_REMOVEPROPS:
    327 	    {
    328 		const struct plistref *plist = (const struct plistref *)data;
    329 		prop_dictionary_t udict;
    330 		prop_object_t obj;
    331 
    332 		if ((flag & FWRITE) == 0)
    333 			return EPERM;
    334 
    335 		error = prop_dictionary_copyin_ioctl(plist, cmd, &udict);
    336 		if (error) {
    337 			DPRINTF(("%s: copyin_ioctl error=%d\n",
    338 			    __func__, error));
    339 			break;
    340 		}
    341 
    342 		obj = prop_dictionary_get(udict, "envsys-remove-props");
    343 		if (!obj || !prop_bool_true(obj)) {
    344 			DPRINTF(("%s: invalid 'envsys-remove-props'\n",
    345 			     __func__));
    346 			return EINVAL;
    347 		}
    348 
    349 		prop_object_release(udict);
    350 		sme_remove_userprops();
    351 
    352 		break;
    353 	    }
    354 	/*
    355 	 * Compatibility ioctls with the old interface, only implemented
    356 	 * ENVSYS_GTREDATA and ENVSYS_GTREINFO; enough to make old
    357 	 * applications work.
    358 	 */
    359 	case ENVSYS_GTREDATA:
    360 	    {
    361 		struct envsys_tre_data *tred = (void *)data;
    362 		envsys_data_t *edata = NULL;
    363 		bool found = false;
    364 
    365 		tred->validflags = 0;
    366 
    367 		mutex_enter(&sme_mtx);
    368 		sme = sysmon_envsys_find_40(tred->sensor);
    369 		if (!sme) {
    370 			mutex_exit(&sme_mtx);
    371 			break;
    372 		}
    373 
    374 		oidx = tred->sensor;
    375 		tred->sensor = SME_SENSOR_IDX(sme, tred->sensor);
    376 
    377 		DPRINTFOBJ(("%s: sensor=%d oidx=%d dev=%s nsensors=%d\n",
    378 		    __func__, tred->sensor, oidx, sme->sme_name,
    379 		    sme->sme_nsensors));
    380 
    381 		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
    382 			if (edata->sensor == tred->sensor) {
    383 				found = true;
    384 				break;
    385 			}
    386 		}
    387 
    388 		if (!found) {
    389 			sysmon_envsys_release(sme);
    390 			mutex_exit(&sme_mtx);
    391 			error = ENODEV;
    392 			break;
    393 		}
    394 
    395 		if (tred->sensor < sme->sme_nsensors) {
    396 			if ((sme->sme_flags & SME_DISABLE_REFRESH) == 0)
    397 				(*sme->sme_refresh)(sme, edata);
    398 
    399 			/*
    400 			 * copy required values to the old interface.
    401 			 */
    402 			tred->sensor = edata->sensor;
    403 			tred->cur.data_us = edata->value_cur;
    404 			tred->cur.data_s = edata->value_cur;
    405 			tred->max.data_us = edata->value_max;
    406 			tred->max.data_s = edata->value_max;
    407 			tred->min.data_us = edata->value_min;
    408 			tred->min.data_s = edata->value_min;
    409 			tred->avg.data_us = edata->value_avg;
    410 			tred->avg.data_s = edata->value_avg;
    411 			if (edata->units == ENVSYS_BATTERY_CHARGE)
    412 				tred->units = ENVSYS_INDICATOR;
    413 			else
    414 				tred->units = edata->units;
    415 
    416 			tred->validflags |= ENVSYS_FVALID;
    417 			tred->validflags |= ENVSYS_FCURVALID;
    418 
    419 			if (edata->flags & ENVSYS_FPERCENT) {
    420 				tred->validflags |= ENVSYS_FMAXVALID;
    421 				tred->validflags |= ENVSYS_FFRACVALID;
    422 			}
    423 
    424 			if (edata->state == ENVSYS_SINVALID) {
    425 				tred->validflags &= ~ENVSYS_FCURVALID;
    426 				tred->cur.data_us = tred->cur.data_s = 0;
    427 			}
    428 
    429 			DPRINTFOBJ(("%s: sensor=%s tred->cur.data_s=%d\n",
    430 			    __func__, edata->desc, tred->cur.data_s));
    431 			DPRINTFOBJ(("%s: tred->validflags=%d tred->units=%d"
    432 			    " tred->sensor=%d\n", __func__, tred->validflags,
    433 			    tred->units, tred->sensor));
    434 		}
    435 		tred->sensor = oidx;
    436 		sysmon_envsys_release(sme);
    437 		mutex_exit(&sme_mtx);
    438 
    439 		break;
    440 	    }
    441 	case ENVSYS_GTREINFO:
    442 	    {
    443 		struct envsys_basic_info *binfo = (void *)data;
    444 		envsys_data_t *edata = NULL;
    445 		bool found = false;
    446 
    447 		binfo->validflags = 0;
    448 
    449 		mutex_enter(&sme_mtx);
    450 		sme = sysmon_envsys_find_40(binfo->sensor);
    451 		if (!sme) {
    452 			mutex_exit(&sme_mtx);
    453 			break;
    454 		}
    455 
    456 		oidx = binfo->sensor;
    457 		binfo->sensor = SME_SENSOR_IDX(sme, binfo->sensor);
    458 
    459 		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
    460 			if (edata->sensor == binfo->sensor) {
    461 				found = true;
    462 				break;
    463 			}
    464 		}
    465 
    466 		if (!found) {
    467 			sysmon_envsys_release(sme);
    468 			mutex_exit(&sme_mtx);
    469 			error = ENODEV;
    470 			break;
    471 		}
    472 
    473 		binfo->validflags |= ENVSYS_FVALID;
    474 
    475 		if (binfo->sensor < sme->sme_nsensors) {
    476 			if (edata->units == ENVSYS_BATTERY_CHARGE)
    477 				binfo->units = ENVSYS_INDICATOR;
    478 			else
    479 				binfo->units = edata->units;
    480 
    481 			/*
    482 			 * previously, the ACPI sensor names included the
    483 			 * device name. Include that in compatibility code.
    484 			 */
    485 			if (strncmp(sme->sme_name, "acpi", 4) == 0)
    486 				(void)snprintf(binfo->desc, sizeof(binfo->desc),
    487 				    "%s %s", sme->sme_name, edata->desc);
    488 			else
    489 				(void)strlcpy(binfo->desc, edata->desc,
    490 				    sizeof(binfo->desc));
    491 		}
    492 
    493 		DPRINTFOBJ(("%s: binfo->units=%d binfo->validflags=%d\n",
    494 		    __func__, binfo->units, binfo->validflags));
    495 		DPRINTFOBJ(("%s: binfo->desc=%s binfo->sensor=%d\n",
    496 		    __func__, binfo->desc, binfo->sensor));
    497 
    498 		binfo->sensor = oidx;
    499 		sysmon_envsys_release(sme);
    500 		mutex_exit(&sme_mtx);
    501 
    502 		break;
    503 	    }
    504 	default:
    505 		error = ENOTTY;
    506 		break;
    507 	}
    508 
    509 	return error;
    510 }
    511 
    512 /*
    513  * sysmon_envsys_create:
    514  *
    515  * 	+ Allocates a new sysmon_envsys object and initializes the
    516  * 	  stuff for sensors and events.
    517  */
    518 struct sysmon_envsys *
    519 sysmon_envsys_create(void)
    520 {
    521 	struct sysmon_envsys *sme;
    522 
    523 	sme = kmem_zalloc(sizeof(*sme), KM_SLEEP);
    524 	TAILQ_INIT(&sme->sme_sensors_list);
    525 	LIST_INIT(&sme->sme_events_list);
    526 
    527 	return sme;
    528 }
    529 
    530 /*
    531  * sysmon_envsys_destroy:
    532  *
    533  * 	+ Removes all sensors from the tail queue and frees the
    534  * 	  sysmon_envsys object.
    535  */
    536 void
    537 sysmon_envsys_destroy(struct sysmon_envsys *sme)
    538 {
    539 	envsys_data_t *edata;
    540 
    541 	KASSERT(sme != NULL);
    542 
    543 	while (!TAILQ_EMPTY(&sme->sme_sensors_list)) {
    544 		edata = TAILQ_FIRST(&sme->sme_sensors_list);
    545 		TAILQ_REMOVE(&sme->sme_sensors_list, edata, sensors_head);
    546 	}
    547 
    548 	kmem_free(sme, sizeof(*sme));
    549 }
    550 
    551 /*
    552  * sysmon_envsys_sensor_attach:
    553  *
    554  * 	+ Attachs a sensor into a sysmon_envsys device checking that units
    555  * 	  is set to a valid type and description is unique and not empty.
    556  */
    557 int
    558 sysmon_envsys_sensor_attach(struct sysmon_envsys *sme, envsys_data_t *edata)
    559 {
    560 	const struct sme_description_table *sdt_units;
    561 	envsys_data_t *oedata;
    562 	int i;
    563 
    564 	KASSERT(sme != NULL || edata != NULL);
    565 
    566 	/*
    567 	 * Find the correct units for this sensor.
    568 	 */
    569 	sdt_units = sme_get_description_table(SME_DESC_UNITS);
    570 	for (i = 0; sdt_units[i].type != -1; i++)
    571 		if (sdt_units[i].type == edata->units)
    572 			break;
    573 
    574 	if (strcmp(sdt_units[i].desc, "unknown") == 0)
    575 		return EINVAL;
    576 
    577 	/*
    578 	 * Check that description is not empty or duplicate.
    579 	 */
    580 	if (strlen(edata->desc) == 0)
    581 		return EINVAL;
    582 
    583 	mutex_enter(&sme_mtx);
    584 	TAILQ_FOREACH(oedata, &sme->sme_sensors_list, sensors_head) {
    585 		if (strcmp(oedata->desc, edata->desc) == 0) {
    586 			mutex_exit(&sme_mtx);
    587 			return EEXIST;
    588 		}
    589 	}
    590 	/*
    591 	 * Ok, the sensor has been added into the device queue.
    592 	 */
    593 	TAILQ_INSERT_TAIL(&sme->sme_sensors_list, edata, sensors_head);
    594 
    595 	/*
    596 	 * Give the sensor a index position.
    597 	 */
    598 	edata->sensor = sme->sme_nsensors;
    599 	sme->sme_nsensors++;
    600 	mutex_exit(&sme_mtx);
    601 
    602 	return 0;
    603 }
    604 
    605 /*
    606  * sysmon_envsys_sensor_detach:
    607  *
    608  * 	+ Detachs a sensor from a sysmon_envsys device and decrements the
    609  * 	  sensors count on success.
    610  */
    611 int
    612 sysmon_envsys_sensor_detach(struct sysmon_envsys *sme, envsys_data_t *edata)
    613 {
    614 	envsys_data_t *oedata;
    615 	bool found = false;
    616 
    617 	KASSERT(sme != NULL || edata != NULL);
    618 
    619 	/*
    620 	 * Check the sensor is already on the list.
    621 	 */
    622 	mutex_enter(&sme_mtx);
    623 	TAILQ_FOREACH(oedata, &sme->sme_sensors_list, sensors_head) {
    624 		if (oedata->sensor == edata->sensor) {
    625 			found = true;
    626 			break;
    627 		}
    628 	}
    629 
    630 	if (!found) {
    631 		mutex_exit(&sme_mtx);
    632 		return EINVAL;
    633 	}
    634 
    635 	/*
    636 	 * remove it and decrement the sensors count.
    637 	 */
    638 	TAILQ_REMOVE(&sme->sme_sensors_list, edata, sensors_head);
    639 	sme->sme_nsensors--;
    640 	mutex_exit(&sme_mtx);
    641 
    642 	return 0;
    643 }
    644 
    645 
    646 /*
    647  * sysmon_envsys_register:
    648  *
    649  *	+ Register a sysmon envsys device.
    650  *	+ Create array of dictionaries for a device.
    651  */
    652 int
    653 sysmon_envsys_register(struct sysmon_envsys *sme)
    654 {
    655 	struct sme_evdrv {
    656 		SLIST_ENTRY(sme_evdrv) evdrv_head;
    657 		sme_event_drv_t *evdrv;
    658 	};
    659 	SLIST_HEAD(, sme_evdrv) sme_evdrv_list;
    660 	struct sme_evdrv *sme_evdrv = NULL;
    661 	struct sysmon_envsys *lsme;
    662 	prop_dictionary_t dict, dict2;
    663 	prop_array_t array;
    664 	envsys_data_t *edata = NULL;
    665 	int i, error = 0;
    666 
    667 	KASSERT(sme != NULL);
    668 	KASSERT(sme->sme_name != NULL);
    669 
    670 	/*
    671 	 * sanity check: if SME_DISABLE_REFRESH is not set,
    672 	 * the sme_refresh function callback must be non NULL.
    673 	 */
    674 	if ((sme->sme_flags & SME_DISABLE_REFRESH) == 0)
    675 		if (!sme->sme_refresh)
    676 			return EINVAL;
    677 
    678 	/*
    679 	 * If the list of sensors is empty, there's no point to continue...
    680 	 */
    681 	if (TAILQ_EMPTY(&sme->sme_sensors_list)) {
    682 		DPRINTF(("%s: sensors list empty for %s\n", __func__,
    683 		    sme->sme_name));
    684 		return ENOTSUP;
    685 	}
    686 
    687 	/*
    688 	 * create the device array.
    689 	 */
    690 	array = prop_array_create();
    691 	if (!array)
    692 		return ENOMEM;
    693 
    694 	/*
    695 	 * Initialize the singly linked list for driver events.
    696 	 */
    697 	SLIST_INIT(&sme_evdrv_list);
    698 
    699 	/*
    700 	 * Iterate over all sensors and create a dictionary per sensor.
    701 	 * We must respect the order in which the sensors were added.
    702 	 */
    703 	for (edata = TAILQ_FIRST(&sme->sme_sensors_list); edata;
    704 	     edata = TAILQ_NEXT(edata, sensors_head)) {
    705 		dict = prop_dictionary_create();
    706 		if (!dict) {
    707 			error = ENOMEM;
    708 			goto out2;
    709 		}
    710 
    711 		/*
    712 		 * Create all objects in sensor's dictionary.
    713 		 */
    714 		sme_evdrv = kmem_zalloc(sizeof(*sme_evdrv), KM_SLEEP);
    715 		sme_evdrv->evdrv = sme_add_sensor_dictionary(sme,
    716 					array, dict, edata);
    717 		if (sme_evdrv->evdrv)
    718 			SLIST_INSERT_HEAD(&sme_evdrv_list,
    719 					  sme_evdrv, evdrv_head);
    720 	}
    721 
    722 	/*
    723 	 * Check if requested sysmon_envsys device is valid
    724 	 * and does not exist already in the list.
    725 	 */
    726 	mutex_enter(&sme_mtx);
    727 	LIST_FOREACH(lsme, &sysmon_envsys_list, sme_list) {
    728 	       if (strcmp(lsme->sme_name, sme->sme_name) == 0) {
    729 		       error = EEXIST;
    730 		       goto out;
    731 	       }
    732 	}
    733 
    734 	/*
    735 	 * If the array does not contain any object (sensor), there's
    736 	 * no need to attach the driver.
    737 	 */
    738 	if (prop_array_count(array) == 0) {
    739 		error = EINVAL;
    740 		DPRINTF(("%s: empty array for '%s'\n", __func__,
    741 		    sme->sme_name));
    742 		goto out;
    743 	}
    744 
    745 	/*
    746 	 * Add the dictionary for the global properties of this device.
    747 	 */
    748 	dict2 = prop_dictionary_create();
    749 	if (!dict2) {
    750 		error = ENOMEM;
    751 		goto out;
    752 	}
    753 
    754 	error = sme_add_property_dictionary(sme, array, dict2);
    755 	if (error) {
    756 		prop_object_release(dict2);
    757 		goto out;
    758 	}
    759 
    760 	/*
    761 	 * Add the array into the global dictionary for the driver.
    762 	 *
    763 	 * <dict>
    764 	 * 	<key>foo0</key>
    765 	 * 	<array>
    766 	 * 		...
    767 	 */
    768 	if (!prop_dictionary_set(sme_propd, sme->sme_name, array)) {
    769 		error = EINVAL;
    770 		DPRINTF(("%s: prop_dictionary_set for '%s'\n", __func__,
    771 		    sme->sme_name));
    772 		goto out;
    773 	}
    774 	/*
    775 	 * Add the device into the list.
    776 	 */
    777 	LIST_INSERT_HEAD(&sysmon_envsys_list, sme, sme_list);
    778 	sme->sme_fsensor = sysmon_envsys_next_sensor_index;
    779 	sysmon_envsys_next_sensor_index += sme->sme_nsensors;
    780 out:
    781 	mutex_exit(&sme_mtx);
    782 
    783 	/*
    784 	 * No errors? register the events that were set in the driver.
    785 	 */
    786 	if (error == 0) {
    787 		i = 0;
    788 		SLIST_FOREACH(sme_evdrv, &sme_evdrv_list, evdrv_head) {
    789 			if (i == 0)
    790 				sysmon_task_queue_init();
    791 			sysmon_task_queue_sched(0,
    792 			    sme_event_drvadd, sme_evdrv->evdrv);
    793 		}
    794 		DPRINTF(("%s: driver '%s' registered (nsens=%d)\n",
    795 		    __func__, sme->sme_name, sme->sme_nsensors));
    796 	}
    797 
    798 out2:
    799 	while (!SLIST_EMPTY(&sme_evdrv_list)) {
    800 		sme_evdrv = SLIST_FIRST(&sme_evdrv_list);
    801 		SLIST_REMOVE_HEAD(&sme_evdrv_list, evdrv_head);
    802 		kmem_free(sme_evdrv, sizeof(*sme_evdrv));
    803 	}
    804 	if (!error)
    805 		return 0;
    806 
    807 	/*
    808 	 * Ugh... something wasn't right; unregister all events and sensors
    809 	 * previously assigned and destroy the array with all its objects.
    810 	 */
    811 	DPRINTF(("%s: failed to register '%s' (%d)\n", __func__,
    812 	    sme->sme_name, error));
    813 	if (error != EEXIST) {
    814 		mutex_enter(&sme_mtx);
    815 		sme_event_unregister_all(sme);
    816 		while (!TAILQ_EMPTY(&sme->sme_sensors_list)) {
    817 			edata = TAILQ_FIRST(&sme->sme_sensors_list);
    818 			TAILQ_REMOVE(&sme->sme_sensors_list, edata,
    819 			    sensors_head);
    820 		}
    821 		mutex_exit(&sme_mtx);
    822 	}
    823 	sysmon_envsys_destroy_plist(array);
    824 	return error;
    825 }
    826 
    827 /*
    828  * sysmon_envsys_destroy_plist:
    829  *
    830  * 	+ Remove all objects from the array of dictionaries that is
    831  * 	  created in a sysmon envsys device.
    832  */
    833 static void
    834 sysmon_envsys_destroy_plist(prop_array_t array)
    835 {
    836 	prop_object_iterator_t iter, iter2;
    837 	prop_dictionary_t dict;
    838 	prop_object_t obj;
    839 
    840 	KASSERT(array != NULL);
    841 
    842 	DPRINTFOBJ(("%s: objects in array=%d\n", __func__,
    843 	    prop_array_count(array)));
    844 
    845 	iter = prop_array_iterator(array);
    846 	if (!iter)
    847 		return;
    848 
    849 	while ((dict = prop_object_iterator_next(iter))) {
    850 		KASSERT(prop_object_type(dict) == PROP_TYPE_DICTIONARY);
    851 		iter2 = prop_dictionary_iterator(dict);
    852 		if (!iter2)
    853 			goto out;
    854 		DPRINTFOBJ(("%s: iterating over dictionary\n", __func__));
    855 		while ((obj = prop_object_iterator_next(iter2)) != NULL) {
    856 			DPRINTFOBJ(("%s: obj=%s\n", __func__,
    857 			    prop_dictionary_keysym_cstring_nocopy(obj)));
    858 			prop_dictionary_remove(dict,
    859 			    prop_dictionary_keysym_cstring_nocopy(obj));
    860 			prop_object_iterator_reset(iter2);
    861 		}
    862 		prop_object_iterator_release(iter2);
    863 		DPRINTFOBJ(("%s: objects in dictionary:%d\n",
    864 		    __func__, prop_dictionary_count(dict)));
    865 		prop_object_release(dict);
    866 	}
    867 
    868 out:
    869 	prop_object_iterator_release(iter);
    870 	prop_object_release(array);
    871 }
    872 
    873 /*
    874  * sysmon_envsys_unregister:
    875  *
    876  *	+ Unregister a sysmon envsys device.
    877  */
    878 void
    879 sysmon_envsys_unregister(struct sysmon_envsys *sme)
    880 {
    881 	prop_array_t array;
    882 
    883 	KASSERT(sme != NULL);
    884 
    885 	mutex_enter(&sme_mtx);
    886 	/*
    887 	 * Wait for device to be available.
    888 	 */
    889 	while (sme->sme_flags & SME_FLAG_BUSY)
    890 		cv_wait(&sme_cv, &sme_mtx);
    891 	/*
    892 	 * Stop the callout.
    893 	 */
    894 	callout_stop(&sme->sme_callout);
    895 	/*
    896 	 * Decrement global sensors counter (only useful for compatibility).
    897 	 */
    898 	sysmon_envsys_next_sensor_index -= sme->sme_nsensors;
    899 	/*
    900 	 * Unregister all events associated with this device.
    901 	 */
    902 	sme_event_unregister_all(sme);
    903 	LIST_REMOVE(sme, sme_list);
    904 	mutex_exit(&sme_mtx);
    905 	/*
    906 	 * Remove the device (and all its objects) from the global dictionary.
    907 	 */
    908 	array = prop_dictionary_get(sme_propd, sme->sme_name);
    909 	if (array && prop_object_type(array) == PROP_TYPE_ARRAY) {
    910 		prop_dictionary_remove(sme_propd, sme->sme_name);
    911 		sysmon_envsys_destroy_plist(array);
    912 	}
    913 	/*
    914 	 * And finally destroy the sysmon_envsys object.
    915 	 */
    916 	sysmon_envsys_destroy(sme);
    917 }
    918 
    919 /*
    920  * sysmon_envsys_find:
    921  *
    922  *	+ Find a sysmon envsys device and mark it as busy if found.
    923  */
    924 struct sysmon_envsys *
    925 sysmon_envsys_find(const char *name)
    926 {
    927 	struct sysmon_envsys *sme;
    928 
    929 	KASSERT(mutex_owned(&sme_mtx));
    930 
    931 again:
    932 	for (sme = LIST_FIRST(&sysmon_envsys_list); sme;
    933 	     sme = LIST_NEXT(sme, sme_list)) {
    934 			if (strcmp(sme->sme_name, name) == 0) {
    935 				if (sme->sme_flags & SME_FLAG_BUSY) {
    936 					cv_wait(&sme_cv, &sme_mtx);
    937 					goto again;
    938 				}
    939 				sme->sme_flags |= SME_FLAG_BUSY;
    940 				break;
    941 			}
    942 	}
    943 	return sme;
    944 }
    945 
    946 /*
    947  * sysmon_envsys_acquire:
    948  *
    949  * 	+ Acquire priviledge to a sysmon envsys device (locked).
    950  */
    951 void
    952 sysmon_envsys_acquire(struct sysmon_envsys *sme)
    953 {
    954 	KASSERT(mutex_owned(&sme_mtx));
    955 
    956 	while (sme->sme_flags & SME_FLAG_BUSY)
    957 		cv_wait(&sme_cv, &sme_mtx);
    958 
    959 	sme->sme_flags |= SME_FLAG_BUSY;
    960 }
    961 
    962 /*
    963  * sysmon_envsys_release:
    964  *
    965  * 	+ Release a sysmon envsys device (locked).
    966  */
    967 void
    968 sysmon_envsys_release(struct sysmon_envsys *sme)
    969 {
    970 	KASSERT(mutex_owned(&sme_mtx));
    971 
    972 	sme->sme_flags &= ~SME_FLAG_BUSY;
    973 	cv_broadcast(&sme_cv);
    974 }
    975 
    976 /* compatibility function */
    977 struct sysmon_envsys *
    978 sysmon_envsys_find_40(u_int idx)
    979 {
    980 	struct sysmon_envsys *sme;
    981 
    982 	KASSERT(mutex_owned(&sme_mtx));
    983 
    984 	for (sme = LIST_FIRST(&sysmon_envsys_list); sme;
    985 	     sme = LIST_NEXT(sme, sme_list)) {
    986 		if (idx >= sme->sme_fsensor &&
    987 	    	    idx < (sme->sme_fsensor + sme->sme_nsensors)) {
    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