Home | History | Annotate | Line # | Download | only in sysmon
sysmon_envsys_events.c revision 1.112
      1 /* $NetBSD: sysmon_envsys_events.c,v 1.112 2014/11/22 15:09:30 ozaki-r 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.112 2014/11/22 15:09:30 ozaki-r 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 static const 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 static const 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 	const 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 it from the list
    413 	 * and release resources.
    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 it from the list
    451 	 * and release resources.
    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 	const 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 	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 	/*
    615 	 * Unset before callout_halt to ensure callout is not scheduled again
    616 	 * during callout_halt.
    617 	 */
    618 	sme->sme_flags &= ~SME_CALLOUT_INITIALIZED;
    619 
    620 	callout_halt(&sme->sme_callout, &sme->sme_mtx);
    621 	callout_destroy(&sme->sme_callout);
    622 
    623 	workqueue_destroy(sme->sme_wq);
    624 	DPRINTF(("%s: events framework destroyed for '%s'\n",
    625 	    __func__, sme->sme_name));
    626 }
    627 
    628 /*
    629  * sysmon_envsys_update_limits
    630  *
    631  *	+ If a driver needs to update the limits that it is providing,
    632  *	  we need to update the dictionary data as well as the limits.
    633  *	  This only makes sense if the driver is capable of providing
    634  *	  its limits, and if there is a limits event-monitor.
    635  */
    636 int
    637 sysmon_envsys_update_limits(struct sysmon_envsys *sme, envsys_data_t *edata)
    638 {
    639 	int err;
    640 
    641 	sysmon_envsys_acquire(sme, false);
    642 	if (sme->sme_get_limits == NULL ||
    643 	    (edata->flags & ENVSYS_FMONLIMITS) == 0)
    644 		err = EINVAL;
    645 	else
    646 		err = sme_update_limits(sme, edata);
    647 	sysmon_envsys_release(sme, false);
    648 
    649 	return err;
    650 }
    651 
    652 /*
    653  * sme_update_limits
    654  *
    655  *	+ Internal version of sysmon_envsys_update_limits() to be used
    656  *	  when the device has already been sysmon_envsys_acquire()d.
    657  */
    658 
    659 int
    660 sme_update_limits(struct sysmon_envsys *sme, envsys_data_t *edata)
    661 {
    662 	prop_dictionary_t sdict = NULL;
    663 	prop_array_t array = NULL;
    664 	sysmon_envsys_lim_t lims;
    665 	sme_event_t *see;
    666 	uint32_t props = 0;
    667 
    668 	/* Find the dictionary for this sensor */
    669 	array = prop_dictionary_get(sme_propd, sme->sme_name);
    670 	if (array == NULL ||
    671 	    prop_object_type(array) != PROP_TYPE_ARRAY) {
    672 		DPRINTF(("%s: array device failed\n", __func__));
    673 		return EINVAL;
    674 	}
    675 
    676 	sdict = prop_array_get(array, edata->sensor);
    677 	if (sdict == NULL) {
    678 		return EINVAL;
    679 	}
    680 
    681 	/* Find the event definition to get its powertype */
    682 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    683 		if (edata == see->see_edata &&
    684 		    see->see_type == PENVSYS_EVENT_LIMITS)
    685 			break;
    686 	}
    687 	if (see == NULL)
    688 		return EINVAL;
    689 
    690 	/* Update limit values from driver if possible */
    691 	if (sme->sme_get_limits != NULL)
    692 		(*sme->sme_get_limits)(sme, edata, &lims, &props);
    693 
    694 	/* Update event and dictionary */
    695 	sme_event_register(sdict, edata, sme, &lims, props,
    696 			   PENVSYS_EVENT_LIMITS, see->see_pes.pes_type);
    697 
    698 	return 0;
    699 }
    700 
    701 /*
    702  * sme_events_check:
    703  *
    704  * 	+ Passes the events to the workqueue thread and stops
    705  * 	  the callout if the 'low-power' condition is triggered.
    706  */
    707 void
    708 sme_events_check(void *arg)
    709 {
    710 	struct sysmon_envsys *sme = arg;
    711 	sme_event_t *see;
    712 
    713 	KASSERT(sme != NULL);
    714 
    715 	mutex_enter(&sme->sme_mtx);
    716 	LIST_FOREACH(see, &sme->sme_events_list, see_list) {
    717 		workqueue_enqueue(sme->sme_wq, &see->see_wk, NULL);
    718 		see->see_edata->flags |= ENVSYS_FNEED_REFRESH;
    719 	}
    720 	if (!sysmon_low_power)
    721 		sme_schedule_callout(sme);
    722 	mutex_exit(&sme->sme_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 
   1034 			if (edata->value_cur)
   1035 				return false;
   1036 		}
   1037 	}
   1038 
   1039 	if (!sensor)
   1040 		return false;
   1041 
   1042 	/*
   1043 	 * AC adapter found and not connected.
   1044 	 */
   1045 	return true;
   1046 }
   1047 
   1048 /*
   1049  * Called with the sysmon_envsys device mtx held through the
   1050  * workqueue thread.
   1051  */
   1052 static bool
   1053 sme_battery_check(void)
   1054 {
   1055 	struct sysmon_envsys *sme;
   1056 	envsys_data_t *edata;
   1057 	int batteriesfound = 0;
   1058 	bool present, batterycap, batterycharge;
   1059 
   1060 	/*
   1061 	 * Check for battery devices and its state.
   1062 	 */
   1063 	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
   1064 		if (sme->sme_class != SME_CLASS_BATTERY)
   1065 			continue;
   1066 
   1067 		present = true;
   1068 
   1069 		/*
   1070 		 * XXX
   1071 		 * this assumes that the first valid ENVSYS_INDICATOR is the
   1072 		 * presence indicator
   1073 		 */
   1074 		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
   1075 			if ((edata->units == ENVSYS_INDICATOR) &&
   1076 			    (edata->state == ENVSYS_SVALID)) {
   1077 				present = edata->value_cur;
   1078 				break;
   1079 			}
   1080 		}
   1081 		if (!present)
   1082 			continue;
   1083 		/*
   1084 		 * We've found a battery device...
   1085 		 */
   1086 		batteriesfound++;
   1087 		batterycap = batterycharge = false;
   1088 		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
   1089 			/* no need to even look at sensors that aren't valid */
   1090 			if (edata->state != ENVSYS_SVALID)
   1091 				continue;
   1092 			if (edata->units == ENVSYS_BATTERY_CAPACITY) {
   1093 				batterycap = true;
   1094 				if (!sme_battery_critical(edata))
   1095 					return false;
   1096 			} else if (edata->units == ENVSYS_BATTERY_CHARGE) {
   1097 				batterycharge = true;
   1098 				if (edata->value_cur)
   1099 					return false;
   1100 			}
   1101 		}
   1102 		if (!batterycap || !batterycharge)
   1103 			return false;
   1104 	}
   1105 
   1106 	if (!batteriesfound)
   1107 		return false;
   1108 
   1109 	/*
   1110 	 * All batteries in low/critical capacity and discharging.
   1111 	 */
   1112 	return true;
   1113 }
   1114 
   1115 static bool
   1116 sme_battery_critical(envsys_data_t *edata)
   1117 {
   1118 	if (edata->value_cur == ENVSYS_BATTERY_CAPACITY_CRITICAL ||
   1119 	    edata->value_cur == ENVSYS_BATTERY_CAPACITY_LOW)
   1120 		return true;
   1121 
   1122 	return false;
   1123 }
   1124