Home | History | Annotate | Line # | Download | only in sysmon
sysmon_envsys_events.c revision 1.104
      1 /* $NetBSD: sysmon_envsys_events.c,v 1.104 2012/08/27 21:42:04 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.104 2012/08/27 21:42:04 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_CAPACITY:
    219 			see->see_evstate = ENVSYS_BATTERY_CAPACITY_NORMAL;
    220 			break;
    221 		case PENVSYS_EVENT_STATE_CHANGED:
    222 			if (edata->units == ENVSYS_BATTERY_CAPACITY)
    223 				see->see_evstate =
    224 				    ENVSYS_BATTERY_CAPACITY_NORMAL;
    225 			else if (edata->units == ENVSYS_DRIVE)
    226 				see->see_evstate = ENVSYS_DRIVE_EMPTY;
    227 			else if (edata->units == ENVSYS_INDICATOR)
    228 				see->see_evstate = ENVSYS_SVALID;
    229 			else
    230 				panic("%s: bad units for "
    231 				      "PENVSYS_EVENT_STATE_CHANGED", __func__);
    232 			break;
    233 		case PENVSYS_EVENT_CRITICAL:
    234 		case PENVSYS_EVENT_LIMITS:
    235 		default:
    236 			see->see_evstate = ENVSYS_SVALID;
    237 			break;
    238 		}
    239 		see->see_evvalue = 0;
    240 
    241 		(void)strlcpy(see->see_pes.pes_dvname, sme->sme_name,
    242 		    sizeof(see->see_pes.pes_dvname));
    243 		(void)strlcpy(see->see_pes.pes_sensname, edata->desc,
    244 		    sizeof(see->see_pes.pes_sensname));
    245 	}
    246 
    247 	/*
    248 	 * Limit operation requested.
    249 	 */
    250 #define	LIMIT_OP(k, l, p)						\
    251 	if (props & p) {						\
    252 		objkey = k;						\
    253 		obj = prop_dictionary_get(sdict, objkey);		\
    254 		if (obj != NULL &&					\
    255 		    prop_object_type(obj) != PROP_TYPE_NUMBER) {	\
    256 			DPRINTF(("%s: (%s) %s object no TYPE_NUMBER\n",	\
    257 			    __func__, sme->sme_name, objkey));		\
    258 			error = ENOTSUP;				\
    259 		} else {						\
    260 			edata->limits.l = lims->l;			\
    261 			error = sme_sensor_upint32(sdict, objkey,lims->l); \
    262 			DPRINTF(("%s: (%s) event [sensor=%s type=%d] "	\
    263 			    "(%s updated)\n", __func__, sme->sme_name,	\
    264 			    edata->desc, crittype, objkey));		\
    265 		}							\
    266 		if (error && error != EEXIST)				\
    267 			goto out;					\
    268 		edata->upropset |= p;					\
    269 	}
    270 
    271 	/* Value-based limits */
    272 	LIMIT_OP("critical-max", sel_critmax, PROP_CRITMAX);
    273 	LIMIT_OP("warning-max",  sel_warnmax, PROP_WARNMAX);
    274 	LIMIT_OP("warning-min",  sel_warnmin, PROP_WARNMIN);
    275 	LIMIT_OP("critical-min", sel_critmin, PROP_CRITMIN);
    276 
    277 	/* %Capacity-based limits */
    278 	LIMIT_OP("maximum-capacity",  sel_critmax,  PROP_BATTMAX);
    279 	LIMIT_OP("high-capacity",     sel_warnmax,  PROP_BATTHIGH);
    280 	LIMIT_OP("warning-capacity",  sel_warnmin,  PROP_BATTWARN);
    281 	LIMIT_OP("critical-capacity", sel_critmin,  PROP_BATTCAP);
    282 
    283 #undef LIMIT_OP
    284 
    285 	if (props & PROP_DRIVER_LIMITS)
    286 		edata->upropset |= PROP_DRIVER_LIMITS;
    287 	else
    288 		edata->upropset &= ~PROP_DRIVER_LIMITS;
    289 
    290 	DPRINTF(("%s: (%s) event registered (sensor=%s snum=%d type=%d "
    291 	    "critmin=%" PRIu32 " warnmin=%" PRIu32 " warnmax=%" PRIu32
    292 	    " critmax=%" PRIu32 " props 0x%04x)\n", __func__,
    293 	    see->see_sme->sme_name, see->see_pes.pes_sensname,
    294 	    edata->sensor, see->see_type, edata->limits.sel_critmin,
    295 	    edata->limits.sel_warnmin, edata->limits.sel_warnmax,
    296 	    edata->limits.sel_critmax, edata->upropset));
    297 	/*
    298 	 * Initialize the events framework if it wasn't initialized before.
    299 	 */
    300 	if ((sme->sme_flags & SME_CALLOUT_INITIALIZED) == 0)
    301 		error = sme_events_init(sme);
    302 
    303 	/*
    304 	 * If driver requested notification, advise it of new
    305 	 * limit values
    306 	 */
    307 	if (sme->sme_set_limits)
    308 		(*sme->sme_set_limits)(sme, edata, &(edata->limits),
    309 					&(edata->upropset));
    310 
    311 out:
    312 	if ((error == 0 || error == EEXIST) && osee == NULL)
    313 		LIST_INSERT_HEAD(&sme->sme_events_list, see, see_list);
    314 
    315 	mutex_exit(&sme->sme_mtx);
    316 
    317 	return error;
    318 }
    319 
    320 /*
    321  * sme_event_unregister_all:
    322  *
    323  * 	+ Unregisters all events associated with a sysmon envsys device.
    324  */
    325 void
    326 sme_event_unregister_all(struct sysmon_envsys *sme)
    327 {
    328 	sme_event_t *see;
    329 	int evcounter = 0;
    330 
    331 	KASSERT(sme != NULL);
    332 
    333 	mutex_enter(&sme->sme_mtx);
    334 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    335 		while (see->see_flags & SEE_EVENT_WORKING)
    336 			cv_wait(&sme->sme_condvar, &sme->sme_mtx);
    337 
    338 		if (strcmp(see->see_pes.pes_dvname, sme->sme_name) == 0)
    339 			evcounter++;
    340 	}
    341 
    342 	DPRINTF(("%s: total events %d (%s)\n", __func__,
    343 	    evcounter, sme->sme_name));
    344 
    345 	while ((see = LIST_FIRST(&sme->sme_events_list))) {
    346 		if (evcounter == 0)
    347 			break;
    348 
    349 		if (strcmp(see->see_pes.pes_dvname, sme->sme_name) == 0) {
    350 			DPRINTF(("%s: event %s %d removed (%s)\n", __func__,
    351 			    see->see_pes.pes_sensname, see->see_type,
    352 			    sme->sme_name));
    353 			sme_remove_event(see, sme);
    354 
    355 			evcounter--;
    356 		}
    357 	}
    358 
    359 	if (LIST_EMPTY(&sme->sme_events_list))
    360 		if (sme->sme_flags & SME_CALLOUT_INITIALIZED)
    361 			sme_events_destroy(sme);
    362 	mutex_exit(&sme->sme_mtx);
    363 }
    364 
    365 /*
    366  * sme_event_unregister:
    367  *
    368  * 	+ Unregisters an event from the specified sysmon envsys device.
    369  */
    370 int
    371 sme_event_unregister(struct sysmon_envsys *sme, const char *sensor, int type)
    372 {
    373 	sme_event_t *see;
    374 	bool found = false;
    375 
    376 	KASSERT(sensor != NULL);
    377 
    378 	mutex_enter(&sme->sme_mtx);
    379 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    380 		if (strcmp(see->see_pes.pes_sensname, sensor) == 0) {
    381 			if (see->see_type == type) {
    382 				found = true;
    383 				break;
    384 			}
    385 		}
    386 	}
    387 
    388 	if (!found) {
    389 		mutex_exit(&sme->sme_mtx);
    390 		return EINVAL;
    391 	}
    392 
    393 	/*
    394 	 * Wait for the event to finish its work, remove from the list
    395 	 * and release resouces.
    396 	 */
    397 	while (see->see_flags & SEE_EVENT_WORKING)
    398 		cv_wait(&sme->sme_condvar, &sme->sme_mtx);
    399 
    400 	DPRINTF(("%s: removed dev=%s sensor=%s type=%d\n",
    401 	    __func__, see->see_pes.pes_dvname, sensor, type));
    402 
    403 	sme_remove_event(see, sme);
    404 
    405 	mutex_exit(&sme->sme_mtx);
    406 	return 0;
    407 }
    408 
    409 /*
    410  * sme_event_unregister_sensor:
    411  *
    412  *	+ Unregisters any event associated with a specific sensor
    413  *	  The caller must already own the sme_mtx.
    414  */
    415 int
    416 sme_event_unregister_sensor(struct sysmon_envsys *sme, envsys_data_t *edata)
    417 {
    418 	sme_event_t *see;
    419 	bool found = false;
    420 
    421 	KASSERT(mutex_owned(&sme->sme_mtx));
    422 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    423 		if (see->see_edata == edata) {
    424 			found = true;
    425 			break;
    426 		}
    427 	}
    428 	if (!found)
    429 		return EINVAL;
    430 
    431 	/*
    432 	 * Wait for the event to finish its work, remove from the list
    433 	 * and release resouces.
    434 	 */
    435 	while (see->see_flags & SEE_EVENT_WORKING)
    436 		cv_wait(&sme->sme_condvar, &sme->sme_mtx);
    437 
    438 	DPRINTF(("%s: removed dev=%s sensor=%s\n",
    439 	    __func__, see->see_pes.pes_dvname, edata->desc));
    440 
    441 	sme_remove_event(see, sme);
    442 
    443 	return 0;
    444 }
    445 
    446 static void
    447 sme_remove_event(sme_event_t *see, struct sysmon_envsys *sme)
    448 {
    449 
    450 	KASSERT(mutex_owned(&sme->sme_mtx));
    451 
    452 	if (see->see_edata->flags & ENVSYS_FHAS_ENTROPY)
    453 		rnd_detach_source(&see->see_edata->rnd_src);
    454 	LIST_REMOVE(see, see_list);
    455 	/*
    456 	 * So the events list is empty, we'll do the following:
    457 	 *
    458 	 * 	- stop and destroy the callout.
    459 	 * 	- destroy the workqueue.
    460 	 */
    461 	if (LIST_EMPTY(&sme->sme_events_list))
    462 		sme_events_destroy(sme);
    463 
    464 	kmem_free(see, sizeof(*see));
    465 }
    466 
    467 /*
    468  * sme_event_drvadd:
    469  *
    470  * 	+ Registers a new event for a device that had enabled any of
    471  * 	  the monitoring flags in the driver.
    472  */
    473 void
    474 sme_event_drvadd(void *arg)
    475 {
    476 	sme_event_drv_t *sed_t = arg;
    477 	sysmon_envsys_lim_t lims;
    478 	uint32_t props;
    479 	int error = 0;
    480 
    481 	KASSERT(sed_t != NULL);
    482 
    483 #define SEE_REGEVENT(a, b, c)						\
    484 do {									\
    485 	if (sed_t->sed_edata->flags & (a)) {				\
    486 		char str[ENVSYS_DESCLEN] = "monitoring-state-";		\
    487 									\
    488 		error = sme_event_register(sed_t->sed_sdict,		\
    489 				      sed_t->sed_edata,			\
    490 				      sed_t->sed_sme,			\
    491 				      &lims, props,			\
    492 				      (b),				\
    493 				      sed_t->sed_powertype);		\
    494 		if (error && error != EEXIST)				\
    495 			printf("%s: failed to add event! "		\
    496 			    "error=%d sensor=%s event=%s\n",		\
    497 			    __func__, error,				\
    498 			    sed_t->sed_edata->desc, (c));		\
    499 		else {							\
    500 			(void)strlcat(str, (c), sizeof(str));		\
    501 			prop_dictionary_set_bool(sed_t->sed_sdict,	\
    502 						 str,			\
    503 						 true);			\
    504 		}							\
    505 	}								\
    506 } while (/* CONSTCOND */ 0)
    507 
    508 	/*
    509 	 * If driver provides a method to retrieve its internal limit
    510 	 * values, call it and use those returned values as initial
    511 	 * limits for event monitoring.
    512 	 */
    513 	props = 0;
    514 	if (sed_t->sed_edata->flags & ENVSYS_FMONLIMITS)
    515 		if (sed_t->sed_sme->sme_get_limits)
    516 			(*sed_t->sed_sme->sme_get_limits)(sed_t->sed_sme,
    517 							  sed_t->sed_edata,
    518 							  &lims, &props);
    519 	/*
    520 	 * If driver doesn't provide a way to "absorb" user-specified
    521 	 * limit values, we must monitor all limits ourselves
    522 	 */
    523 	if (sed_t->sed_sme->sme_set_limits == NULL)
    524 		props &= ~PROP_DRIVER_LIMITS;
    525 
    526 	/* Register the events that were specified */
    527 
    528 	SEE_REGEVENT(ENVSYS_FMONCRITICAL,
    529 		     PENVSYS_EVENT_CRITICAL,
    530 		     "critical");
    531 
    532 	SEE_REGEVENT(ENVSYS_FMONSTCHANGED,
    533 		     PENVSYS_EVENT_STATE_CHANGED,
    534 		     "state-changed");
    535 
    536 	SEE_REGEVENT(ENVSYS_FMONLIMITS,
    537 		     PENVSYS_EVENT_LIMITS,
    538 		     "hw-range-limits");
    539 
    540 	SEE_REGEVENT(ENVSYS_FHAS_ENTROPY,
    541 		     PENVSYS_EVENT_NULL,
    542 		     "refresh-event");
    543 
    544 	/*
    545 	 * we are done, free memory now.
    546 	 */
    547 	kmem_free(sed_t, sizeof(*sed_t));
    548 }
    549 
    550 /*
    551  * sme_events_init:
    552  *
    553  * 	+ Initialize the events framework for this device.
    554  */
    555 int
    556 sme_events_init(struct sysmon_envsys *sme)
    557 {
    558 	int error = 0;
    559 
    560 	KASSERT(sme != NULL);
    561 	KASSERT(mutex_owned(&sme->sme_mtx));
    562 
    563 	error = workqueue_create(&sme->sme_wq, sme->sme_name,
    564 	    sme_events_worker, sme, PRI_NONE, IPL_SOFTCLOCK, WQ_MPSAFE);
    565 	if (error)
    566 		return error;
    567 
    568 	mutex_init(&sme->sme_callout_mtx, MUTEX_DEFAULT, IPL_SOFTCLOCK);
    569 	callout_init(&sme->sme_callout, CALLOUT_MPSAFE);
    570 	callout_setfunc(&sme->sme_callout, sme_events_check, sme);
    571 	sme->sme_flags |= SME_CALLOUT_INITIALIZED;
    572 	sme_schedule_callout(sme);
    573 	DPRINTF(("%s: events framework initialized for '%s'\n",
    574 	    __func__, sme->sme_name));
    575 
    576 	return error;
    577 }
    578 
    579 /*
    580  * sme_schedule_callout
    581  *
    582  *	(Re)-schedule the device's callout timer
    583  */
    584 void
    585 sme_schedule_callout(struct sysmon_envsys *sme)
    586 {
    587 	uint64_t timo;
    588 
    589 	KASSERT(sme != NULL);
    590 
    591 	if ((sme->sme_flags & SME_CALLOUT_INITIALIZED) == 0)
    592 		return;
    593 
    594 	if (sme->sme_events_timeout)
    595 		timo = sme->sme_events_timeout * hz;
    596 	else
    597 		timo = SME_EVTIMO;
    598 
    599 	callout_stop(&sme->sme_callout);
    600 	callout_schedule(&sme->sme_callout, timo);
    601 }
    602 
    603 /*
    604  * sme_events_destroy:
    605  *
    606  * 	+ Destroys the event framework for this device: callout
    607  * 	  stopped, workqueue destroyed and callout mutex destroyed.
    608  */
    609 void
    610 sme_events_destroy(struct sysmon_envsys *sme)
    611 {
    612 	KASSERT(mutex_owned(&sme->sme_mtx));
    613 
    614 	callout_stop(&sme->sme_callout);
    615 	workqueue_destroy(sme->sme_wq);
    616 	mutex_destroy(&sme->sme_callout_mtx);
    617 	callout_destroy(&sme->sme_callout);
    618 	sme->sme_flags &= ~SME_CALLOUT_INITIALIZED;
    619 	DPRINTF(("%s: events framework destroyed for '%s'\n",
    620 	    __func__, sme->sme_name));
    621 }
    622 
    623 /*
    624  * sysmon_envsys_update_limits
    625  *
    626  *	+ If a driver needs to update the limits that it is providing,
    627  *	  we need to update the dictionary data as well as the limits.
    628  *	  This only makes sense if the driver is capable of providing
    629  *	  its limits, and if there is a limits event-monitor.
    630  */
    631 int
    632 sysmon_envsys_update_limits(struct sysmon_envsys *sme, envsys_data_t *edata)
    633 {
    634 	int err;
    635 
    636 	sysmon_envsys_acquire(sme, false);
    637 	if (sme->sme_get_limits == NULL ||
    638 	    (edata->flags & ENVSYS_FMONLIMITS) == 0)
    639 		err = EINVAL;
    640 	else
    641 		err = sme_update_limits(sme, edata);
    642 	sysmon_envsys_release(sme, false);
    643 
    644 	return err;
    645 }
    646 
    647 /*
    648  * sme_update_limits
    649  *
    650  *	+ Internal version of sysmon_envsys_update_limits() to be used
    651  *	  when the device has already been sysmon_envsys_acquire()d.
    652  */
    653 
    654 int
    655 sme_update_limits(struct sysmon_envsys *sme, envsys_data_t *edata)
    656 {
    657 	prop_dictionary_t sdict = NULL;
    658 	prop_array_t array = NULL;
    659 	sysmon_envsys_lim_t lims;
    660 	sme_event_t *see;
    661 	uint32_t props = 0;
    662 
    663 	/* Find the dictionary for this sensor */
    664 	array = prop_dictionary_get(sme_propd, sme->sme_name);
    665 	if (array == NULL ||
    666 	    prop_object_type(array) != PROP_TYPE_ARRAY) {
    667 		DPRINTF(("%s: array device failed\n", __func__));
    668 		return EINVAL;
    669 	}
    670 
    671 	sdict = prop_array_get(array, edata->sensor);
    672 	if (sdict == NULL) {
    673 		return EINVAL;
    674 	}
    675 
    676 	/* Find the event definition to get its powertype */
    677 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    678 		if (edata == see->see_edata &&
    679 		    see->see_type == PENVSYS_EVENT_LIMITS)
    680 			break;
    681 	}
    682 	if (see == NULL)
    683 		return EINVAL;
    684 
    685 	/* Update limit values from driver if possible */
    686 	if (sme->sme_get_limits != NULL)
    687 		(*sme->sme_get_limits)(sme, edata, &lims, &props);
    688 
    689 	/* Update event and dictionary */
    690 	sme_event_register(sdict, edata, sme, &lims, props,
    691 			   PENVSYS_EVENT_LIMITS, see->see_pes.pes_type);
    692 
    693 	return 0;
    694 }
    695 
    696 /*
    697  * sme_events_check:
    698  *
    699  * 	+ Passes the events to the workqueue thread and stops
    700  * 	  the callout if the 'low-power' condition is triggered.
    701  */
    702 void
    703 sme_events_check(void *arg)
    704 {
    705 	struct sysmon_envsys *sme = arg;
    706 	sme_event_t *see;
    707 	uint64_t timo;
    708 
    709 	KASSERT(sme != NULL);
    710 
    711 	mutex_enter(&sme->sme_callout_mtx);
    712 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    713 		workqueue_enqueue(sme->sme_wq, &see->see_wk, NULL);
    714 		see->see_edata->flags |= ENVSYS_FNEED_REFRESH;
    715 	}
    716 	if (sme->sme_events_timeout)
    717 		timo = sme->sme_events_timeout * hz;
    718 	else
    719 		timo = SME_EVTIMO;
    720 	if (!sysmon_low_power)
    721 		sme_schedule_callout(sme);
    722 	mutex_exit(&sme->sme_callout_mtx);
    723 }
    724 
    725 /*
    726  * sme_events_worker:
    727  *
    728  * 	+ workqueue thread that checks if there's a critical condition
    729  * 	  and sends an event if it was triggered.
    730  */
    731 void
    732 sme_events_worker(struct work *wk, void *arg)
    733 {
    734 	sme_event_t *see = (void *)wk;
    735 	struct sysmon_envsys *sme = see->see_sme;
    736 	envsys_data_t *edata = see->see_edata;
    737 
    738 	KASSERT(wk == &see->see_wk);
    739 	KASSERT(sme != NULL || edata != NULL);
    740 
    741 	mutex_enter(&sme->sme_mtx);
    742 	see->see_flags |= SEE_EVENT_WORKING;
    743 	/*
    744 	 * sme_events_check marks the sensors to make us refresh them here.
    745 	 * sme_envsys_refresh_sensor will not call the driver if the driver
    746 	 * does its own setting of the sensor value.
    747 	 */
    748 	if ((edata->flags & ENVSYS_FNEED_REFRESH) != 0) {
    749 		/* refresh sensor in device */
    750 		sysmon_envsys_refresh_sensor(sme, edata);
    751 		edata->flags &= ~ENVSYS_FNEED_REFRESH;
    752 	}
    753 
    754 	DPRINTFOBJ(("%s: (%s) desc=%s sensor=%d type=%d state=%d units=%d "
    755 	    "value_cur=%d upropset=%d\n", __func__, sme->sme_name, edata->desc,
    756 	    edata->sensor, see->see_type, edata->state, edata->units,
    757 	    edata->value_cur, edata->upropset));
    758 
    759 	/* skip the event if current sensor is in invalid state */
    760 	if (edata->state == ENVSYS_SINVALID)
    761 		goto out;
    762 
    763 	/*
    764 	 * For range limits, if the driver claims responsibility for
    765 	 * limit/range checking, just user driver-supplied status.
    766 	 * Else calculate our own status.  Note that driver must
    767 	 * relinquish responsibility for ALL limits if there is even
    768 	 * one limit that it cannot handle!
    769 	 *
    770 	 * If this is a CAPACITY monitor, but the sensor's max_value
    771 	 * is not set, treat it as though the monitor does not exist.
    772 	 */
    773 	if ((see->see_type == PENVSYS_EVENT_LIMITS ||
    774 	     see->see_type == PENVSYS_EVENT_CAPACITY) &&
    775 	    (edata->upropset & PROP_DRIVER_LIMITS) == 0) {
    776 		if ((see->see_type == PENVSYS_EVENT_CAPACITY) &&
    777 		    (edata->value_max == 0))
    778 			edata->state = ENVSYS_SVALID;
    779 		else if ((edata->upropset & (PROP_CRITMIN | PROP_BATTCAP)) &&
    780 		    (edata->value_cur < edata->limits.sel_critmin))
    781 			edata->state = ENVSYS_SCRITUNDER;
    782 		else if ((edata->upropset & (PROP_WARNMIN | PROP_BATTWARN)) &&
    783 			 (edata->value_cur < edata->limits.sel_warnmin))
    784 			edata->state = ENVSYS_SWARNUNDER;
    785 		else if ((edata->upropset & (PROP_CRITMAX | PROP_BATTMAX)) &&
    786 			 (edata->value_cur > edata->limits.sel_critmax))
    787 			edata->state = ENVSYS_SCRITOVER;
    788 		else if ((edata->upropset & (PROP_WARNMAX | PROP_BATTHIGH)) &&
    789 			 (edata->value_cur > edata->limits.sel_warnmax))
    790 			edata->state = ENVSYS_SWARNOVER;
    791 		else
    792 			edata->state = ENVSYS_SVALID;
    793 	}
    794 	sme_deliver_event(see);
    795 
    796 out:
    797 	see->see_flags &= ~SEE_EVENT_WORKING;
    798 	cv_broadcast(&sme->sme_condvar);
    799 	mutex_exit(&sme->sme_mtx);
    800 }
    801 
    802 /*
    803  * sysmon_envsys_sensor_event
    804  *
    805  *	+ Find the monitor event of a particular type for a given sensor
    806  *	  on a device and deliver the event if one is required.  If
    807  *	  no event type is specified, deliver all events for the sensor.
    808  */
    809 void
    810 sysmon_envsys_sensor_event(struct sysmon_envsys *sme, envsys_data_t *edata,
    811 			   int ev_type)
    812 {
    813 	sme_event_t *see;
    814 
    815 	mutex_enter(&sme->sme_mtx);
    816 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    817 		if (edata != see->see_edata)
    818 			continue;
    819 		if (ev_type == 0 ||
    820 		    ev_type == see->see_type) {
    821 			sme_deliver_event(see);
    822 			if (ev_type != 0)
    823 				break;
    824 		}
    825 	}
    826 	mutex_exit(&sme->sme_mtx);
    827 }
    828 
    829 /*
    830  * sme_deliver_event:
    831  *
    832  * 	+ If new sensor state requires it, send an event to powerd
    833  *
    834  *	  Must be called with the device's sysmon mutex held
    835  *		see->see_sme->sme_mtx
    836  */
    837 void
    838 sme_deliver_event(sme_event_t *see)
    839 {
    840 	envsys_data_t *edata = see->see_edata;
    841 	const struct sme_descr_entry *sdt = NULL;
    842 	const struct sme_sensor_event *sse = sme_sensor_event;
    843 	int i, state = 0;
    844 
    845 	switch (see->see_type) {
    846 	case PENVSYS_EVENT_LIMITS:
    847 	case PENVSYS_EVENT_CAPACITY:
    848 		/*
    849 		 * Send event if state has changed
    850 		 */
    851 		if (edata->state == see->see_evstate)
    852 			break;
    853 
    854 		for (i = 0; sse[i].state != -1; i++)
    855 			if (sse[i].state == edata->state)
    856 				break;
    857 
    858 		if (sse[i].state == -1)
    859 			break;
    860 
    861 		if (edata->state == ENVSYS_SVALID)
    862 			sysmon_penvsys_event(&see->see_pes,
    863 					     PENVSYS_EVENT_NORMAL);
    864 		else
    865 			sysmon_penvsys_event(&see->see_pes, sse[i].event);
    866 
    867 		see->see_evstate = edata->state;
    868 		DPRINTFOBJ(("%s: (%s) desc=%s sensor=%d state=%d send_ev=%d\n",
    869 		    __func__, see->see_sme->sme_name, edata->desc,
    870 		    edata->sensor, edata->state,
    871 		    (edata->state == ENVSYS_SVALID) ? PENVSYS_EVENT_NORMAL :
    872 			sse[i].event));
    873 
    874 		break;
    875 
    876 	/*
    877 	 * Send PENVSYS_EVENT_CRITICAL event if:
    878 	 *	State has gone from non-CRITICAL to CRITICAL,
    879 	 *	State remains CRITICAL and value has changed, or
    880 	 *	State has returned from CRITICAL to non-CRITICAL
    881 	 */
    882 	case PENVSYS_EVENT_CRITICAL:
    883 		DPRINTF(("%s: CRITICAL: old/new state %d/%d, old/new value "
    884 		    "%d/%d\n", __func__, see->see_evstate, edata->state,
    885 		    see->see_evvalue, edata->value_cur));
    886 		if (edata->state == ENVSYS_SVALID &&
    887 		    see->see_evstate != ENVSYS_SVALID) {
    888 			sysmon_penvsys_event(&see->see_pes,
    889 					     PENVSYS_EVENT_NORMAL);
    890 			see->see_evstate = ENVSYS_SVALID;
    891 			break;
    892 		} else if (edata->state != ENVSYS_SCRITICAL)
    893 			break;
    894 		if (see->see_evstate != ENVSYS_SCRITICAL ||
    895 		    see->see_evvalue != edata->value_cur) {
    896 			sysmon_penvsys_event(&see->see_pes,
    897 					     PENVSYS_EVENT_CRITICAL);
    898 			see->see_evstate = ENVSYS_SCRITICAL;
    899 		}
    900 		see->see_evvalue = edata->value_cur;
    901 		break;
    902 
    903 	/*
    904 	 * if value_cur is not normal (battery) or online (drive),
    905 	 * send the event...
    906 	 */
    907 	case PENVSYS_EVENT_STATE_CHANGED:
    908 		/*
    909 		 * the state has not been changed, just ignore the event.
    910 		 */
    911 		if (edata->value_cur == see->see_evvalue)
    912 			break;
    913 
    914 		switch (edata->units) {
    915 		case ENVSYS_DRIVE:
    916 			sdt = sme_find_table_entry(SME_DESC_DRIVE_STATES,
    917 			    edata->value_cur);
    918 			state = ENVSYS_DRIVE_ONLINE;
    919 			break;
    920 		case ENVSYS_BATTERY_CAPACITY:
    921 			sdt = sme_find_table_entry(SME_DESC_BATTERY_CAPACITY,
    922 			    edata->value_cur);
    923 			state = ENVSYS_BATTERY_CAPACITY_NORMAL;
    924 			break;
    925 		case ENVSYS_INDICATOR:
    926 			sdt = sme_find_table_entry(SME_DESC_INDICATOR,
    927 			    edata->value_cur);
    928 			state = see->see_evvalue;	/* force state change */
    929 			break;
    930 		default:
    931 			panic("%s: bad units for PENVSYS_EVENT_STATE_CHANGED",
    932 			    __func__);
    933 		}
    934 
    935 		if (sdt->type == -1)
    936 			break;
    937 
    938 		/*
    939 		 * copy current state description.
    940 		 */
    941 		(void)strlcpy(see->see_pes.pes_statedesc, sdt->desc,
    942 		    sizeof(see->see_pes.pes_statedesc));
    943 
    944 		if (edata->value_cur == state)
    945 			/*
    946 			 * state returned to normal condition
    947 			 */
    948 			sysmon_penvsys_event(&see->see_pes,
    949 					     PENVSYS_EVENT_NORMAL);
    950 		else
    951 			/*
    952 			 * state changed to abnormal condition
    953 			 */
    954 			sysmon_penvsys_event(&see->see_pes, see->see_type);
    955 
    956 		see->see_evvalue = edata->value_cur;
    957 
    958 		/*
    959 		 * There's no need to continue if it's a drive sensor.
    960 		 */
    961 		if (edata->units == ENVSYS_DRIVE)
    962 			break;
    963 
    964 		/*
    965 		 * Check if the system is running in low power and send the
    966 		 * event to powerd (if running) or shutdown the system
    967 		 * otherwise.
    968 		 */
    969 		if (!sysmon_low_power && sme_event_check_low_power()) {
    970 			struct penvsys_state pes;
    971 
    972 			/*
    973 			 * Stop the callout and send the 'low-power' event.
    974 			 */
    975 			sysmon_low_power = true;
    976 			callout_stop(&see->see_sme->sme_callout);
    977 			pes.pes_type = PENVSYS_TYPE_BATTERY;
    978 			sysmon_penvsys_event(&pes, PENVSYS_EVENT_LOW_POWER);
    979 		}
    980 		break;
    981 	case PENVSYS_EVENT_NULL:
    982 		break;
    983 	default:
    984 		panic("%s: invalid event type %d", __func__, see->see_type);
    985 	}
    986 }
    987 
    988 /*
    989  * Returns true if the system is in low power state: an AC adapter
    990  * is OFF and all batteries are in LOW/CRITICAL state.
    991  */
    992 static bool
    993 sme_event_check_low_power(void)
    994 {
    995 	if (!sme_acadapter_check())
    996 		return false;
    997 
    998 	return sme_battery_check();
    999 }
   1000 
   1001 /*
   1002  * Called with the sysmon_envsys device mtx held through the
   1003  * workqueue thread.
   1004  */
   1005 static bool
   1006 sme_acadapter_check(void)
   1007 {
   1008 	struct sysmon_envsys *sme;
   1009 	envsys_data_t *edata;
   1010 	bool dev = false, sensor = false;
   1011 
   1012 	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
   1013 		if (sme->sme_class == SME_CLASS_ACADAPTER) {
   1014 			dev = true;
   1015 			break;
   1016 		}
   1017 	}
   1018 
   1019 	/*
   1020 	 * No AC Adapter devices were found.
   1021 	 */
   1022 	if (!dev)
   1023 		return false;
   1024 
   1025 	/*
   1026 	 * Check if there's an AC adapter device connected.
   1027 	 */
   1028 	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
   1029 		if (edata->units == ENVSYS_INDICATOR) {
   1030 			sensor = true;
   1031 			/* refresh current sensor */
   1032 			sysmon_envsys_refresh_sensor(sme, edata);
   1033 			if (edata->value_cur)
   1034 				return false;
   1035 		}
   1036 	}
   1037 
   1038 	if (!sensor)
   1039 		return false;
   1040 
   1041 	/*
   1042 	 * AC adapter found and not connected.
   1043 	 */
   1044 	return true;
   1045 }
   1046 
   1047 /*
   1048  * Called with the sysmon_envsys device mtx held through the
   1049  * workqueue thread.
   1050  */
   1051 static bool
   1052 sme_battery_check(void)
   1053 {
   1054 	struct sysmon_envsys *sme;
   1055 	envsys_data_t *edata;
   1056 	int batteriesfound = 0;
   1057 	bool present, batterycap, batterycharge;
   1058 
   1059 	/*
   1060 	 * Check for battery devices and its state.
   1061 	 */
   1062 	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
   1063 		if (sme->sme_class != SME_CLASS_BATTERY)
   1064 			continue;
   1065 
   1066 		present = true;
   1067 		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
   1068 			if (edata->units == ENVSYS_INDICATOR &&
   1069 			    !edata->value_cur) {
   1070 				present = false;
   1071 				break;
   1072 			}
   1073 		}
   1074 		if (!present)
   1075 			continue;
   1076 		/*
   1077 		 * We've found a battery device...
   1078 		 */
   1079 		batteriesfound++;
   1080 		batterycap = batterycharge = false;
   1081 		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
   1082 			if (edata->units == ENVSYS_BATTERY_CAPACITY) {
   1083 				batterycap = true;
   1084 				if (!sme_battery_critical(edata))
   1085 					return false;
   1086 			} else if (edata->units == ENVSYS_BATTERY_CHARGE) {
   1087 				batterycharge = true;
   1088 				if (edata->value_cur)
   1089 					return false;
   1090 			}
   1091 		}
   1092 		if (!batterycap || !batterycharge)
   1093 			return false;
   1094 	}
   1095 
   1096 	if (!batteriesfound)
   1097 		return false;
   1098 
   1099 	/*
   1100 	 * All batteries in low/critical capacity and discharging.
   1101 	 */
   1102 	return true;
   1103 }
   1104 
   1105 static bool
   1106 sme_battery_critical(envsys_data_t *edata)
   1107 {
   1108 	if (edata->value_cur == ENVSYS_BATTERY_CAPACITY_CRITICAL ||
   1109 	    edata->value_cur == ENVSYS_BATTERY_CAPACITY_LOW)
   1110 		return true;
   1111 
   1112 	return false;
   1113 }
   1114