Home | History | Annotate | Line # | Download | only in sysmon
sysmon_envsys_events.c revision 1.103
      1 /* $NetBSD: sysmon_envsys_events.c,v 1.103 2012/07/19 13:30:01 pgoyette Exp $ */
      2 
      3 /*-
      4  * Copyright (c) 2007, 2008 Juan Romero Pardines.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26  */
     27 
     28 /*
     29  * sysmon_envsys(9) events framework.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 __KERNEL_RCSID(0, "$NetBSD: sysmon_envsys_events.c,v 1.103 2012/07/19 13:30:01 pgoyette Exp $");
     34 
     35 #include <sys/param.h>
     36 #include <sys/types.h>
     37 #include <sys/conf.h>
     38 #include <sys/errno.h>
     39 #include <sys/kernel.h>
     40 #include <sys/systm.h>
     41 #include <sys/proc.h>
     42 #include <sys/mutex.h>
     43 #include <sys/kmem.h>
     44 #include <sys/callout.h>
     45 
     46 /* #define ENVSYS_DEBUG */
     47 /* #define ENVSYS_OBJECTS_DEBUG */
     48 
     49 #include <dev/sysmon/sysmonvar.h>
     50 #include <dev/sysmon/sysmon_envsysvar.h>
     51 
     52 struct sme_sensor_event {
     53 	int		state;
     54 	int		event;
     55 };
     56 
     57 static const struct sme_sensor_event sme_sensor_event[] = {
     58 	{ ENVSYS_SVALID,			PENVSYS_EVENT_NORMAL },
     59 	{ ENVSYS_SCRITOVER, 			PENVSYS_EVENT_CRITOVER },
     60 	{ ENVSYS_SCRITUNDER, 			PENVSYS_EVENT_CRITUNDER },
     61 	{ ENVSYS_SWARNOVER, 			PENVSYS_EVENT_WARNOVER },
     62 	{ ENVSYS_SWARNUNDER,			PENVSYS_EVENT_WARNUNDER },
     63 	{ ENVSYS_BATTERY_CAPACITY_NORMAL,	PENVSYS_EVENT_NORMAL },
     64 	{ ENVSYS_BATTERY_CAPACITY_WARNING,	PENVSYS_EVENT_BATT_WARN },
     65 	{ ENVSYS_BATTERY_CAPACITY_CRITICAL,	PENVSYS_EVENT_BATT_CRIT },
     66 	{ ENVSYS_BATTERY_CAPACITY_HIGH,		PENVSYS_EVENT_BATT_HIGH },
     67 	{ ENVSYS_BATTERY_CAPACITY_MAX,		PENVSYS_EVENT_BATT_MAX },
     68 	{ -1, 					-1 }
     69 };
     70 
     71 static bool sysmon_low_power;
     72 
     73 #define SME_EVTIMO	(SME_EVENTS_DEFTIMEOUT * hz)
     74 
     75 static bool sme_event_check_low_power(void);
     76 static bool sme_battery_check(void);
     77 static bool sme_battery_critical(envsys_data_t *);
     78 static bool sme_acadapter_check(void);
     79 
     80 static void sme_remove_event(sme_event_t *, struct sysmon_envsys *);
     81 
     82 /*
     83  * sme_event_register:
     84  *
     85  * 	+ Registers a new sysmon envsys event or updates any event
     86  * 	  already in the queue.
     87  */
     88 int
     89 sme_event_register(prop_dictionary_t sdict, envsys_data_t *edata,
     90 		   struct sysmon_envsys *sme, sysmon_envsys_lim_t *lims,
     91 		   uint32_t props, int crittype, int powertype)
     92 {
     93 	sme_event_t *see = NULL, *osee = NULL;
     94 	prop_object_t obj;
     95 	int error = 0;
     96 	const char *objkey;
     97 
     98 	KASSERT(sdict != NULL);
     99 	KASSERT(edata != NULL);
    100 	KASSERT(sme != NULL);
    101 	KASSERT(lims != NULL);
    102 
    103 	/*
    104 	 * Some validation first for limit-checking events
    105 	 *
    106 	 * 1. Limits are not permitted if the units is ENVSYS_INDICATOR
    107 	 *    or ENVSYS_BATTERY_CHARGE.
    108 	 *
    109 	 * 2. Capacity limits are permitted only if the sensor has the
    110 	 *    ENVSYS_FPERCENT flag set and value_max is set.
    111 	 *
    112 	 * 3. It is not permissible for both capacity and value limits
    113 	 *    to coexist.
    114 	 *
    115 	 * Note that it permissible for a sensor to have value limits
    116 	 * even if its ENVSYS_FPERCENT flag and value_max are set.
    117 	 */
    118 
    119 	DPRINTF(("%s: units %d props 0x%04x upropset 0x%04x max_val %d"
    120 		" edata-flags 0x%04x\n", __func__, edata->units, props,
    121 		edata->upropset, edata->value_max, edata->flags));
    122 
    123 	if (props)
    124 		if (edata->units == ENVSYS_INDICATOR ||
    125 		    edata->units == ENVSYS_BATTERY_CHARGE)
    126 			return ENOTSUP;
    127 
    128 	if ((props & PROP_CAP_LIMITS) &&
    129 	    ((edata->value_max == 0) ||
    130 	     !(edata->flags & ENVSYS_FPERCENT) ||
    131 	     (props & PROP_VAL_LIMITS) ||
    132 	     (edata->upropset & PROP_VAL_LIMITS)))
    133 		props = 0;
    134 
    135 	if ((props & PROP_VAL_LIMITS) && (edata->upropset & PROP_CAP_LIMITS))
    136 		props = 0;
    137 
    138 	/*
    139 	 * check if the event is already on the list and return
    140 	 * EEXIST if value provided hasn't been changed.
    141 	 */
    142 	mutex_enter(&sme->sme_mtx);
    143 	LIST_FOREACH(osee, &sme->sme_events_list, see_list) {
    144 		if (strcmp(edata->desc, osee->see_pes.pes_sensname) != 0)
    145 			continue;
    146 		if (crittype != osee->see_type &&
    147 		    osee->see_type != PENVSYS_EVENT_NULL)
    148 			continue;
    149 
    150 		/*
    151 		 * We found an existing event for this sensor.  Make
    152 		 * sure it references the correct edata
    153 		 */
    154 		KASSERT(edata == osee->see_edata);
    155 
    156 		DPRINTF(("%s: dev %s sensor %s: event type %d exists\n",
    157 		    __func__, sme->sme_name, edata->desc, crittype));
    158 
    159 		see = osee;
    160 		if (props & edata->upropset & (PROP_CRITMAX | PROP_BATTMAX)) {
    161 			if (lims->sel_critmax == edata->limits.sel_critmax) {
    162 				DPRINTF(("%s: critmax exists\n", __func__));
    163 				error = EEXIST;
    164 				props &= ~(PROP_CRITMAX | PROP_BATTMAX);
    165 			}
    166 		}
    167 		if (props & edata->upropset & (PROP_WARNMAX | PROP_BATTHIGH)) {
    168 			if (lims->sel_warnmax == edata->limits.sel_warnmax) {
    169 				DPRINTF(("%s: warnmax exists\n", __func__));
    170 				error = EEXIST;
    171 				props &= ~(PROP_WARNMAX | PROP_BATTHIGH);
    172 			}
    173 		}
    174 		if (props & edata->upropset & (PROP_WARNMIN | PROP_BATTWARN)) {
    175 			if (lims->sel_warnmin == edata->limits.sel_warnmin) {
    176 				DPRINTF(("%s: warnmin exists\n", __func__));
    177 				error = EEXIST;
    178 				props &= ~(PROP_WARNMIN | PROP_BATTWARN);
    179 			}
    180 		}
    181 		if (props & edata->upropset & (PROP_CRITMIN | PROP_BATTCAP)) {
    182 			if (lims->sel_critmin == edata->limits.sel_critmin) {
    183 				DPRINTF(("%s: critmin exists\n", __func__));
    184 				error = EEXIST;
    185 				props &= ~(PROP_CRITMIN | PROP_BATTCAP);
    186 			}
    187 		}
    188 		if (props && see->see_type == PENVSYS_EVENT_NULL)
    189 			see->see_type = crittype;
    190 
    191 		break;
    192 	}
    193 	if (crittype == PENVSYS_EVENT_NULL && see != NULL) {
    194 		mutex_exit(&sme->sme_mtx);
    195 		return EEXIST;
    196 	}
    197 
    198 	if (see == NULL) {
    199 		/*
    200 		 * New event requested - allocate a sysmon_envsys event.
    201 		 */
    202 		see = kmem_zalloc(sizeof(*see), KM_SLEEP);
    203 		if (see == NULL)
    204 			return ENOMEM;
    205 
    206 		DPRINTF(("%s: dev %s sensor %s: new event\n",
    207 		    __func__, sme->sme_name, edata->desc));
    208 
    209 		see->see_type = crittype;
    210 		see->see_sme = sme;
    211 		see->see_edata = edata;
    212 
    213 		/* Initialize sensor type and previously-sent state */
    214 
    215 		see->see_pes.pes_type = powertype;
    216 
    217 		switch (crittype) {
    218 		case PENVSYS_EVENT_LIMITS:
    219 			see->see_evsent = ENVSYS_SVALID;
    220 			break;
    221 		case PENVSYS_EVENT_CAPACITY:
    222 			see->see_evsent = ENVSYS_BATTERY_CAPACITY_NORMAL;
    223 			break;
    224 		case PENVSYS_EVENT_STATE_CHANGED:
    225 			if (edata->units == ENVSYS_BATTERY_CAPACITY)
    226 				see->see_evsent = ENVSYS_BATTERY_CAPACITY_NORMAL;
    227 			else if (edata->units == ENVSYS_DRIVE)
    228 				see->see_evsent = ENVSYS_DRIVE_EMPTY;
    229 			else
    230 				panic("%s: bad units for "
    231 				      "PENVSYS_EVENT_STATE_CHANGED", __func__);
    232 			break;
    233 		case PENVSYS_EVENT_CRITICAL:
    234 		default:
    235 			see->see_evsent = 0;
    236 			break;
    237 		}
    238 
    239 		(void)strlcpy(see->see_pes.pes_dvname, sme->sme_name,
    240 		    sizeof(see->see_pes.pes_dvname));
    241 		(void)strlcpy(see->see_pes.pes_sensname, edata->desc,
    242 		    sizeof(see->see_pes.pes_sensname));
    243 	}
    244 
    245 	/*
    246 	 * Limit operation requested.
    247 	 */
    248 #define	LIMIT_OP(k, l, p)						\
    249 	if (props & p) {						\
    250 		objkey = k;						\
    251 		obj = prop_dictionary_get(sdict, objkey);		\
    252 		if (obj != NULL &&					\
    253 		    prop_object_type(obj) != PROP_TYPE_NUMBER) {	\
    254 			DPRINTF(("%s: (%s) %s object no TYPE_NUMBER\n",	\
    255 			    __func__, sme->sme_name, objkey));		\
    256 			error = ENOTSUP;				\
    257 		} else {						\
    258 			edata->limits.l = lims->l;			\
    259 			error = sme_sensor_upint32(sdict, objkey,lims->l); \
    260 			DPRINTF(("%s: (%s) event [sensor=%s type=%d] "	\
    261 			    "(%s updated)\n", __func__, sme->sme_name,	\
    262 			    edata->desc, crittype, objkey));		\
    263 		}							\
    264 		if (error && error != EEXIST)				\
    265 			goto out;					\
    266 		edata->upropset |= p;					\
    267 	}
    268 
    269 	/* Value-based limits */
    270 	LIMIT_OP("critical-max", sel_critmax, PROP_CRITMAX);
    271 	LIMIT_OP("warning-max",  sel_warnmax, PROP_WARNMAX);
    272 	LIMIT_OP("warning-min",  sel_warnmin, PROP_WARNMIN);
    273 	LIMIT_OP("critical-min", sel_critmin, PROP_CRITMIN);
    274 
    275 	/* %Capacity-based limits */
    276 	LIMIT_OP("maximum-capacity",  sel_critmax,  PROP_BATTMAX);
    277 	LIMIT_OP("high-capacity",     sel_warnmax,  PROP_BATTHIGH);
    278 	LIMIT_OP("warning-capacity",  sel_warnmin,  PROP_BATTWARN);
    279 	LIMIT_OP("critical-capacity", sel_critmin,  PROP_BATTCAP);
    280 
    281 #undef LIMIT_OP
    282 
    283 	if (props & PROP_DRIVER_LIMITS)
    284 		edata->upropset |= PROP_DRIVER_LIMITS;
    285 	else
    286 		edata->upropset &= ~PROP_DRIVER_LIMITS;
    287 
    288 	DPRINTF(("%s: (%s) event registered (sensor=%s snum=%d type=%d "
    289 	    "critmin=%" PRIu32 " warnmin=%" PRIu32 " warnmax=%" PRIu32
    290 	    " critmax=%" PRIu32 " props 0x%04x)\n", __func__,
    291 	    see->see_sme->sme_name, see->see_pes.pes_sensname,
    292 	    edata->sensor, see->see_type, edata->limits.sel_critmin,
    293 	    edata->limits.sel_warnmin, edata->limits.sel_warnmax,
    294 	    edata->limits.sel_critmax, edata->upropset));
    295 	/*
    296 	 * Initialize the events framework if it wasn't initialized before.
    297 	 */
    298 	if ((sme->sme_flags & SME_CALLOUT_INITIALIZED) == 0)
    299 		error = sme_events_init(sme);
    300 
    301 	/*
    302 	 * If driver requested notification, advise it of new
    303 	 * limit values
    304 	 */
    305 	if (sme->sme_set_limits)
    306 		(*sme->sme_set_limits)(sme, edata, &(edata->limits),
    307 					&(edata->upropset));
    308 
    309 out:
    310 	if ((error == 0 || error == EEXIST) && osee == NULL)
    311 		LIST_INSERT_HEAD(&sme->sme_events_list, see, see_list);
    312 
    313 	mutex_exit(&sme->sme_mtx);
    314 
    315 	return error;
    316 }
    317 
    318 /*
    319  * sme_event_unregister_all:
    320  *
    321  * 	+ Unregisters all events associated with a sysmon envsys device.
    322  */
    323 void
    324 sme_event_unregister_all(struct sysmon_envsys *sme)
    325 {
    326 	sme_event_t *see;
    327 	int evcounter = 0;
    328 
    329 	KASSERT(sme != NULL);
    330 
    331 	mutex_enter(&sme->sme_mtx);
    332 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    333 		while (see->see_flags & SEE_EVENT_WORKING)
    334 			cv_wait(&sme->sme_condvar, &sme->sme_mtx);
    335 
    336 		if (strcmp(see->see_pes.pes_dvname, sme->sme_name) == 0)
    337 			evcounter++;
    338 	}
    339 
    340 	DPRINTF(("%s: total events %d (%s)\n", __func__,
    341 	    evcounter, sme->sme_name));
    342 
    343 	while ((see = LIST_FIRST(&sme->sme_events_list))) {
    344 		if (evcounter == 0)
    345 			break;
    346 
    347 		if (strcmp(see->see_pes.pes_dvname, sme->sme_name) == 0) {
    348 			DPRINTF(("%s: event %s %d removed (%s)\n", __func__,
    349 			    see->see_pes.pes_sensname, see->see_type,
    350 			    sme->sme_name));
    351 			sme_remove_event(see, sme);
    352 
    353 			evcounter--;
    354 		}
    355 	}
    356 
    357 	if (LIST_EMPTY(&sme->sme_events_list))
    358 		if (sme->sme_flags & SME_CALLOUT_INITIALIZED)
    359 			sme_events_destroy(sme);
    360 	mutex_exit(&sme->sme_mtx);
    361 }
    362 
    363 /*
    364  * sme_event_unregister:
    365  *
    366  * 	+ Unregisters an event from the specified sysmon envsys device.
    367  */
    368 int
    369 sme_event_unregister(struct sysmon_envsys *sme, const char *sensor, int type)
    370 {
    371 	sme_event_t *see;
    372 	bool found = false;
    373 
    374 	KASSERT(sensor != NULL);
    375 
    376 	mutex_enter(&sme->sme_mtx);
    377 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    378 		if (strcmp(see->see_pes.pes_sensname, sensor) == 0) {
    379 			if (see->see_type == type) {
    380 				found = true;
    381 				break;
    382 			}
    383 		}
    384 	}
    385 
    386 	if (!found) {
    387 		mutex_exit(&sme->sme_mtx);
    388 		return EINVAL;
    389 	}
    390 
    391 	/*
    392 	 * Wait for the event to finish its work, remove from the list
    393 	 * and release resouces.
    394 	 */
    395 	while (see->see_flags & SEE_EVENT_WORKING)
    396 		cv_wait(&sme->sme_condvar, &sme->sme_mtx);
    397 
    398 	DPRINTF(("%s: removed dev=%s sensor=%s type=%d\n",
    399 	    __func__, see->see_pes.pes_dvname, sensor, type));
    400 
    401 	sme_remove_event(see, sme);
    402 
    403 	mutex_exit(&sme->sme_mtx);
    404 	return 0;
    405 }
    406 
    407 /*
    408  * sme_event_unregister_sensor:
    409  *
    410  *	+ Unregisters any event associated with a specific sensor
    411  *	  The caller must already own the sme_mtx.
    412  */
    413 int
    414 sme_event_unregister_sensor(struct sysmon_envsys *sme, envsys_data_t *edata)
    415 {
    416 	sme_event_t *see;
    417 	bool found = false;
    418 
    419 	KASSERT(mutex_owned(&sme->sme_mtx));
    420 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    421 		if (see->see_edata == edata) {
    422 			found = true;
    423 			break;
    424 		}
    425 	}
    426 	if (!found)
    427 		return EINVAL;
    428 
    429 	/*
    430 	 * Wait for the event to finish its work, remove from the list
    431 	 * and release resouces.
    432 	 */
    433 	while (see->see_flags & SEE_EVENT_WORKING)
    434 		cv_wait(&sme->sme_condvar, &sme->sme_mtx);
    435 
    436 	DPRINTF(("%s: removed dev=%s sensor=%s\n",
    437 	    __func__, see->see_pes.pes_dvname, edata->desc));
    438 
    439 	sme_remove_event(see, sme);
    440 
    441 	return 0;
    442 }
    443 
    444 static void
    445 sme_remove_event(sme_event_t *see, struct sysmon_envsys *sme)
    446 {
    447 
    448 	KASSERT(mutex_owned(&sme->sme_mtx));
    449 
    450 	if (see->see_edata->flags & ENVSYS_FHAS_ENTROPY)
    451 		rnd_detach_source(&see->see_edata->rnd_src);
    452 	LIST_REMOVE(see, see_list);
    453 	/*
    454 	 * So the events list is empty, we'll do the following:
    455 	 *
    456 	 * 	- stop and destroy the callout.
    457 	 * 	- destroy the workqueue.
    458 	 */
    459 	if (LIST_EMPTY(&sme->sme_events_list))
    460 		sme_events_destroy(sme);
    461 
    462 	kmem_free(see, sizeof(*see));
    463 }
    464 
    465 /*
    466  * sme_event_drvadd:
    467  *
    468  * 	+ Registers a new event for a device that had enabled any of
    469  * 	  the monitoring flags in the driver.
    470  */
    471 void
    472 sme_event_drvadd(void *arg)
    473 {
    474 	sme_event_drv_t *sed_t = arg;
    475 	sysmon_envsys_lim_t lims;
    476 	uint32_t props;
    477 	int error = 0;
    478 
    479 	KASSERT(sed_t != NULL);
    480 
    481 #define SEE_REGEVENT(a, b, c)						\
    482 do {									\
    483 	if (sed_t->sed_edata->flags & (a)) {				\
    484 		char str[ENVSYS_DESCLEN] = "monitoring-state-";		\
    485 									\
    486 		error = sme_event_register(sed_t->sed_sdict,		\
    487 				      sed_t->sed_edata,			\
    488 				      sed_t->sed_sme,			\
    489 				      &lims, props,			\
    490 				      (b),				\
    491 				      sed_t->sed_powertype);		\
    492 		if (error && error != EEXIST)				\
    493 			printf("%s: failed to add event! "		\
    494 			    "error=%d sensor=%s event=%s\n",		\
    495 			    __func__, error,				\
    496 			    sed_t->sed_edata->desc, (c));		\
    497 		else {							\
    498 			(void)strlcat(str, (c), sizeof(str));		\
    499 			prop_dictionary_set_bool(sed_t->sed_sdict,	\
    500 						 str,			\
    501 						 true);			\
    502 		}							\
    503 	}								\
    504 } while (/* CONSTCOND */ 0)
    505 
    506 	/*
    507 	 * If driver provides a method to retrieve its internal limit
    508 	 * values, call it and use those returned values as initial
    509 	 * limits for event monitoring.
    510 	 */
    511 	props = 0;
    512 	if (sed_t->sed_edata->flags & ENVSYS_FMONLIMITS)
    513 		if (sed_t->sed_sme->sme_get_limits)
    514 			(*sed_t->sed_sme->sme_get_limits)(sed_t->sed_sme,
    515 							  sed_t->sed_edata,
    516 							  &lims, &props);
    517 	/*
    518 	 * If driver doesn't provide a way to "absorb" user-specified
    519 	 * limit values, we must monitor all limits ourselves
    520 	 */
    521 	if (sed_t->sed_sme->sme_set_limits == NULL)
    522 		props &= ~PROP_DRIVER_LIMITS;
    523 
    524 	/* Register the events that were specified */
    525 
    526 	SEE_REGEVENT(ENVSYS_FMONCRITICAL,
    527 		     PENVSYS_EVENT_CRITICAL,
    528 		     "critical");
    529 
    530 	SEE_REGEVENT(ENVSYS_FMONSTCHANGED,
    531 		     PENVSYS_EVENT_STATE_CHANGED,
    532 		     "state-changed");
    533 
    534 	SEE_REGEVENT(ENVSYS_FMONLIMITS,
    535 		     PENVSYS_EVENT_LIMITS,
    536 		     "hw-range-limits");
    537 
    538 	SEE_REGEVENT(ENVSYS_FHAS_ENTROPY,
    539 		     PENVSYS_EVENT_NULL,
    540 		     "refresh-event");
    541 
    542 	/*
    543 	 * we are done, free memory now.
    544 	 */
    545 	kmem_free(sed_t, sizeof(*sed_t));
    546 }
    547 
    548 /*
    549  * sme_events_init:
    550  *
    551  * 	+ Initialize the events framework for this device.
    552  */
    553 int
    554 sme_events_init(struct sysmon_envsys *sme)
    555 {
    556 	int error = 0;
    557 
    558 	KASSERT(sme != NULL);
    559 	KASSERT(mutex_owned(&sme->sme_mtx));
    560 
    561 	error = workqueue_create(&sme->sme_wq, sme->sme_name,
    562 	    sme_events_worker, sme, PRI_NONE, IPL_SOFTCLOCK, WQ_MPSAFE);
    563 	if (error)
    564 		return error;
    565 
    566 	mutex_init(&sme->sme_callout_mtx, MUTEX_DEFAULT, IPL_SOFTCLOCK);
    567 	callout_init(&sme->sme_callout, CALLOUT_MPSAFE);
    568 	callout_setfunc(&sme->sme_callout, sme_events_check, sme);
    569 	sme->sme_flags |= SME_CALLOUT_INITIALIZED;
    570 	sme_schedule_callout(sme);
    571 	DPRINTF(("%s: events framework initialized for '%s'\n",
    572 	    __func__, sme->sme_name));
    573 
    574 	return error;
    575 }
    576 
    577 /*
    578  * sme_schedule_callout
    579  *
    580  *	(Re)-schedule the device's callout timer
    581  */
    582 void
    583 sme_schedule_callout(struct sysmon_envsys *sme)
    584 {
    585 	uint64_t timo;
    586 
    587 	KASSERT(sme != NULL);
    588 
    589 	if ((sme->sme_flags & SME_CALLOUT_INITIALIZED) == 0)
    590 		return;
    591 
    592 	if (sme->sme_events_timeout)
    593 		timo = sme->sme_events_timeout * hz;
    594 	else
    595 		timo = SME_EVTIMO;
    596 
    597 	callout_stop(&sme->sme_callout);
    598 	callout_schedule(&sme->sme_callout, timo);
    599 }
    600 
    601 /*
    602  * sme_events_destroy:
    603  *
    604  * 	+ Destroys the event framework for this device: callout
    605  * 	  stopped, workqueue destroyed and callout mutex destroyed.
    606  */
    607 void
    608 sme_events_destroy(struct sysmon_envsys *sme)
    609 {
    610 	KASSERT(mutex_owned(&sme->sme_mtx));
    611 
    612 	callout_stop(&sme->sme_callout);
    613 	workqueue_destroy(sme->sme_wq);
    614 	mutex_destroy(&sme->sme_callout_mtx);
    615 	callout_destroy(&sme->sme_callout);
    616 	sme->sme_flags &= ~SME_CALLOUT_INITIALIZED;
    617 	DPRINTF(("%s: events framework destroyed for '%s'\n",
    618 	    __func__, sme->sme_name));
    619 }
    620 
    621 /*
    622  * sysmon_envsys_update_limits
    623  *
    624  *	+ If a driver needs to update the limits that it is providing,
    625  *	  we need to update the dictionary data as well as the limits.
    626  *	  This only makes sense if the driver is capable of providing
    627  *	  its limits, and if there is a limits event-monitor.
    628  */
    629 int
    630 sysmon_envsys_update_limits(struct sysmon_envsys *sme, envsys_data_t *edata)
    631 {
    632 	int err;
    633 
    634 	sysmon_envsys_acquire(sme, false);
    635 	if (sme->sme_get_limits == NULL ||
    636 	    (edata->flags & ENVSYS_FMONLIMITS) == 0)
    637 		err = EINVAL;
    638 	else
    639 		err = sme_update_limits(sme, edata);
    640 	sysmon_envsys_release(sme, false);
    641 
    642 	return err;
    643 }
    644 
    645 /*
    646  * sme_update_limits
    647  *
    648  *	+ Internal version of sysmon_envsys_update_limits() to be used
    649  *	  when the device has already been sysmon_envsys_acquire()d.
    650  */
    651 
    652 int
    653 sme_update_limits(struct sysmon_envsys *sme, envsys_data_t *edata)
    654 {
    655 	prop_dictionary_t sdict = NULL;
    656 	prop_array_t array = NULL;
    657 	sysmon_envsys_lim_t lims;
    658 	sme_event_t *see;
    659 	uint32_t props = 0;
    660 
    661 	/* Find the dictionary for this sensor */
    662 	array = prop_dictionary_get(sme_propd, sme->sme_name);
    663 	if (array == NULL ||
    664 	    prop_object_type(array) != PROP_TYPE_ARRAY) {
    665 		DPRINTF(("%s: array device failed\n", __func__));
    666 		return EINVAL;
    667 	}
    668 
    669 	sdict = prop_array_get(array, edata->sensor);
    670 	if (sdict == NULL) {
    671 		return EINVAL;
    672 	}
    673 
    674 	/* Find the event definition to get its powertype */
    675 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    676 		if (edata == see->see_edata &&
    677 		    see->see_type == PENVSYS_EVENT_LIMITS)
    678 			break;
    679 	}
    680 	if (see == NULL)
    681 		return EINVAL;
    682 
    683 	/* Update limit values from driver if possible */
    684 	if (sme->sme_get_limits != NULL)
    685 		(*sme->sme_get_limits)(sme, edata, &lims, &props);
    686 
    687 	/* Update event and dictionary */
    688 	sme_event_register(sdict, edata, sme, &lims, props,
    689 			   PENVSYS_EVENT_LIMITS, see->see_pes.pes_type);
    690 
    691 	return 0;
    692 }
    693 
    694 /*
    695  * sme_events_check:
    696  *
    697  * 	+ Passes the events to the workqueue thread and stops
    698  * 	  the callout if the 'low-power' condition is triggered.
    699  */
    700 void
    701 sme_events_check(void *arg)
    702 {
    703 	struct sysmon_envsys *sme = arg;
    704 	sme_event_t *see;
    705 	uint64_t timo;
    706 
    707 	KASSERT(sme != NULL);
    708 
    709 	mutex_enter(&sme->sme_callout_mtx);
    710 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    711 		workqueue_enqueue(sme->sme_wq, &see->see_wk, NULL);
    712 		see->see_edata->flags |= ENVSYS_FNEED_REFRESH;
    713 	}
    714 	if (sme->sme_events_timeout)
    715 		timo = sme->sme_events_timeout * hz;
    716 	else
    717 		timo = SME_EVTIMO;
    718 	if (!sysmon_low_power)
    719 		sme_schedule_callout(sme);
    720 	mutex_exit(&sme->sme_callout_mtx);
    721 }
    722 
    723 /*
    724  * sme_events_worker:
    725  *
    726  * 	+ workqueue thread that checks if there's a critical condition
    727  * 	  and sends an event if it was triggered.
    728  */
    729 void
    730 sme_events_worker(struct work *wk, void *arg)
    731 {
    732 	sme_event_t *see = (void *)wk;
    733 	struct sysmon_envsys *sme = see->see_sme;
    734 	envsys_data_t *edata = see->see_edata;
    735 
    736 	KASSERT(wk == &see->see_wk);
    737 	KASSERT(sme != NULL || edata != NULL);
    738 
    739 	mutex_enter(&sme->sme_mtx);
    740 	see->see_flags |= SEE_EVENT_WORKING;
    741 	/*
    742 	 * sme_events_check marks the sensors to make us refresh them here.
    743 	 * sme_envsys_refresh_sensor will not call the driver if the driver
    744 	 * does its own setting of the sensor value.
    745 	 */
    746 	if ((edata->flags & ENVSYS_FNEED_REFRESH) != 0) {
    747 		/* refresh sensor in device */
    748 		sysmon_envsys_refresh_sensor(sme, edata);
    749 		edata->flags &= ~ENVSYS_FNEED_REFRESH;
    750 	}
    751 
    752 	DPRINTFOBJ(("%s: (%s) desc=%s sensor=%d type=%d state=%d units=%d "
    753 	    "value_cur=%d upropset=%d\n", __func__, sme->sme_name, edata->desc,
    754 	    edata->sensor, see->see_type, edata->state, edata->units,
    755 	    edata->value_cur, edata->upropset));
    756 
    757 	/* skip the event if current sensor is in invalid state */
    758 	if (edata->state == ENVSYS_SINVALID)
    759 		goto out;
    760 
    761 	/*
    762 	 * For range limits, if the driver claims responsibility for
    763 	 * limit/range checking, just user driver-supplied status.
    764 	 * Else calculate our own status.  Note that driver must
    765 	 * relinquish responsibility for ALL limits if there is even
    766 	 * one limit that it cannot handle!
    767 	 *
    768 	 * If this is a CAPACITY monitor, but the sensor's max_value
    769 	 * is not set, treat it as though the monitor does not exist.
    770 	 */
    771 	if ((see->see_type == PENVSYS_EVENT_LIMITS ||
    772 	     see->see_type == PENVSYS_EVENT_CAPACITY) &&
    773 	    (edata->upropset & PROP_DRIVER_LIMITS) == 0) {
    774 		if ((see->see_type == PENVSYS_EVENT_CAPACITY) &&
    775 		    (edata->value_max == 0))
    776 			edata->state = ENVSYS_SVALID;
    777 		else if ((edata->upropset & (PROP_CRITMIN | PROP_BATTCAP)) &&
    778 		    (edata->value_cur < edata->limits.sel_critmin))
    779 			edata->state = ENVSYS_SCRITUNDER;
    780 		else if ((edata->upropset & (PROP_WARNMIN | PROP_BATTWARN)) &&
    781 			 (edata->value_cur < edata->limits.sel_warnmin))
    782 			edata->state = ENVSYS_SWARNUNDER;
    783 		else if ((edata->upropset & (PROP_CRITMAX | PROP_BATTMAX)) &&
    784 			 (edata->value_cur > edata->limits.sel_critmax))
    785 			edata->state = ENVSYS_SCRITOVER;
    786 		else if ((edata->upropset & (PROP_WARNMAX | PROP_BATTHIGH)) &&
    787 			 (edata->value_cur > edata->limits.sel_warnmax))
    788 			edata->state = ENVSYS_SWARNOVER;
    789 		else
    790 			edata->state = ENVSYS_SVALID;
    791 	}
    792 	sme_deliver_event(see);
    793 
    794 out:
    795 	see->see_flags &= ~SEE_EVENT_WORKING;
    796 	cv_broadcast(&sme->sme_condvar);
    797 	mutex_exit(&sme->sme_mtx);
    798 }
    799 
    800 /*
    801  * sysmon_envsys_sensor_event
    802  *
    803  *	+ Find the monitor event of a particular type for a given sensor
    804  *	  on a device and deliver the event if one is required.  If
    805  *	  no event type is specified, deliver all events for the sensor.
    806  */
    807 void
    808 sysmon_envsys_sensor_event(struct sysmon_envsys *sme, envsys_data_t *edata,
    809 			   int ev_type)
    810 {
    811 	sme_event_t *see;
    812 
    813 	mutex_enter(&sme->sme_mtx);
    814 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    815 		if (edata != see->see_edata)
    816 			continue;
    817 		if (ev_type == 0 ||
    818 		    ev_type == see->see_type) {
    819 			sme_deliver_event(see);
    820 			if (ev_type != 0)
    821 				break;
    822 		}
    823 	}
    824 	mutex_exit(&sme->sme_mtx);
    825 }
    826 
    827 /*
    828  * sme_deliver_event:
    829  *
    830  * 	+ If new sensor state requires it, send an event to powerd
    831  *
    832  *	  Must be called with the device's sysmon mutex held
    833  *		see->see_sme->sme_mtx
    834  */
    835 void
    836 sme_deliver_event(sme_event_t *see)
    837 {
    838 	envsys_data_t *edata = see->see_edata;
    839 	const struct sme_descr_entry *sdt = NULL;
    840 	const struct sme_sensor_event *sse = sme_sensor_event;
    841 	int i, state = 0;
    842 
    843 	switch (see->see_type) {
    844 	case PENVSYS_EVENT_LIMITS:
    845 	case PENVSYS_EVENT_CAPACITY:
    846 		/*
    847 		 * Send event if state has changed
    848 		 */
    849 		if (edata->state == see->see_evsent)
    850 			break;
    851 
    852 		for (i = 0; sse[i].state != -1; i++)
    853 			if (sse[i].state == edata->state)
    854 				break;
    855 
    856 		if (sse[i].state == -1)
    857 			break;
    858 
    859 		if (edata->state == ENVSYS_SVALID)
    860 			sysmon_penvsys_event(&see->see_pes,
    861 					     PENVSYS_EVENT_NORMAL);
    862 		else
    863 			sysmon_penvsys_event(&see->see_pes, sse[i].event);
    864 
    865 		see->see_evsent = edata->state;
    866 		DPRINTFOBJ(("%s: (%s) desc=%s sensor=%d state=%d send_ev=%d\n",
    867 		    __func__, see->see_sme->sme_name, edata->desc,
    868 		    edata->sensor, edata->state,
    869 		    (edata->state == ENVSYS_SVALID) ? PENVSYS_EVENT_NORMAL :
    870 			sse[i].event));
    871 
    872 		break;
    873 
    874 	/*
    875 	 * Send PENVSYS_EVENT_CRITICAL event if:
    876 	 *	State has gone from non-CRITICAL to CRITICAL,
    877 	 *	State remains CRITICAL and value has changed, or
    878 	 *	State has returned from CRITICAL to non-CRITICAL
    879 	 */
    880 	case PENVSYS_EVENT_CRITICAL:
    881 		if (edata->state == ENVSYS_SVALID &&
    882 		    see->see_evsent != 0) {
    883 			sysmon_penvsys_event(&see->see_pes,
    884 					     PENVSYS_EVENT_NORMAL);
    885 			see->see_evsent = 0;
    886 		} else if (edata->state == ENVSYS_SCRITICAL &&
    887 		    see->see_evsent != edata->value_cur) {
    888 			sysmon_penvsys_event(&see->see_pes,
    889 					     PENVSYS_EVENT_CRITICAL);
    890 			see->see_evsent = edata->value_cur;
    891 		}
    892 		break;
    893 
    894 	/*
    895 	 * if value_cur is not normal (battery) or online (drive),
    896 	 * send the event...
    897 	 */
    898 	case PENVSYS_EVENT_STATE_CHANGED:
    899 		/*
    900 		 * the state has not been changed, just ignore the event.
    901 		 */
    902 		if (edata->value_cur == see->see_evsent)
    903 			break;
    904 
    905 		switch (edata->units) {
    906 		case ENVSYS_DRIVE:
    907 			sdt = sme_find_table_entry(SME_DESC_DRIVE_STATES,
    908 			    edata->value_cur);
    909 			state = ENVSYS_DRIVE_ONLINE;
    910 			break;
    911 		case ENVSYS_BATTERY_CAPACITY:
    912 			sdt = sme_find_table_entry(SME_DESC_BATTERY_CAPACITY,
    913 			    edata->value_cur);
    914 			state = ENVSYS_BATTERY_CAPACITY_NORMAL;
    915 			break;
    916 		default:
    917 			panic("%s: bad units for PENVSYS_EVENT_STATE_CHANGED",
    918 			    __func__);
    919 		}
    920 
    921 		if (sdt->type == -1)
    922 			break;
    923 
    924 		/*
    925 		 * copy current state description.
    926 		 */
    927 		(void)strlcpy(see->see_pes.pes_statedesc, sdt->desc,
    928 		    sizeof(see->see_pes.pes_statedesc));
    929 
    930 		if (edata->value_cur == state)
    931 			/*
    932 			 * state returned to normal condition
    933 			 */
    934 			sysmon_penvsys_event(&see->see_pes,
    935 					     PENVSYS_EVENT_NORMAL);
    936 		else
    937 			/*
    938 			 * state changed to abnormal condition
    939 			 */
    940 			sysmon_penvsys_event(&see->see_pes, see->see_type);
    941 
    942 		see->see_evsent = edata->value_cur;
    943 
    944 		/*
    945 		 * There's no need to continue if it's a drive sensor.
    946 		 */
    947 		if (edata->units == ENVSYS_DRIVE)
    948 			break;
    949 
    950 		/*
    951 		 * Check if the system is running in low power and send the
    952 		 * event to powerd (if running) or shutdown the system
    953 		 * otherwise.
    954 		 */
    955 		if (!sysmon_low_power && sme_event_check_low_power()) {
    956 			struct penvsys_state pes;
    957 
    958 			/*
    959 			 * Stop the callout and send the 'low-power' event.
    960 			 */
    961 			sysmon_low_power = true;
    962 			callout_stop(&see->see_sme->sme_callout);
    963 			pes.pes_type = PENVSYS_TYPE_BATTERY;
    964 			sysmon_penvsys_event(&pes, PENVSYS_EVENT_LOW_POWER);
    965 		}
    966 		break;
    967 	case PENVSYS_EVENT_NULL:
    968 		break;
    969 	default:
    970 		panic("%s: invalid event type %d", __func__, see->see_type);
    971 	}
    972 }
    973 
    974 /*
    975  * Returns true if the system is in low power state: an AC adapter
    976  * is OFF and all batteries are in LOW/CRITICAL state.
    977  */
    978 static bool
    979 sme_event_check_low_power(void)
    980 {
    981 	if (!sme_acadapter_check())
    982 		return false;
    983 
    984 	return sme_battery_check();
    985 }
    986 
    987 /*
    988  * Called with the sysmon_envsys device mtx held through the
    989  * workqueue thread.
    990  */
    991 static bool
    992 sme_acadapter_check(void)
    993 {
    994 	struct sysmon_envsys *sme;
    995 	envsys_data_t *edata;
    996 	bool dev = false, sensor = false;
    997 
    998 	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
    999 		if (sme->sme_class == SME_CLASS_ACADAPTER) {
   1000 			dev = true;
   1001 			break;
   1002 		}
   1003 	}
   1004 
   1005 	/*
   1006 	 * No AC Adapter devices were found.
   1007 	 */
   1008 	if (!dev)
   1009 		return false;
   1010 
   1011 	/*
   1012 	 * Check if there's an AC adapter device connected.
   1013 	 */
   1014 	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
   1015 		if (edata->units == ENVSYS_INDICATOR) {
   1016 			sensor = true;
   1017 			/* refresh current sensor */
   1018 			sysmon_envsys_refresh_sensor(sme, edata);
   1019 			if (edata->value_cur)
   1020 				return false;
   1021 		}
   1022 	}
   1023 
   1024 	if (!sensor)
   1025 		return false;
   1026 
   1027 	/*
   1028 	 * AC adapter found and not connected.
   1029 	 */
   1030 	return true;
   1031 }
   1032 
   1033 /*
   1034  * Called with the sysmon_envsys device mtx held through the
   1035  * workqueue thread.
   1036  */
   1037 static bool
   1038 sme_battery_check(void)
   1039 {
   1040 	struct sysmon_envsys *sme;
   1041 	envsys_data_t *edata;
   1042 	int batteriesfound = 0;
   1043 	bool present, batterycap, batterycharge;
   1044 
   1045 	/*
   1046 	 * Check for battery devices and its state.
   1047 	 */
   1048 	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
   1049 		if (sme->sme_class != SME_CLASS_BATTERY)
   1050 			continue;
   1051 
   1052 		present = true;
   1053 		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
   1054 			if (edata->units == ENVSYS_INDICATOR &&
   1055 			    !edata->value_cur) {
   1056 				present = false;
   1057 				break;
   1058 			}
   1059 		}
   1060 		if (!present)
   1061 			continue;
   1062 		/*
   1063 		 * We've found a battery device...
   1064 		 */
   1065 		batteriesfound++;
   1066 		batterycap = batterycharge = false;
   1067 		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
   1068 			if (edata->units == ENVSYS_BATTERY_CAPACITY) {
   1069 				batterycap = true;
   1070 				if (!sme_battery_critical(edata))
   1071 					return false;
   1072 			} else if (edata->units == ENVSYS_BATTERY_CHARGE) {
   1073 				batterycharge = true;
   1074 				if (edata->value_cur)
   1075 					return false;
   1076 			}
   1077 		}
   1078 		if (!batterycap || !batterycharge)
   1079 			return false;
   1080 	}
   1081 
   1082 	if (!batteriesfound)
   1083 		return false;
   1084 
   1085 	/*
   1086 	 * All batteries in low/critical capacity and discharging.
   1087 	 */
   1088 	return true;
   1089 }
   1090 
   1091 static bool
   1092 sme_battery_critical(envsys_data_t *edata)
   1093 {
   1094 	if (edata->value_cur == ENVSYS_BATTERY_CAPACITY_CRITICAL ||
   1095 	    edata->value_cur == ENVSYS_BATTERY_CAPACITY_LOW)
   1096 		return true;
   1097 
   1098 	return false;
   1099 }
   1100