xref: /illumos-gate/usr/src/uts/common/os/ksensor.c (revision ac2250cb76bb32944fd2c8a3ba2cd3f79747748d)
1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright 2026 Oxide Computer Company
14  */
15 
16 /*
17  * Kernel Sensor Framework
18  *
19  * The kernel sensor framework exists to provide a simple and straightforward
20  * means for various parts of the system to declare and instantiate sensor
21  * information. Between this and the ksensor character device
22  * (uts/common/io/ksensor/ksensor_drv.c) this exposes per-device sensors and
23  * character devices.
24  *
25  * --------------------------
26  * Driver and User Interfaces
27  * --------------------------
28  *
29  * Each sensor that is registered with the framework is exposed as a character
30  * device under /dev/sensors. The device class and node name are often ':'
31  * delineated and must begin with 'ddi_sensor'. Everything after 'ddi_sensor'
32  * will be created in a directory under /dev/sensors. So for example the Intel
33  * PCH driver uses a class "ddi_sensor:temperature:pch" and a node name of
34  * 'ts.%d'. This creates the node /dev/sensors/temperature/pch/ts.0. The
35  * devfsadm plugin automatically handles the creation of directories which makes
36  * the addition of additional sensor types easy to create.
37  *
38  * Strictly speaking, any device can manage their own sensors and minor nodes by
39  * using the appropriate class and implementing the corresponding ioctls. That
40  * was how the first kernel sensors were written; however, there are a lot of
41  * issues with that which led to this:
42  *
43  * 1. Every driver had to actually implement character devices.
44  *
45  * 2. Every driver had to duplicate a lot of the logic around open(9E),
46  *    close(9E), and ioctl(9E).
47  *
48  * 3. Drivers that tied into frameworks like mac(9E) or SCSAv3 needed a lot more
49  *    work to fit into this model. For example, because the minor state is
50  *    shared between all the instances and the frameworks, they would have
51  *    required shared, global state that they don't have today.
52  *
53  * Ultimately, having an operations vector and a callback argument makes work a
54  * lot simpler for the producers of sensor data and that simplicity makes it
55  * worthwhile to take on additional effort and work here.
56  *
57  * ----------
58  * Components
59  * ----------
60  *
61  * The ksensor framework is made of a couple of different pieces:
62  *
63  * 1. This glue that is a part of genunix.
64  * 2. The ksensor character device driver.
65  * 3. Sensor providers, which are generally drivers that register with the
66  *    ksensor framework.
67  *
68  * The implementation of (1) is all in this file. The implementation of (2) is
69  * in uts/common/io/ksensor/ksensor_drv.c. The implementation of (3) is found in
70  * all of the different leaf devices. Examples of (3) include pchtemp(4D) and
71  * igb(4D).
72  *
73  * We separate numbers one and two into two different components for a few
74  * reasons. The most important thing is that drivers that provide sensors should
75  * not be dependent on some other part of the system having been loaded. This
76  * makes a compelling argument for it being a part of the core kernel. However,
77  * like other subsystems (e.g. kstats, smbios, etc.), it's useful to separate
78  * out the thing that provides the interface to users with the thing that is
79  * used to glue together providers in the kernel. There's the added benefit that
80  * it's practically simpler to spin up a pseudo-device through a module.
81  *
82  * The ksensor character device driver (2) registers with the main genunix
83  * ksensor code (1) when it attaches and when it detaches. The kernel only
84  * allows a single driver to be attached to it. When that character device
85  * driver attaches, the ksensor framework will walk through all of the currently
86  * registered sensors and inform the character device driver of the nodes that
87  * it needs to create. While the character device driver is attached, the
88  * ksensor framework will also call back into it when a sensor needs to be
89  * removed.
90  *
91  * Generally speaking, this distinction of responsibilities allows the kernel
92  * sensor character device driver to attach and detach without impact to the
93  * sensor providers or them even being notified at all, it's all transparent to
94  * them.
95  *
96  * ------------------------------
97  * Sensor Lifetime and detach(9E)
98  * ------------------------------
99  *
100  * Traditionally, a device driver may be detached by the broader kernel whenever
101  * the kernel desires it. On debug builds this happens by a dedicated thread. On
102  * a non-debug build this may happen due to memory pressure or as an attempt to
103  * reclaim idle resources (though this is much less common). However, when the
104  * module is detached, the system remembers that minor nodes previously existed
105  * and that entries in /devices had been created. When something proceeds to
106  * access an entry in /devices again, the system will use that to bring a driver
107  * back to life. It doesn't matter whether it's a pseudo-device driver or
108  * something else, this can happen.
109  *
110  * One downside to the sensor framework, is that we need to emulate this
111  * behavior which leads to some amount of complexity here. But this is a
112  * worthwhile tradeoff as it makes things much simpler for providers and it's
113  * not too hard for us to emulate this behavior.
114  *
115  * When a sensor provider registers the sensor, the sensor becomes available to
116  * the system. When the sensor provider unregisters with the system, which
117  * happens during its detach routine, then we note that it has been detached;
118  * however, we don't delete its minor node and if something accesses it, we
119  * attempt to load the driver again, the same way that devfs (the file system
120  * behind /devices) does.
121  *
122  * For each dev_info_t that registers a sensor we register a callback such that
123  * when the device is removed, e.g. someone called rem_drv or physically pulls
124  * the device, then we'll be able to finally clean up the device. This lifetime
125  * can be represented in the following image:
126  *
127  *         |
128  *         |
129  *         +-----<-------------------------------------+
130  *         |                                           |
131  *         | . . call ksensor_create()                 |
132  *         v                                           |
133  *     +-------+                                       |
134  *     | Valid |                                       |
135  *     +-------+                                       |
136  *         |                                           ^
137  *         | . . call ksensor_remove()                 |
138  *         v                                           |
139  *    +---------+                                      |
140  *    | Invalid |                                      |
141  *    +---------+                                      |
142  *      |     |                                        |
143  *      |     | . . user uses sensor again             |
144  *      |     |                                        |
145  *      |     +-------------------+                    |
146  *      |                         |                    |
147  *      |                         v                    |
148  *      |                 +---------------+            |
149  *      |                 | Attatching... |-->---------+
150  *      |                 +---------------+
151  *      | . . ddi unbind cb       |
152  *      |                         |
153  *      v                         | . . attatch fails or
154  *   +---------+                  |     no call to ksensor_create()
155  *   | Deleted |--<---------------+     again
156  *   +---------+
157  *
158  * When the DDI unbind callback is called, we know that the device is going to
159  * be removed. However, this happens within a subtle context with a majority of
160  * the device tree held (at least the dip's parent). In particular, another
161  * thread may be trying to obtain a hold on it and be blocked in
162  * ndi_devi_enter(). As the callback thread holds that, that could lead to a
163  * deadlock. As a result, we clean things up in two phases. One during the
164  * synchronous callback and the other via a taskq. In the first phase we
165  * logically do the following:
166  *
167  *  o Remove the dip from the list of ksensor dips and set the flag that
168  *    indicates that it's been removed. Once we get this callback we must no
169  *    longer trust the actual dip that is present in it. We leave ksdip_dip set
170  *    to its old address for debugging purposes.
171  *  o Remove all of the sensors from the global avl to make sure that new
172  *    threads cannot look it up.
173  *  o Add the dip to list of dead ksensor dips so that way any sensors that
174  *    remain on it can be denotified if we end up in a race condition and the
175  *    registered ksensor is removed prior to us cleaning it up. If we did not do
176  *    this, the minor node would outlast the ksensor_t, which is not our intent.
177  *    The ksensor_t should always outlive the minor.
178  *
179  * Then, after the taskq is dispatched, we do the following in taskq context:
180  *
181  *  o Tell the ksensor driver that it should remove the minor node.
182  *  o Block on each sensor until it is no-longer busy and then clean it up.
183  *  o Clean up the ksensor_dip_t.
184  *
185  * ------------------
186  * Accessing a Sensor
187  * ------------------
188  *
189  * Sensors are intended to be accessed through the traditional character
190  * operations: open(9E), close(9E), and ioctl(9E). Providers assume that only a
191  * single callback for a given sensor will be called at once. For example, if
192  * two threads have the same temperature sensor and are both issuing an ioctl
193  * for the current temperature, the provider will only get one call at a time.
194  * However, providers with multiple sensors cannot assume any relationship
195  * between their sensors.
196  *
197  * Because we may have to reattach a driver to access a sensor, the broader
198  * access logic is split into two different parts:
199  *
200  * 1. Calling open(9E) and therefore ksensor_op_open() is the main thing that
201  *    causes us to go through and verify that the sensor is still valid and that
202  *    the provider is attached. Between an open() and close() there will always
203  *    be a hold on the driver, just like happens normally for a character device
204  *    driver.
205  *
206  *    Only one caller to open(9E) of a particular sensor is allowed to be doing
207  *    this at a time. This is managed by the KSENSOR_F_META_WORK flag. To obtain
208  *    a hold on a sensor, the following logical steps are required. See
209  *    ksensor_op_open() for the implementation:
210  *
211  *    1. Map the minor to the ksensor_t via the avl tree.
212  *    2. Check that the ksensor's dip is valid.
213  *    3. If the sensor is already performing meta work, wait until it is no
214  *       longer so, and restart from the top. Otherwise, mark that it is now
215  *       doing so.
216  *    4. Enter the parent and place a hold on the sensor provider's dip.
217  *    5. Once again check if the dip is removed or not because we have to drop
218  *       locks during that operation.
219  *    6. Check if the ksensor has the valid flag set. If not, attempt to
220  *       configure the dip.
221  *    7. Assuming the sensor is now valid, the sensor is now usable.
222  *
223  *    When subsequent open(9E) calls are made and they see that both the
224  *    KSENSOR_F_VALID and KSENSOR_F_HELD flags are set, then all of this can be
225  *    bypassed.
226  *
227  *    The KSENSOR_F_HELD flag will remain until someone calls close(9E) occurs.
228  *    This will cause KSENSOR_F_HELD to be removed and remove the NDI hold on
229  *    the underlying provider. Only at this point will any other detach activity
230  *    on the provider be allowed to continue.
231  *
232  * 2. When the other operations are called, e.g. ksensor_op_kind() and
233  *    ksensor_op_scalar(), then we provide the actual per-operation
234  *    serialization. Because the ksensor has been opened, we don't have to worry
235  *    about the complex dance we did in step (1). Effectively we manage this
236  *    with a flag, KSENSOR_F_OP, and a cv, ksensor_op_cv. The use of the flag
237  *    and cv allows a user to interrupt the operation with a signal if required.
238  *    The general logic for this is taken care of by ksensor_op_acquire() and
239  *    ksensor_op_release().
240  *
241  * -----------------------------
242  * Character Device Registration
243  * -----------------------------
244  *
245  * The 'ksensor' character device driver can come and go. To support this, the
246  * ksensor framework communicates with the ksensor character device by a
247  * well-defined set of callbacks, used to indicate sensor addition and removal.
248  * The ksensor character device is found in uts/common/io/ksensor/ksensor_drv.c.
249  * The ksensor character device is responsible for creating and destroying minor
250  * nodes.
251  *
252  * Each ksensor_t has a flag, KSENSOR_F_NOTIFIED, that is used to indicate
253  * whether or not the registered driver has been notified of the sensor. When a
254  * callback is first registered, we'll walk through the entire list of nodes to
255  * make sure that its minor has been created. When unregistering, the minor node
256  * remove callback will not be called; however, this can generally by dealt with
257  * by calling something like ddi_remove_minor_node(dip, NULL).
258  *
259  * -------
260  * Locking
261  * -------
262  *
263  * The following rules apply to dealing with lock ordering:
264  *
265  * 1. The global ksensor_g_mutex protects all global data and must be taken
266  *    before a ksensor_t's individual mutex.
267  *
268  * 2. A thread should not hold any two ksensor_t's mutex at any time.
269  *
270  * 3. No locks should be held when attempting to grab or manipulate a
271  *    dev_info_t, e.g. ndi_devi_enter().
272  *
273  * 4. Unless the ksensor is actively being held, whenever a ksensor is found,
274  *    one must check whether the ksensor_dip_t flag KSENSOR_DIP_F_REMOVED is
275  *    set or not and whether the ksensor_t's KSENSOR_F_VALID flag is set.
276  */
277 
278 #include <sys/types.h>
279 #include <sys/file.h>
280 #include <sys/errno.h>
281 #include <sys/cred.h>
282 #include <sys/ddi.h>
283 #include <sys/stat.h>
284 #include <sys/sunddi.h>
285 #include <sys/sunndi.h>
286 #include <sys/esunddi.h>
287 #include <sys/ksensor_impl.h>
288 #include <sys/ddi_impldefs.h>
289 #include <sys/pci.h>
290 #include <sys/avl.h>
291 #include <sys/list.h>
292 #include <sys/stddef.h>
293 #include <sys/sysmacros.h>
294 #include <sys/fs/dv_node.h>
295 
296 typedef enum {
297 	/*
298 	 * This flag indicates that the subscribing ksensor character device has
299 	 * been notified about this flag.
300 	 */
301 	KSENSOR_F_NOTIFIED	= 1 << 0,
302 	/*
303 	 * This indicates that the sensor is currently valid, meaning that the
304 	 * ops vector and argument are safe to use. This is removed when a
305 	 * driver with a sensor is detached.
306 	 */
307 	KSENSOR_F_VALID		= 1 << 1,
308 	/*
309 	 * This flag is used to synchronize the act of holding and/or
310 	 * potentially attaching a given sensor. There can only be one of these
311 	 * active at a time for a sensor. While multiple sensor can share the
312 	 * same underlying ksensor_dip_t which is what we try to attach, it's
313 	 * ultimately simpler for us to track this and the hold on a per-sensor
314 	 * basis.
315 	 */
316 	KSENSOR_F_META_WORK	= 1 << 2,
317 	/*
318 	 * Indicates that an NDI hold is present on the dip from this sensor.
319 	 */
320 	KSENSOR_F_HELD		= 1 << 3,
321 	/*
322 	 * Indicates that an active op is going on.
323 	 */
324 	KSENSOR_F_OP		= 1 << 4
325 } ksensor_flags_t;
326 
327 typedef enum {
328 	/*
329 	 * Indicates that the dip this references has been removed from the
330 	 * system and we have been notified through its unbind callback.
331 	 */
332 	KSENSOR_DIP_F_REMOVED	= 1 << 0
333 } ksensor_dip_flags_t;
334 
335 typedef struct {
336 	list_node_t ksdip_link;
337 	ksensor_dip_flags_t ksdip_flags;
338 	dev_info_t *ksdip_dip;
339 	ddi_unbind_callback_t ksdip_cb;
340 	list_t ksdip_sensors;
341 } ksensor_dip_t;
342 
343 typedef struct {
344 	kmutex_t ksensor_mutex;
345 	kcondvar_t ksensor_meta_cv;
346 	kcondvar_t ksensor_op_cv;
347 	uintptr_t ksensor_op_thr;
348 	ksensor_flags_t ksensor_flags;
349 	list_node_t ksensor_dip_list;
350 	avl_node_t ksensor_id_avl;
351 	uint_t ksensor_nwaiters;
352 	ksensor_dip_t *ksensor_ksdip;
353 	char *ksensor_name;
354 	char *ksensor_class;
355 	id_t ksensor_id;
356 	const ksensor_ops_t *ksensor_ops;
357 	void *ksensor_arg;
358 } ksensor_t;
359 
360 static kmutex_t ksensor_g_mutex;
361 static id_space_t *ksensor_ids;
362 static list_t ksensor_dips;
363 static list_t ksensor_dead_dips;
364 static avl_tree_t ksensor_avl;
365 static dev_info_t *ksensor_cb_dip;
366 static ksensor_create_f ksensor_cb_create;
367 static ksensor_remove_f ksensor_cb_remove;
368 
369 static int
370 ksensor_avl_compare(const void *l, const void *r)
371 {
372 	const ksensor_t *kl = l;
373 	const ksensor_t *kr = r;
374 
375 	if (kl->ksensor_id > kr->ksensor_id) {
376 		return (1);
377 	} else if (kl->ksensor_id < kr->ksensor_id) {
378 		return (-1);
379 	} else {
380 		return (0);
381 	}
382 }
383 
384 static ksensor_t *
385 ksensor_find_by_id(id_t id)
386 {
387 	ksensor_t k, *ret;
388 
389 	ASSERT(MUTEX_HELD(&ksensor_g_mutex));
390 
391 	k.ksensor_id = id;
392 	return (avl_find(&ksensor_avl, &k, NULL));
393 
394 }
395 
396 static ksensor_t *
397 ksensor_search_ksdip(ksensor_dip_t *ksdip, const char *name, const char *class)
398 {
399 	ksensor_t *s;
400 
401 	ASSERT(MUTEX_HELD(&ksensor_g_mutex));
402 
403 	for (s = list_head(&ksdip->ksdip_sensors); s != NULL;
404 	    s = list_next(&ksdip->ksdip_sensors, s)) {
405 		if (strcmp(s->ksensor_name, name) == 0 &&
406 		    strcmp(s->ksensor_class, class) == 0) {
407 			return (s);
408 		}
409 	}
410 
411 	return (NULL);
412 }
413 
414 static void
415 ksensor_free_sensor(ksensor_t *sensor)
416 {
417 	strfree(sensor->ksensor_name);
418 	strfree(sensor->ksensor_class);
419 	id_free(ksensor_ids, sensor->ksensor_id);
420 	cv_destroy(&sensor->ksensor_op_cv);
421 	cv_destroy(&sensor->ksensor_meta_cv);
422 	mutex_destroy(&sensor->ksensor_mutex);
423 	kmem_free(sensor, sizeof (ksensor_t));
424 }
425 
426 static void
427 ksensor_free_dip(ksensor_dip_t *ksdip)
428 {
429 	list_destroy(&ksdip->ksdip_sensors);
430 	kmem_free(ksdip, sizeof (ksensor_dip_t));
431 }
432 
433 static void
434 ksensor_denotify(ksensor_t *sensor)
435 {
436 	mutex_enter(&sensor->ksensor_mutex);
437 	if ((sensor->ksensor_flags & KSENSOR_F_NOTIFIED) != 0) {
438 		VERIFY3P(ksensor_cb_remove, !=, NULL);
439 		ksensor_cb_remove(sensor->ksensor_id, sensor->ksensor_name);
440 		sensor->ksensor_flags &= ~KSENSOR_F_NOTIFIED;
441 	}
442 	mutex_exit(&sensor->ksensor_mutex);
443 }
444 
445 static void
446 ksensor_dip_unbind_taskq(void *arg)
447 {
448 	ksensor_dip_t *k = arg;
449 	ksensor_t *sensor;
450 
451 	/*
452 	 * First notify an attached driver that the nodes are going away
453 	 * before we block and wait on them. Now that this is done, it's safe to
454 	 * remove it from the dead list.
455 	 */
456 	mutex_enter(&ksensor_g_mutex);
457 	for (sensor = list_head(&k->ksdip_sensors); sensor != NULL;
458 	    sensor = list_next(&k->ksdip_sensors, sensor)) {
459 		ksensor_denotify(sensor);
460 	}
461 	list_remove(&ksensor_dead_dips, k);
462 	mutex_exit(&ksensor_g_mutex);
463 
464 	/*
465 	 * Now that the driver has destroyed its minor, wait for anything that's
466 	 * still there.
467 	 */
468 	while ((sensor = list_remove_head(&k->ksdip_sensors)) != NULL) {
469 		mutex_enter(&sensor->ksensor_mutex);
470 		while ((sensor->ksensor_flags & KSENSOR_F_META_WORK) != 0 ||
471 		    sensor->ksensor_nwaiters > 0) {
472 			cv_wait(&sensor->ksensor_meta_cv,
473 			    &sensor->ksensor_mutex);
474 		}
475 		mutex_exit(&sensor->ksensor_mutex);
476 		ksensor_free_sensor(sensor);
477 	}
478 	ksensor_free_dip(k);
479 }
480 
481 static void
482 ksensor_dip_unbind_cb(void *arg, dev_info_t *dip)
483 {
484 	ksensor_dip_t *k = arg;
485 	ksensor_t *sensor;
486 
487 	/*
488 	 * Remove the dip and the associated sensors from global visibility.
489 	 * This will ensure that no new clients can find this; however, others
490 	 * may have extent attempts to grab it (but lost the race in an NDI
491 	 * hold).
492 	 */
493 	mutex_enter(&ksensor_g_mutex);
494 	list_remove(&ksensor_dips, k);
495 	list_insert_head(&ksensor_dead_dips, k);
496 	k->ksdip_flags |= KSENSOR_DIP_F_REMOVED;
497 	for (sensor = list_head(&k->ksdip_sensors); sensor != NULL;
498 	    sensor = list_next(&k->ksdip_sensors, sensor)) {
499 		avl_remove(&ksensor_avl, sensor);
500 	}
501 	mutex_exit(&ksensor_g_mutex);
502 
503 	(void) taskq_dispatch(system_taskq, ksensor_dip_unbind_taskq, k,
504 	    TQ_SLEEP);
505 }
506 
507 static ksensor_dip_t *
508 ksensor_dip_create(dev_info_t *dip)
509 {
510 	ksensor_dip_t *k;
511 
512 	k = kmem_zalloc(sizeof (ksensor_dip_t), KM_SLEEP);
513 	k->ksdip_dip = dip;
514 	k->ksdip_cb.ddiub_cb = ksensor_dip_unbind_cb;
515 	k->ksdip_cb.ddiub_arg = k;
516 	list_create(&k->ksdip_sensors, sizeof (ksensor_t),
517 	    offsetof(ksensor_t, ksensor_dip_list));
518 	e_ddi_register_unbind_callback(dip, &k->ksdip_cb);
519 
520 	return (k);
521 }
522 
523 static ksensor_dip_t *
524 ksensor_dip_find(dev_info_t *dip)
525 {
526 	ksensor_dip_t *k;
527 
528 	ASSERT(MUTEX_HELD(&ksensor_g_mutex));
529 	for (k = list_head(&ksensor_dips); k != NULL;
530 	    k = list_next(&ksensor_dips, k)) {
531 		if (dip == k->ksdip_dip) {
532 			return (k);
533 		}
534 	}
535 
536 	return (NULL);
537 }
538 
539 int
540 ksensor_create(dev_info_t *dip, const ksensor_ops_t *ops, void *arg,
541     const char *name, const char *class, id_t *idp)
542 {
543 	ksensor_dip_t *ksdip;
544 	ksensor_t *sensor;
545 
546 	if (dip == NULL || ops == NULL || name == NULL || class == NULL ||
547 	    idp == NULL) {
548 		return (EINVAL);
549 	}
550 
551 	if (!DEVI_IS_ATTACHING(dip)) {
552 		return (EAGAIN);
553 	}
554 
555 	mutex_enter(&ksensor_g_mutex);
556 	ksdip = ksensor_dip_find(dip);
557 	if (ksdip == NULL) {
558 		ksdip = ksensor_dip_create(dip);
559 		list_insert_tail(&ksensor_dips, ksdip);
560 	}
561 
562 	sensor = ksensor_search_ksdip(ksdip, name, class);
563 	if (sensor != NULL) {
564 		ASSERT3P(sensor->ksensor_ksdip, ==, ksdip);
565 		if ((sensor->ksensor_flags & KSENSOR_F_VALID) != 0) {
566 			mutex_exit(&ksensor_g_mutex);
567 			dev_err(dip, CE_WARN, "tried to create sensor %s:%s "
568 			    "which is currently active", class, name);
569 			return (EEXIST);
570 		}
571 
572 		sensor->ksensor_ops = ops;
573 		sensor->ksensor_arg = arg;
574 	} else {
575 		sensor = kmem_zalloc(sizeof (ksensor_t), KM_SLEEP);
576 		mutex_init(&sensor->ksensor_mutex, NULL, MUTEX_DRIVER, NULL);
577 		cv_init(&sensor->ksensor_meta_cv, NULL, CV_DRIVER, NULL);
578 		cv_init(&sensor->ksensor_op_cv, NULL, CV_DRIVER, NULL);
579 		sensor->ksensor_ksdip = ksdip;
580 		sensor->ksensor_name = ddi_strdup(name, KM_SLEEP);
581 		sensor->ksensor_class = ddi_strdup(class, KM_SLEEP);
582 		sensor->ksensor_id = id_alloc(ksensor_ids);
583 		sensor->ksensor_ops = ops;
584 		sensor->ksensor_arg = arg;
585 		list_insert_tail(&ksdip->ksdip_sensors, sensor);
586 		avl_add(&ksensor_avl, sensor);
587 	}
588 
589 	sensor->ksensor_flags |= KSENSOR_F_VALID;
590 
591 	if ((sensor->ksensor_flags & KSENSOR_F_NOTIFIED) == 0 &&
592 	    ksensor_cb_create != NULL)  {
593 		if (ksensor_cb_create(sensor->ksensor_id, sensor->ksensor_class,
594 		    sensor->ksensor_name) == 0) {
595 			sensor->ksensor_flags |= KSENSOR_F_NOTIFIED;
596 		}
597 	}
598 
599 	*idp = sensor->ksensor_id;
600 	mutex_exit(&ksensor_g_mutex);
601 
602 	return (0);
603 }
604 
605 int
606 ksensor_create_scalar_pcidev(dev_info_t *dip, uint64_t kind,
607     const ksensor_ops_t *ops, void *arg, const char *name, id_t *idp)
608 {
609 	char *pci_name, *type;
610 	const char *class;
611 	int *regs, ret;
612 	uint_t nregs;
613 	uint16_t bus, dev;
614 
615 	switch (kind) {
616 	case SENSOR_KIND_TEMPERATURE:
617 		class = "ddi_sensor:temperature:pci";
618 		break;
619 	case SENSOR_KIND_VOLTAGE:
620 		class = "ddi_sensor:voltage:pci";
621 		break;
622 	case SENSOR_KIND_CURRENT:
623 		class = "ddi_sensor:current:pci";
624 		break;
625 	default:
626 		return (ENOTSUP);
627 	}
628 
629 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, dip, 0, "device_type",
630 	    &type) != DDI_PROP_SUCCESS) {
631 		return (EINVAL);
632 	}
633 
634 	if (strcmp(type, "pciex") != 0 && strcmp(type, "pci") != 0) {
635 		ddi_prop_free(type);
636 		return (EINVAL);
637 	}
638 	ddi_prop_free(type);
639 
640 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dip, 0, "reg",
641 	    &regs, &nregs) != DDI_PROP_SUCCESS) {
642 		return (EINVAL);
643 	}
644 
645 	if (nregs < 1) {
646 		ddi_prop_free(regs);
647 		return (EIO);
648 	}
649 
650 	bus = PCI_REG_BUS_G(regs[0]);
651 	dev = PCI_REG_DEV_G(regs[0]);
652 	ddi_prop_free(regs);
653 
654 	pci_name = kmem_asprintf("%x.%x:%s", bus, dev, name);
655 
656 	ret = ksensor_create(dip, ops, arg, pci_name, class, idp);
657 	strfree(pci_name);
658 	return (ret);
659 }
660 
661 /*
662  * When a driver removes a sensor, we basically mark it as invalid. This happens
663  * because drivers can detach and we will need to reattach them when the sensor
664  * is used again.
665  */
666 int
667 ksensor_remove(dev_info_t *dip, id_t id)
668 {
669 	ksensor_dip_t *kdip;
670 	ksensor_t *sensor;
671 
672 	if (!DEVI_IS_ATTACHING(dip) && !DEVI_IS_DETACHING(dip)) {
673 		return (EAGAIN);
674 	}
675 
676 	mutex_enter(&ksensor_g_mutex);
677 	kdip = ksensor_dip_find(dip);
678 	if (kdip == NULL) {
679 		mutex_exit(&ksensor_g_mutex);
680 		return (ENOENT);
681 	}
682 
683 	for (sensor = list_head(&kdip->ksdip_sensors); sensor != NULL;
684 	    sensor = list_next(&kdip->ksdip_sensors, sensor)) {
685 		if (sensor->ksensor_id == id || id == KSENSOR_ALL_IDS) {
686 			mutex_enter(&sensor->ksensor_mutex);
687 			sensor->ksensor_flags &= ~KSENSOR_F_VALID;
688 			sensor->ksensor_ops = NULL;
689 			sensor->ksensor_arg = NULL;
690 			mutex_exit(&sensor->ksensor_mutex);
691 		}
692 	}
693 	mutex_exit(&ksensor_g_mutex);
694 	return (0);
695 }
696 
697 static void
698 ksensor_release_meta(ksensor_t *sensor)
699 {
700 	mutex_enter(&sensor->ksensor_mutex);
701 	VERIFY(sensor->ksensor_flags & KSENSOR_F_META_WORK);
702 	sensor->ksensor_flags &= ~KSENSOR_F_META_WORK;
703 	cv_broadcast(&sensor->ksensor_meta_cv);
704 	mutex_exit(&sensor->ksensor_mutex);
705 }
706 
707 static void
708 ksensor_release(ksensor_t *sensor)
709 {
710 	dev_info_t *pdip;
711 
712 	ddi_release_devi(sensor->ksensor_ksdip->ksdip_dip);
713 
714 	mutex_enter(&sensor->ksensor_mutex);
715 	VERIFY(sensor->ksensor_flags & KSENSOR_F_HELD);
716 	sensor->ksensor_flags &= ~KSENSOR_F_HELD;
717 	mutex_exit(&sensor->ksensor_mutex);
718 }
719 
720 int
721 ksensor_op_open(id_t id)
722 {
723 restart:
724 	mutex_enter(&ksensor_g_mutex);
725 	ksensor_t *sensor = ksensor_find_by_id(id);
726 
727 	/*
728 	 * If this ID doesn't exist or the dip has been removed on this, then
729 	 * this there is nothing else we can do.
730 	 */
731 	if (sensor == NULL) {
732 		mutex_exit(&ksensor_g_mutex);
733 		return (ESTALE);
734 	}
735 
736 	if ((sensor->ksensor_ksdip->ksdip_flags & KSENSOR_DIP_F_REMOVED) != 0) {
737 		mutex_exit(&ksensor_g_mutex);
738 		return (ESTALE);
739 	}
740 
741 	/*
742 	 * If the ksensor is considered valid and there's an existing hold on
743 	 * it, then that means this ksensor is guaranteeing that its dip will
744 	 * not disappear. We don't need to track the reference count on this
745 	 * minor as the kernel is kindly going that for us.
746 	 */
747 	mutex_enter(&sensor->ksensor_mutex);
748 	if ((sensor->ksensor_flags & (KSENSOR_F_VALID | KSENSOR_F_HELD)) ==
749 	    (KSENSOR_F_VALID | KSENSOR_F_HELD)) {
750 		mutex_exit(&sensor->ksensor_mutex);
751 		mutex_exit(&ksensor_g_mutex);
752 		return (0);
753 	}
754 
755 	/*
756 	 * At this point, the ksensor is either not valid or not held. While the
757 	 * kernel guarantees open(9E) and close(9E) exclusion, it does not
758 	 * guarantee that only one open(9E) is going on at a time. We need to
759 	 * ensure that only one entity is acting on the ksensor at any given
760 	 * time. Note, while doing this we drop all the locks. If we have to do
761 	 * this, then we will end up restarting the entire loop due to dropping
762 	 * the global lock.
763 	 */
764 	if ((sensor->ksensor_flags & KSENSOR_F_META_WORK) != 0) {
765 		mutex_exit(&ksensor_g_mutex);
766 		sensor->ksensor_nwaiters++;
767 		while ((sensor->ksensor_flags & KSENSOR_F_META_WORK) != 0) {
768 			int cv = cv_wait_sig(&sensor->ksensor_meta_cv,
769 			    &sensor->ksensor_mutex);
770 			if (cv == 0) {
771 				sensor->ksensor_nwaiters--;
772 				cv_broadcast(&sensor->ksensor_meta_cv);
773 				mutex_exit(&sensor->ksensor_mutex);
774 				return (EINTR);
775 			}
776 		}
777 
778 		/*
779 		 * We're not longer waiting; however, because we dropped the
780 		 * global mutex we have to start over at the top.
781 		 */
782 		sensor->ksensor_nwaiters--;
783 		cv_broadcast(&sensor->ksensor_meta_cv);
784 		mutex_exit(&sensor->ksensor_mutex);
785 		goto restart;
786 	}
787 
788 	/*
789 	 * We have obtained ownership of the sensor. At this point, we should
790 	 * check to see if it's valid or not.
791 	 */
792 	sensor->ksensor_flags |= KSENSOR_F_META_WORK;
793 	dev_info_t *pdip = ddi_get_parent(sensor->ksensor_ksdip->ksdip_dip);
794 	mutex_exit(&sensor->ksensor_mutex);
795 	mutex_exit(&ksensor_g_mutex);
796 
797 	/*
798 	 * Grab a reference on the device node to ensure that it won't go away.
799 	 */
800 	ndi_devi_enter(pdip);
801 	e_ddi_hold_devi(sensor->ksensor_ksdip->ksdip_dip);
802 	ndi_devi_exit(pdip);
803 
804 	/*
805 	 * Now that we have an NDI hold, check if it's valid or not. It may have
806 	 * become invalid while we were waiting due to a race. We must set the
807 	 * flag indicating that we have a hold on it. This is what allows us to
808 	 * use ksensor_release().
809 	 */
810 	mutex_enter(&ksensor_g_mutex);
811 	mutex_enter(&sensor->ksensor_mutex);
812 	sensor->ksensor_flags |= KSENSOR_F_HELD;
813 	if ((sensor->ksensor_ksdip->ksdip_flags & KSENSOR_DIP_F_REMOVED) != 0) {
814 		mutex_exit(&ksensor_g_mutex);
815 		ksensor_release(sensor);
816 		ksensor_release_meta(sensor);
817 		return (ESTALE);
818 	}
819 
820 	/*
821 	 * This sensor isn't valid. Try to prod it via the NDI to see if it
822 	 * should be. This needs to happen if an instance gets detached for
823 	 * example.
824 	 */
825 	if ((sensor->ksensor_flags & KSENSOR_F_VALID) == 0) {
826 		mutex_exit(&sensor->ksensor_mutex);
827 		mutex_exit(&ksensor_g_mutex);
828 		(void) ndi_devi_config(pdip, NDI_NO_EVENT);
829 		mutex_enter(&ksensor_g_mutex);
830 		mutex_enter(&sensor->ksensor_mutex);
831 
832 		/*
833 		 * If we attempted to reattach it and it isn't now valid, fail
834 		 * this request.
835 		 */
836 		if ((sensor->ksensor_ksdip->ksdip_flags &
837 		    KSENSOR_DIP_F_REMOVED) != 0 ||
838 		    (sensor->ksensor_flags & KSENSOR_F_VALID) == 0) {
839 			mutex_exit(&sensor->ksensor_mutex);
840 			mutex_exit(&ksensor_g_mutex);
841 			ksensor_release(sensor);
842 			ksensor_release_meta(sensor);
843 			return (ESTALE);
844 		}
845 	}
846 
847 	VERIFY(sensor->ksensor_flags & KSENSOR_F_META_WORK);
848 	VERIFY(sensor->ksensor_flags & KSENSOR_F_HELD);
849 	VERIFY(sensor->ksensor_flags & KSENSOR_F_VALID);
850 
851 	mutex_exit(&sensor->ksensor_mutex);
852 	mutex_exit(&ksensor_g_mutex);
853 	ksensor_release_meta(sensor);
854 
855 	return (0);
856 }
857 
858 int
859 ksensor_op_close(id_t id)
860 {
861 	mutex_enter(&ksensor_g_mutex);
862 	ksensor_t *sensor = ksensor_find_by_id(id);
863 	if (sensor == NULL) {
864 		mutex_exit(&ksensor_g_mutex);
865 		return (ENOENT);
866 	}
867 
868 	mutex_enter(&sensor->ksensor_mutex);
869 	VERIFY(sensor->ksensor_flags & KSENSOR_F_VALID);
870 	VERIFY(sensor->ksensor_flags & KSENSOR_F_HELD);
871 	VERIFY0(sensor->ksensor_flags & KSENSOR_F_META_WORK);
872 
873 	/*
874 	 * The system guarantees that open(9E) and close(9E) will not happen at
875 	 * the same time, so it's safe for us to drop these and know that we
876 	 * can't get another open until we return.
877 	 */
878 	mutex_exit(&sensor->ksensor_mutex);
879 	mutex_exit(&ksensor_g_mutex);
880 
881 	ksensor_release(sensor);
882 	return (0);
883 }
884 
885 /*
886  * Obtain a ksensor that should already have been held by a call to
887  * ksensor_op_open().
888  */
889 static ksensor_t *
890 ksensor_op_acquire(id_t id)
891 {
892 	mutex_enter(&ksensor_g_mutex);
893 	ksensor_t *sensor = ksensor_find_by_id(id);
894 	VERIFY3P(sensor, !=, NULL);
895 	mutex_enter(&sensor->ksensor_mutex);
896 	mutex_exit(&ksensor_g_mutex);
897 	VERIFY(sensor->ksensor_flags & KSENSOR_F_VALID);
898 	VERIFY(sensor->ksensor_flags & KSENSOR_F_HELD);
899 
900 	/*
901 	 * Serialize access to the ksensor for operations. Providers expect to
902 	 * only have a single operation called at once per sensor.
903 	 */
904 	while ((sensor->ksensor_flags & KSENSOR_F_OP) != 0) {
905 		int cv = cv_wait_sig(&sensor->ksensor_op_cv,
906 		    &sensor->ksensor_mutex);
907 		if (cv == 0) {
908 			mutex_exit(&sensor->ksensor_mutex);
909 			return (NULL);
910 		}
911 	}
912 	sensor->ksensor_flags |= KSENSOR_F_OP;
913 	sensor->ksensor_op_thr = (uintptr_t)curthread;
914 	mutex_exit(&sensor->ksensor_mutex);
915 
916 	return (sensor);
917 }
918 
919 static void
920 ksensor_op_release(ksensor_t *sensor)
921 {
922 	mutex_enter(&sensor->ksensor_mutex);
923 	VERIFY3U(sensor->ksensor_op_thr, ==, curthread);
924 	VERIFY(sensor->ksensor_flags & KSENSOR_F_OP);
925 	sensor->ksensor_flags &= ~KSENSOR_F_OP;
926 	sensor->ksensor_op_thr = 0;
927 	cv_signal(&sensor->ksensor_op_cv);
928 	mutex_exit(&sensor->ksensor_mutex);
929 }
930 
931 int
932 ksensor_op_kind(id_t id, sensor_ioctl_kind_t *kind)
933 {
934 	ksensor_t *sensor = ksensor_op_acquire(id);
935 	if (sensor == NULL) {
936 		return (EINTR);
937 	}
938 
939 	int ret = sensor->ksensor_ops->kso_kind(sensor->ksensor_arg, kind);
940 	ksensor_op_release(sensor);
941 
942 	return (ret);
943 }
944 
945 int
946 ksensor_op_scalar(id_t id, sensor_ioctl_scalar_t *scalar)
947 {
948 	ksensor_t *sensor = ksensor_op_acquire(id);
949 	if (sensor == NULL) {
950 		return (EINTR);
951 	}
952 
953 	int ret = sensor->ksensor_ops->kso_scalar(sensor->ksensor_arg, scalar);
954 	ksensor_op_release(sensor);
955 
956 	return (ret);
957 }
958 
959 void
960 ksensor_unregister(dev_info_t *reg_dip)
961 {
962 	mutex_enter(&ksensor_g_mutex);
963 	if (ksensor_cb_dip != reg_dip) {
964 		dev_err(reg_dip, CE_PANIC, "asked to unregister illegal dip");
965 	}
966 
967 	for (ksensor_t *sensor = avl_first(&ksensor_avl); sensor != NULL;
968 	    sensor = AVL_NEXT(&ksensor_avl, sensor)) {
969 		ksensor_denotify(sensor);
970 	}
971 
972 	for (ksensor_dip_t *k = list_head(&ksensor_dead_dips); k != NULL;
973 	    k = list_next(&ksensor_dead_dips, k)) {
974 		for (ksensor_t *sensor = list_head(&k->ksdip_sensors); sensor !=
975 		    NULL; sensor = list_next(&k->ksdip_sensors, sensor)) {
976 			ksensor_denotify(sensor);
977 		}
978 	}
979 
980 	ksensor_cb_dip = NULL;
981 	ksensor_cb_create = NULL;
982 	ksensor_cb_remove = NULL;
983 	mutex_exit(&ksensor_g_mutex);
984 }
985 
986 int
987 ksensor_register(dev_info_t *reg_dip, ksensor_create_f create,
988     ksensor_remove_f remove)
989 {
990 	ksensor_t *sensor;
991 
992 	if (create == NULL || remove == NULL) {
993 		dev_err(reg_dip, CE_WARN, "kernel sensor registration "
994 		    "requires both a create and removal callback");
995 		return (EINVAL);
996 	}
997 
998 	mutex_enter(&ksensor_g_mutex);
999 	if (ksensor_cb_dip != NULL) {
1000 		dev_err(reg_dip, CE_WARN, "kernel sensors are already "
1001 		    "registered");
1002 		mutex_exit(&ksensor_g_mutex);
1003 		return (EEXIST);
1004 	}
1005 
1006 	ksensor_cb_dip = reg_dip;
1007 	ksensor_cb_create = create;
1008 	ksensor_cb_remove = remove;
1009 
1010 	for (sensor = avl_first(&ksensor_avl); sensor != NULL; sensor =
1011 	    AVL_NEXT(&ksensor_avl, sensor)) {
1012 		mutex_enter(&sensor->ksensor_mutex);
1013 		ASSERT0(sensor->ksensor_flags & KSENSOR_F_NOTIFIED);
1014 
1015 		if (ksensor_cb_create(sensor->ksensor_id, sensor->ksensor_class,
1016 		    sensor->ksensor_name) == 0) {
1017 			sensor->ksensor_flags |= KSENSOR_F_NOTIFIED;
1018 		}
1019 
1020 		mutex_exit(&sensor->ksensor_mutex);
1021 	}
1022 
1023 	mutex_exit(&ksensor_g_mutex);
1024 
1025 	return (0);
1026 }
1027 
1028 int
1029 ksensor_kind_temperature(void *unused, sensor_ioctl_kind_t *k)
1030 {
1031 	k->sik_kind = SENSOR_KIND_TEMPERATURE;
1032 	return (0);
1033 }
1034 
1035 int
1036 ksensor_kind_current(void *unused, sensor_ioctl_kind_t *k)
1037 {
1038 	k->sik_kind = SENSOR_KIND_CURRENT;
1039 	return (0);
1040 }
1041 
1042 int
1043 ksensor_kind_voltage(void *unused, sensor_ioctl_kind_t *k)
1044 {
1045 	k->sik_kind = SENSOR_KIND_VOLTAGE;
1046 	return (0);
1047 }
1048 
1049 void
1050 ksensor_init(void)
1051 {
1052 	mutex_init(&ksensor_g_mutex, NULL, MUTEX_DRIVER, NULL);
1053 	list_create(&ksensor_dips, sizeof (ksensor_dip_t),
1054 	    offsetof(ksensor_dip_t, ksdip_link));
1055 	list_create(&ksensor_dead_dips, sizeof (ksensor_dip_t),
1056 	    offsetof(ksensor_dip_t, ksdip_link));
1057 	ksensor_ids = id_space_create("ksensor", 1, L_MAXMIN32);
1058 	avl_create(&ksensor_avl, ksensor_avl_compare, sizeof (ksensor_t),
1059 	    offsetof(ksensor_t, ksensor_id_avl));
1060 }
1061