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