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