Home | History | Annotate | Line # | Download | only in sysmon
sysmon_envsys_events.c revision 1.88
      1 /* $NetBSD: sysmon_envsys_events.c,v 1.88 2010/03/23 16:52:02 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.88 2010/03/23 16:52:02 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 /*
     81  * sme_event_register:
     82  *
     83  * 	+ Registers a new sysmon envsys event or updates any event
     84  * 	  already in the queue.
     85  */
     86 int
     87 sme_event_register(prop_dictionary_t sdict, envsys_data_t *edata,
     88 		   struct sysmon_envsys *sme, sysmon_envsys_lim_t *lims,
     89 		   uint32_t props, int crittype, int powertype)
     90 {
     91 	sme_event_t *see = NULL, *osee = NULL;
     92 	prop_object_t obj;
     93 	int error = 0;
     94 	const char *objkey;
     95 
     96 	KASSERT(sdict != NULL);
     97 	KASSERT(edata != NULL);
     98 	KASSERT(sme != NULL);
     99 	KASSERT(lims != NULL);
    100 
    101 	/*
    102 	 * Some validation first for limit-checking events
    103 	 *
    104 	 * 1. Limits are not permitted if the units is ENVSYS_INDICATOR.
    105 	 *
    106 	 * 2. Capacity limits are permitted only if the sensor has the
    107 	 *    ENVSYS_FPERCENT flag set and value_max is set.
    108 	 *
    109 	 * 3. It is not permissible for both capacity and value limits
    110 	 *    to coexist.
    111 	 *
    112 	 * Note that it permissible for a sensor to have value limits
    113 	 * even if its ENVSYS_FPERCENT flag and value_max are set.
    114 	 */
    115 
    116 	DPRINTF(("%s: units %d props 0x%04x upropset 0x%04x max_val %"PRId64
    117 		" edata-flags 0x%04x\n", __func__, edata->units, props,
    118 		edata->upropset, edata->value_max, edata->flags));
    119 
    120 	if (props && edata->units == ENVSYS_INDICATOR)
    121 		return ENOTSUP;
    122 
    123 	if ((props & PROP_CAP_LIMITS) &&
    124 	    ((edata->value_max == 0) ||
    125 	     !(edata->flags & ENVSYS_FPERCENT) ||
    126 	     (props & PROP_VAL_LIMITS) ||
    127 	     (edata->upropset & PROP_VAL_LIMITS)))
    128 		return ENOTSUP;
    129 
    130 	if ((props & PROP_VAL_LIMITS) && (edata->upropset & PROP_CAP_LIMITS))
    131 		return ENOTSUP;
    132 
    133 	/*
    134 	 * check if the event is already on the list and return
    135 	 * EEXIST if value provided hasn't been changed.
    136 	 */
    137 	mutex_enter(&sme->sme_mtx);
    138 	LIST_FOREACH(osee, &sme->sme_events_list, see_list) {
    139 		if (strcmp(edata->desc, osee->see_pes.pes_sensname) != 0)
    140 			continue;
    141 		if (crittype != osee->see_type)
    142 			continue;
    143 
    144 		/*
    145 		 * We found an existing event for this sensor.  Make
    146 		 * sure it references the correct edata
    147 		 */
    148 		KASSERT(edata == osee->see_edata);
    149 
    150 		DPRINTF(("%s: dev %s sensor %s: event type %d exists\n",
    151 		    __func__, sme->sme_name, edata->desc, crittype));
    152 
    153 		see = osee;
    154 		if (props & (PROP_CRITMAX | PROP_BATTMAX)) {
    155 			if (lims->sel_critmax == edata->limits.sel_critmax) {
    156 				DPRINTF(("%s: type=%d (critmax exists)\n",
    157 				    __func__, crittype));
    158 				error = EEXIST;
    159 				props &= ~(PROP_CRITMAX | PROP_BATTMAX);
    160 			}
    161 		}
    162 		if (props & (PROP_WARNMAX | PROP_BATTHIGH)) {
    163 			if (lims->sel_warnmax == edata->limits.sel_warnmax) {
    164 				DPRINTF(("%s: warnmax exists\n", __func__));
    165 				error = EEXIST;
    166 				props &= ~(PROP_WARNMAX | PROP_BATTHIGH);
    167 			}
    168 		}
    169 		if (props & (PROP_WARNMIN | PROP_BATTWARN)) {
    170 			if (lims->sel_warnmin == edata->limits.sel_warnmin) {
    171 				DPRINTF(("%s: warnmin exists\n", __func__));
    172 				error = EEXIST;
    173 				props &= ~(PROP_WARNMIN | PROP_BATTWARN);
    174 			}
    175 		}
    176 		if (props & (PROP_CRITMIN | PROP_BATTCAP)) {
    177 			if (lims->sel_critmin == edata->limits.sel_critmin) {
    178 				DPRINTF(("%s: critmin exists\n", __func__));
    179 				error = EEXIST;
    180 				props &= ~(PROP_CRITMIN | PROP_BATTCAP);
    181 			}
    182 		}
    183 		break;
    184 	}
    185 	if (see == NULL) {
    186 		/*
    187 		 * New event requested - allocate a sysmon_envsys event.
    188 		 */
    189 		see = kmem_zalloc(sizeof(*see), KM_SLEEP);
    190 		if (see == NULL)
    191 			return ENOMEM;
    192 
    193 		DPRINTF(("%s: dev %s sensor %s: new event\n",
    194 		    __func__, sme->sme_name, edata->desc));
    195 
    196 		see->see_type = crittype;
    197 		see->see_sme = sme;
    198 		see->see_edata = edata;
    199 
    200 		/* Initialize sensor type and previously-sent state */
    201 
    202 		see->see_pes.pes_type = powertype;
    203 
    204 		switch (crittype) {
    205 		case PENVSYS_EVENT_LIMITS:
    206 			see->see_evsent = ENVSYS_SVALID;
    207 			break;
    208 		case PENVSYS_EVENT_CAPACITY:
    209 			see->see_evsent = ENVSYS_BATTERY_CAPACITY_NORMAL;
    210 			break;
    211 		case PENVSYS_EVENT_STATE_CHANGED:
    212 			if (edata->units == ENVSYS_BATTERY_CAPACITY)
    213 				see->see_evsent = ENVSYS_BATTERY_CAPACITY_NORMAL;
    214 			else if (edata->units == ENVSYS_DRIVE)
    215 				see->see_evsent = ENVSYS_DRIVE_EMPTY;
    216 			else
    217 				panic("%s: bad units for "
    218 				      "PENVSYS_EVENT_STATE_CHANGED", __func__);
    219 			break;
    220 		case PENVSYS_EVENT_CRITICAL:
    221 		default:
    222 			see->see_evsent = 0;
    223 			break;
    224 		}
    225 
    226 		(void)strlcpy(see->see_pes.pes_dvname, sme->sme_name,
    227 		    sizeof(see->see_pes.pes_dvname));
    228 		(void)strlcpy(see->see_pes.pes_sensname, edata->desc,
    229 		    sizeof(see->see_pes.pes_sensname));
    230 	}
    231 
    232 	/*
    233 	 * Limit operation requested.
    234 	 */
    235 #define	LIMIT_OP(k, l, p)						\
    236 	if (props & p) {						\
    237 		objkey = k;						\
    238 		obj = prop_dictionary_get(sdict, objkey);		\
    239 		if (obj != NULL &&					\
    240 		    prop_object_type(obj) != PROP_TYPE_NUMBER) {	\
    241 			DPRINTF(("%s: (%s) %s object no TYPE_NUMBER\n",	\
    242 			    __func__, sme->sme_name, objkey));		\
    243 			error = ENOTSUP;				\
    244 		} else {						\
    245 			edata->limits.l = lims->l;			\
    246 			error = sme_sensor_upint32(sdict, objkey,lims->l); \
    247 			DPRINTF(("%s: (%s) event [sensor=%s type=%d] "	\
    248 			    "(%s updated)\n", __func__, sme->sme_name,	\
    249 			    edata->desc, crittype, objkey));		\
    250 		}							\
    251 		if (error && error != EEXIST)				\
    252 			goto out;					\
    253 		edata->upropset |= p;					\
    254 	}
    255 
    256 	/* Value-based limits */
    257 	LIMIT_OP("critical-max", sel_critmax, PROP_CRITMAX);
    258 	LIMIT_OP("warning-max",  sel_warnmax, PROP_WARNMAX);
    259 	LIMIT_OP("warning-min",  sel_warnmin, PROP_WARNMIN);
    260 	LIMIT_OP("critical-min", sel_critmin, PROP_CRITMIN);
    261 
    262 	/* %Capacity-based limits */
    263 	LIMIT_OP("maximum-capacity",  sel_critmax,  PROP_BATTMAX);
    264 	LIMIT_OP("high-capacity",     sel_warnmax,  PROP_BATTHIGH);
    265 	LIMIT_OP("warning-capacity",  sel_warnmin,  PROP_BATTWARN);
    266 	LIMIT_OP("critical-capacity", sel_critmin,  PROP_BATTCAP);
    267 
    268 #undef LIMIT_OP
    269 
    270 	if (props & PROP_DRIVER_LIMITS)
    271 		edata->upropset |= PROP_DRIVER_LIMITS;
    272 	else
    273 		edata->upropset &= ~PROP_DRIVER_LIMITS;
    274 
    275 	DPRINTF(("%s: (%s) event registered (sensor=%s snum=%d type=%d "
    276 	    "critmin=%" PRIu32 " warnmin=%" PRIu32 " warnmax=%" PRIu32
    277 	    " critmax=%" PRIu32 " props 0x%04x)\n", __func__,
    278 	    see->see_sme->sme_name, see->see_pes.pes_sensname,
    279 	    edata->sensor, see->see_type, edata->limits.sel_critmin,
    280 	    edata->limits.sel_warnmin, edata->limits.sel_warnmax,
    281 	    edata->limits.sel_critmax, edata->upropset));
    282 	/*
    283 	 * Initialize the events framework if it wasn't initialized before.
    284 	 */
    285 	if ((sme->sme_flags & SME_CALLOUT_INITIALIZED) == 0)
    286 		error = sme_events_init(sme);
    287 
    288 	/*
    289 	 * If driver requested notification, advise it of new
    290 	 * limit values
    291 	 */
    292 	if (sme->sme_set_limits)
    293 		(*sme->sme_set_limits)(sme, edata, &(edata->limits),
    294 					&(edata->upropset));
    295 
    296 out:
    297 	if ((error == 0 || error == EEXIST) && osee == NULL)
    298 		LIST_INSERT_HEAD(&sme->sme_events_list, see, see_list);
    299 
    300 	mutex_exit(&sme->sme_mtx);
    301 
    302 	return error;
    303 }
    304 
    305 /*
    306  * sme_event_unregister_all:
    307  *
    308  * 	+ Unregisters all events associated with a sysmon envsys device.
    309  */
    310 void
    311 sme_event_unregister_all(struct sysmon_envsys *sme)
    312 {
    313 	sme_event_t *see;
    314 	int evcounter = 0;
    315 
    316 	KASSERT(sme != NULL);
    317 
    318 	mutex_enter(&sme->sme_mtx);
    319 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    320 		while (see->see_flags & SEE_EVENT_WORKING)
    321 			cv_wait(&sme->sme_condvar, &sme->sme_mtx);
    322 
    323 		if (strcmp(see->see_pes.pes_dvname, sme->sme_name) == 0)
    324 			evcounter++;
    325 	}
    326 
    327 	DPRINTF(("%s: total events %d (%s)\n", __func__,
    328 	    evcounter, sme->sme_name));
    329 
    330 	while ((see = LIST_FIRST(&sme->sme_events_list))) {
    331 		if (evcounter == 0)
    332 			break;
    333 
    334 		if (strcmp(see->see_pes.pes_dvname, sme->sme_name) == 0) {
    335 			LIST_REMOVE(see, see_list);
    336 			DPRINTF(("%s: event %s %d removed (%s)\n", __func__,
    337 			    see->see_pes.pes_sensname, see->see_type,
    338 			    sme->sme_name));
    339 			kmem_free(see, sizeof(*see));
    340 			evcounter--;
    341 		}
    342 	}
    343 
    344 	if (LIST_EMPTY(&sme->sme_events_list))
    345 		if (sme->sme_flags & SME_CALLOUT_INITIALIZED)
    346 			sme_events_destroy(sme);
    347 	mutex_exit(&sme->sme_mtx);
    348 }
    349 
    350 /*
    351  * sme_event_unregister:
    352  *
    353  * 	+ Unregisters an event from the specified sysmon envsys device.
    354  */
    355 int
    356 sme_event_unregister(struct sysmon_envsys *sme, const char *sensor, int type)
    357 {
    358 	sme_event_t *see;
    359 	bool found = false;
    360 
    361 	KASSERT(sensor != NULL);
    362 
    363 	mutex_enter(&sme->sme_mtx);
    364 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    365 		if (strcmp(see->see_pes.pes_sensname, sensor) == 0) {
    366 			if (see->see_type == type) {
    367 				found = true;
    368 				break;
    369 			}
    370 		}
    371 	}
    372 
    373 	if (!found) {
    374 		mutex_exit(&sme->sme_mtx);
    375 		return EINVAL;
    376 	}
    377 
    378 	/*
    379 	 * Wait for the event to finish its work, remove from the list
    380 	 * and release resouces.
    381 	 */
    382 	while (see->see_flags & SEE_EVENT_WORKING)
    383 		cv_wait(&sme->sme_condvar, &sme->sme_mtx);
    384 
    385 	DPRINTF(("%s: removed dev=%s sensor=%s type=%d\n",
    386 	    __func__, see->see_pes.pes_dvname, sensor, type));
    387 	LIST_REMOVE(see, see_list);
    388 	/*
    389 	 * So the events list is empty, we'll do the following:
    390 	 *
    391 	 * 	- stop and destroy the callout.
    392 	 * 	- destroy the workqueue.
    393 	 */
    394 	if (LIST_EMPTY(&sme->sme_events_list))
    395 		sme_events_destroy(sme);
    396 	mutex_exit(&sme->sme_mtx);
    397 
    398 	kmem_free(see, sizeof(*see));
    399 	return 0;
    400 }
    401 
    402 /*
    403  * sme_event_drvadd:
    404  *
    405  * 	+ Registers a new event for a device that had enabled any of
    406  * 	  the monitoring flags in the driver.
    407  */
    408 void
    409 sme_event_drvadd(void *arg)
    410 {
    411 	sme_event_drv_t *sed_t = arg;
    412 	sysmon_envsys_lim_t lims;
    413 	uint32_t props;
    414 	int error = 0;
    415 
    416 	KASSERT(sed_t != NULL);
    417 
    418 #define SEE_REGEVENT(a, b, c)						\
    419 do {									\
    420 	if (sed_t->sed_edata->flags & (a)) {				\
    421 		char str[ENVSYS_DESCLEN] = "monitoring-state-";		\
    422 									\
    423 		error = sme_event_register(sed_t->sed_sdict,		\
    424 				      sed_t->sed_edata,			\
    425 				      sed_t->sed_sme,			\
    426 				      &lims, props,			\
    427 				      (b),				\
    428 				      sed_t->sed_powertype);		\
    429 		if (error && error != EEXIST)				\
    430 			printf("%s: failed to add event! "		\
    431 			    "error=%d sensor=%s event=%s\n",		\
    432 			    __func__, error,				\
    433 			    sed_t->sed_edata->desc, (c));		\
    434 		else {							\
    435 			(void)strlcat(str, (c), sizeof(str));		\
    436 			prop_dictionary_set_bool(sed_t->sed_sdict,	\
    437 						 str,			\
    438 						 true);			\
    439 		}							\
    440 	}								\
    441 } while (/* CONSTCOND */ 0)
    442 
    443 	/*
    444 	 * If driver provides a method to retrieve its internal limit
    445 	 * values, call it and use those returned values as initial
    446 	 * limits for event monitoring.
    447 	 */
    448 	props = 0;
    449 	if (sed_t->sed_edata->flags & ENVSYS_FMONLIMITS)
    450 		if (sed_t->sed_sme->sme_get_limits)
    451 			(*sed_t->sed_sme->sme_get_limits)(sed_t->sed_sme,
    452 							  sed_t->sed_edata,
    453 							  &lims, &props);
    454 	/*
    455 	 * If no values returned, don't create the event monitor at
    456 	 * this time.  We'll get another chance later when the user
    457 	 * provides us with limits.
    458 	 */
    459 	if (props == 0)
    460 		sed_t->sed_edata->flags &= ~ENVSYS_FMONLIMITS;
    461 
    462 	/*
    463 	 * If driver doesn't provide a way to "absorb" user-specified
    464 	 * limit values, we must monitor all limits ourselves
    465 	 */
    466 	else if (sed_t->sed_sme->sme_set_limits == NULL)
    467 		props &= ~PROP_DRIVER_LIMITS;
    468 
    469 	/* Register the events that were specified */
    470 
    471 	SEE_REGEVENT(ENVSYS_FMONCRITICAL,
    472 		     PENVSYS_EVENT_CRITICAL,
    473 		     "critical");
    474 
    475 	SEE_REGEVENT(ENVSYS_FMONSTCHANGED,
    476 		     PENVSYS_EVENT_STATE_CHANGED,
    477 		     "state-changed");
    478 
    479 	SEE_REGEVENT(ENVSYS_FMONLIMITS,
    480 		     PENVSYS_EVENT_LIMITS,
    481 		     "hw-range-limits");
    482 
    483 	/*
    484 	 * we are done, free memory now.
    485 	 */
    486 	kmem_free(sed_t, sizeof(*sed_t));
    487 }
    488 
    489 /*
    490  * sme_events_init:
    491  *
    492  * 	+ Initialize the events framework for this device.
    493  */
    494 int
    495 sme_events_init(struct sysmon_envsys *sme)
    496 {
    497 	int error = 0;
    498 	uint64_t timo;
    499 
    500 	KASSERT(sme != NULL);
    501 	KASSERT(mutex_owned(&sme->sme_mtx));
    502 
    503 	if (sme->sme_events_timeout)
    504 		timo = sme->sme_events_timeout * hz;
    505 	else
    506 		timo = SME_EVTIMO;
    507 
    508 	error = workqueue_create(&sme->sme_wq, sme->sme_name,
    509 	    sme_events_worker, sme, PRI_NONE, IPL_SOFTCLOCK, WQ_MPSAFE);
    510 	if (error)
    511 		return error;
    512 
    513 	mutex_init(&sme->sme_callout_mtx, MUTEX_DEFAULT, IPL_SOFTCLOCK);
    514 	callout_init(&sme->sme_callout, CALLOUT_MPSAFE);
    515 	callout_setfunc(&sme->sme_callout, sme_events_check, sme);
    516 	callout_schedule(&sme->sme_callout, timo);
    517 	sme->sme_flags |= SME_CALLOUT_INITIALIZED;
    518 	DPRINTF(("%s: events framework initialized for '%s'\n",
    519 	    __func__, sme->sme_name));
    520 
    521 	return error;
    522 }
    523 
    524 /*
    525  * sme_events_destroy:
    526  *
    527  * 	+ Destroys the event framework for this device: callout
    528  * 	  stopped, workqueue destroyed and callout mutex destroyed.
    529  */
    530 void
    531 sme_events_destroy(struct sysmon_envsys *sme)
    532 {
    533 	KASSERT(mutex_owned(&sme->sme_mtx));
    534 
    535 	callout_stop(&sme->sme_callout);
    536 	workqueue_destroy(sme->sme_wq);
    537 	mutex_destroy(&sme->sme_callout_mtx);
    538 	callout_destroy(&sme->sme_callout);
    539 	sme->sme_flags &= ~SME_CALLOUT_INITIALIZED;
    540 	DPRINTF(("%s: events framework destroyed for '%s'\n",
    541 	    __func__, sme->sme_name));
    542 }
    543 
    544 /*
    545  * sme_events_check:
    546  *
    547  * 	+ Passes the events to the workqueue thread and stops
    548  * 	  the callout if the 'low-power' condition is triggered.
    549  */
    550 void
    551 sme_events_check(void *arg)
    552 {
    553 	struct sysmon_envsys *sme = arg;
    554 	sme_event_t *see;
    555 	uint64_t timo;
    556 
    557 	KASSERT(sme != NULL);
    558 
    559 	mutex_enter(&sme->sme_callout_mtx);
    560 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    561 		workqueue_enqueue(sme->sme_wq, &see->see_wk, NULL);
    562 		see->see_edata->flags |= ENVSYS_FNEED_REFRESH;
    563 	}
    564 	if (sme->sme_events_timeout)
    565 		timo = sme->sme_events_timeout * hz;
    566 	else
    567 		timo = SME_EVTIMO;
    568 	if (!sysmon_low_power)
    569 		callout_schedule(&sme->sme_callout, timo);
    570 	mutex_exit(&sme->sme_callout_mtx);
    571 }
    572 
    573 /*
    574  * sme_events_worker:
    575  *
    576  * 	+ workqueue thread that checks if there's a critical condition
    577  * 	  and sends an event if it was triggered.
    578  */
    579 void
    580 sme_events_worker(struct work *wk, void *arg)
    581 {
    582 	sme_event_t *see = (void *)wk;
    583 	struct sysmon_envsys *sme = see->see_sme;
    584 	envsys_data_t *edata = see->see_edata;
    585 
    586 	KASSERT(wk == &see->see_wk);
    587 	KASSERT(sme != NULL || edata != NULL);
    588 
    589 	mutex_enter(&sme->sme_mtx);
    590 	see->see_flags |= SEE_EVENT_WORKING;
    591 	/*
    592 	 * sme_events_check marks the sensors to make us refresh them here.
    593 	 * Don't refresh if the driver uses its own method for refreshing.
    594 	 */
    595 	if ((sme->sme_flags & SME_DISABLE_REFRESH) == 0) {
    596 		if ((edata->flags & ENVSYS_FNEED_REFRESH) != 0) {
    597 			/* refresh sensor in device */
    598 			(*sme->sme_refresh)(sme, edata);
    599 			edata->flags &= ~ENVSYS_FNEED_REFRESH;
    600 		}
    601 	}
    602 
    603 	DPRINTFOBJ(("%s: (%s) desc=%s sensor=%d type=%d state=%d units=%d "
    604 	    "value_cur=%d upropset=%d\n", __func__, sme->sme_name, edata->desc,
    605 	    edata->sensor, see->see_type, edata->state, edata->units,
    606 	    edata->value_cur, edata->upropset));
    607 
    608 	/* skip the event if current sensor is in invalid state */
    609 	if (edata->state == ENVSYS_SINVALID)
    610 		goto out;
    611 
    612 	/*
    613 	 * For range limits, if the driver claims responsibility for
    614 	 * limit/range checking, just user driver-supplied status.
    615 	 * Else calculate our own status.  Note that driver must
    616 	 * relinquish responsibility for ALL limits if there is even
    617 	 * one limit that it cannot handle!
    618 	 */
    619 	if ((see->see_type == PENVSYS_EVENT_LIMITS ||
    620 	     see->see_type == PENVSYS_EVENT_CAPACITY) &&
    621 	    (edata->upropset & PROP_DRIVER_LIMITS) == 0) {
    622 		if ((edata->upropset & (PROP_CRITMIN | PROP_BATTCAP)) &&
    623 		    (edata->value_cur < edata->limits.sel_critmin))
    624 			edata->state = ENVSYS_SCRITUNDER;
    625 		else if ((edata->upropset & (PROP_WARNMIN | PROP_BATTWARN)) &&
    626 			 (edata->value_cur < edata->limits.sel_warnmin))
    627 			edata->state = ENVSYS_SWARNUNDER;
    628 		else if ((edata->upropset & (PROP_CRITMAX | PROP_BATTMAX)) &&
    629 			 (edata->value_cur > edata->limits.sel_critmax))
    630 			edata->state = ENVSYS_SCRITOVER;
    631 		else if ((edata->upropset & (PROP_WARNMAX | PROP_BATTHIGH)) &&
    632 			 (edata->value_cur > edata->limits.sel_warnmax))
    633 			edata->state = ENVSYS_SWARNOVER;
    634 		else
    635 			edata->state = ENVSYS_SVALID;
    636 	}
    637 	sme_deliver_event(see);
    638 
    639 out:
    640 	see->see_flags &= ~SEE_EVENT_WORKING;
    641 	cv_broadcast(&sme->sme_condvar);
    642 	mutex_exit(&sme->sme_mtx);
    643 }
    644 
    645 /*
    646  * sysmon_envsys_sensor_event
    647  *
    648  *	+ Find the monitor event of a particular type for a given sensor
    649  *	  on a device and deliver the event if one is required.
    650  */
    651 void
    652 sysmon_envsys_sensor_event(struct sysmon_envsys *sme, envsys_data_t *edata,
    653 			   int ev_type)
    654 {
    655 	sme_event_t *see;
    656 
    657 	mutex_enter(&sme->sme_mtx);
    658 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    659 		if (edata != see->see_edata ||
    660 		    see->see_type != ev_type)
    661 			continue;
    662 		sme_deliver_event(see);
    663 		break;
    664 	}
    665 	mutex_exit(&sme->sme_mtx);
    666 }
    667 
    668 /*
    669  * sme_deliver_event:
    670  *
    671  * 	+ If new sensor state requires it, send an event to powerd
    672  *
    673  *	  Must be called with the device's sysmon mutex held
    674  *		see->see_sme->sme_mtx
    675  */
    676 void
    677 sme_deliver_event(sme_event_t *see)
    678 {
    679 	envsys_data_t *edata = see->see_edata;
    680 	const struct sme_description_table *sdt = NULL;
    681 	const struct sme_sensor_event *sse = sme_sensor_event;
    682 	int i, state = 0;
    683 
    684 	switch (see->see_type) {
    685 	case PENVSYS_EVENT_LIMITS:
    686 	case PENVSYS_EVENT_CAPACITY:
    687 		/*
    688 		 * Send event if state has changed
    689 		 */
    690 		if (edata->state == see->see_evsent)
    691 			break;
    692 
    693 		for (i = 0; sse[i].state != -1; i++)
    694 			if (sse[i].state == edata->state)
    695 				break;
    696 
    697 		if (sse[i].state == -1)
    698 			break;
    699 
    700 		if (edata->state == ENVSYS_SVALID)
    701 			sysmon_penvsys_event(&see->see_pes,
    702 					     PENVSYS_EVENT_NORMAL);
    703 		else
    704 			sysmon_penvsys_event(&see->see_pes, sse[i].event);
    705 
    706 		see->see_evsent = edata->state;
    707 		DPRINTFOBJ(("%s: (%s) desc=%s sensor=%d state=%d send_ev=%d\n",
    708 		    __func__, sme->sme_name, edata->desc, edata->sensor,
    709 		    edata->state,
    710 		    (edata->state == ENVSYS_SVALID) ? PENVSYS_EVENT_NORMAL :
    711 			sse[i].event));
    712 
    713 		break;
    714 
    715 	/*
    716 	 * Send PENVSYS_EVENT_CRITICAL event if:
    717 	 *	State has gone from non-CRITICAL to CRITICAL,
    718 	 *	State remains CRITICAL and value has changed, or
    719 	 *	State has returned from CRITICAL to non-CRITICAL
    720 	 */
    721 	case PENVSYS_EVENT_CRITICAL:
    722 		if (edata->state == ENVSYS_SVALID &&
    723 		    see->see_evsent != 0) {
    724 			sysmon_penvsys_event(&see->see_pes,
    725 					     PENVSYS_EVENT_NORMAL);
    726 			see->see_evsent = 0;
    727 		} else if (edata->state == ENVSYS_SCRITICAL &&
    728 		    see->see_evsent != edata->value_cur) {
    729 			sysmon_penvsys_event(&see->see_pes,
    730 					     PENVSYS_EVENT_CRITICAL);
    731 			see->see_evsent = edata->value_cur;
    732 		}
    733 		break;
    734 
    735 	/*
    736 	 * if value_cur is not normal (battery) or online (drive),
    737 	 * send the event...
    738 	 */
    739 	case PENVSYS_EVENT_STATE_CHANGED:
    740 		/*
    741 		 * the state has not been changed, just ignore the event.
    742 		 */
    743 		if (edata->value_cur == see->see_evsent)
    744 			break;
    745 
    746 		switch (edata->units) {
    747 		case ENVSYS_DRIVE:
    748 			sdt = sme_get_description_table(SME_DESC_DRIVE_STATES);
    749 			state = ENVSYS_DRIVE_ONLINE;
    750 			break;
    751 		case ENVSYS_BATTERY_CAPACITY:
    752 			sdt = sme_get_description_table(
    753 			    SME_DESC_BATTERY_CAPACITY);
    754 			state = ENVSYS_BATTERY_CAPACITY_NORMAL;
    755 			break;
    756 		default:
    757 			panic("%s: bad units for PENVSYS_EVENT_STATE_CHANGED",
    758 			    __func__);
    759 		}
    760 
    761 		for (i = 0; sdt[i].type != -1; i++)
    762 			if (sdt[i].type == edata->value_cur)
    763 				break;
    764 
    765 		if (sdt[i].type == -1)
    766 			break;
    767 
    768 		/*
    769 		 * copy current state description.
    770 		 */
    771 		(void)strlcpy(see->see_pes.pes_statedesc, sdt[i].desc,
    772 		    sizeof(see->see_pes.pes_statedesc));
    773 
    774 		if (edata->value_cur == state)
    775 			/*
    776 			 * state returned to normal condition
    777 			 */
    778 			sysmon_penvsys_event(&see->see_pes,
    779 					     PENVSYS_EVENT_NORMAL);
    780 		else
    781 			/*
    782 			 * state changed to abnormal condition
    783 			 */
    784 			sysmon_penvsys_event(&see->see_pes, see->see_type);
    785 
    786 		see->see_evsent = edata->value_cur;
    787 
    788 		/*
    789 		 * There's no need to continue if it's a drive sensor.
    790 		 */
    791 		if (edata->units == ENVSYS_DRIVE)
    792 			break;
    793 
    794 		/*
    795 		 * Check if the system is running in low power and send the
    796 		 * event to powerd (if running) or shutdown the system
    797 		 * otherwise.
    798 		 */
    799 		if (!sysmon_low_power && sme_event_check_low_power()) {
    800 			struct penvsys_state pes;
    801 
    802 			/*
    803 			 * Stop the callout and send the 'low-power' event.
    804 			 */
    805 			sysmon_low_power = true;
    806 			callout_stop(&see->see_sme->sme_callout);
    807 			pes.pes_type = PENVSYS_TYPE_BATTERY;
    808 			sysmon_penvsys_event(&pes, PENVSYS_EVENT_LOW_POWER);
    809 		}
    810 		break;
    811 	default:
    812 		panic("%s: invalid event type %d", __func__, see->see_type);
    813 	}
    814 }
    815 
    816 /*
    817  * Returns true if the system is in low power state: an AC adapter
    818  * is OFF and all batteries are in LOW/CRITICAL state.
    819  */
    820 static bool
    821 sme_event_check_low_power(void)
    822 {
    823 	if (!sme_acadapter_check())
    824 		return false;
    825 
    826 	return sme_battery_check();
    827 }
    828 
    829 /*
    830  * Called with the sysmon_envsys device mtx held through the
    831  * workqueue thread.
    832  */
    833 static bool
    834 sme_acadapter_check(void)
    835 {
    836 	struct sysmon_envsys *sme;
    837 	envsys_data_t *edata;
    838 	bool dev = false, sensor = false;
    839 
    840 	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
    841 		if (sme->sme_class == SME_CLASS_ACADAPTER) {
    842 			dev = true;
    843 			break;
    844 		}
    845 	}
    846 
    847 	/*
    848 	 * No AC Adapter devices were found.
    849 	 */
    850 	if (!dev)
    851 		return false;
    852 
    853 	/*
    854 	 * Check if there's an AC adapter device connected.
    855 	 */
    856 	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
    857 		if (edata->units == ENVSYS_INDICATOR) {
    858 			sensor = true;
    859 			/* refresh current sensor */
    860 			if ((sme->sme_flags & SME_DISABLE_REFRESH) == 0)
    861 				(*sme->sme_refresh)(sme, edata);
    862 			if (edata->value_cur)
    863 				return false;
    864 		}
    865 	}
    866 
    867 	if (!sensor)
    868 		return false;
    869 
    870 	/*
    871 	 * AC adapter found and not connected.
    872 	 */
    873 	return true;
    874 }
    875 
    876 /*
    877  * Called with the sysmon_envsys device mtx held through the
    878  * workqueue thread.
    879  */
    880 static bool
    881 sme_battery_check(void)
    882 {
    883 	struct sysmon_envsys *sme;
    884 	envsys_data_t *edata;
    885 	int batteriesfound = 0;
    886 	bool present, batterycap, batterycharge;
    887 
    888 	/*
    889 	 * Check for battery devices and its state.
    890 	 */
    891 	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
    892 		if (sme->sme_class != SME_CLASS_BATTERY)
    893 			continue;
    894 
    895 		present = true;
    896 		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
    897 			if (edata->units == ENVSYS_INDICATOR &&
    898 			    !edata->value_cur) {
    899 				present = false;
    900 				break;
    901 			}
    902 		}
    903 		if (!present)
    904 			continue;
    905 		/*
    906 		 * We've found a battery device...
    907 		 */
    908 		batteriesfound++;
    909 		batterycap = batterycharge = false;
    910 		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
    911 			if (edata->units == ENVSYS_BATTERY_CAPACITY) {
    912 				batterycap = true;
    913 				if (!sme_battery_critical(edata))
    914 					return false;
    915 			} else if (edata->units == ENVSYS_BATTERY_CHARGE) {
    916 				batterycharge = true;
    917 				if (edata->value_cur)
    918 					return false;
    919 			}
    920 		}
    921 		if (!batterycap || !batterycharge)
    922 			return false;
    923 	}
    924 
    925 	if (!batteriesfound)
    926 		return false;
    927 
    928 	/*
    929 	 * All batteries in low/critical capacity and discharging.
    930 	 */
    931 	return true;
    932 }
    933 
    934 static bool
    935 sme_battery_critical(envsys_data_t *edata)
    936 {
    937 	if (edata->value_cur == ENVSYS_BATTERY_CAPACITY_CRITICAL ||
    938 	    edata->value_cur == ENVSYS_BATTERY_CAPACITY_LOW)
    939 		return true;
    940 
    941 	return false;
    942 }
    943