xref: /illumos-gate/usr/src/uts/common/io/gpio/kgpio.c (revision fd71220ba0fafcc9cf5ea0785db206f3f31336e7)
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 2022 Oxide Computer Company
14  */
15 
16 /*
17  * Kernel GPIO Framework
18  * ---------------------
19  *
20  * This driver, kgpio(4D), implements the general kernel general purpose I/O
21  * (GPIO) and dedicated purpose I/O (dpio) framework discussed in gpio(7).
22  * Before we jump into the organization and specifics here, let's go into a few
23  * definitions and overviews of what all is going on:
24  *
25  * GPIO -- General Purpose I/O
26  *
27  *	A GPIO is something that allows software to directly understand and
28  *	manipulate the state of a particular pin on an ASIC. For example, this
29  *	allows software to do things like to read the logical level on a pin or
30  *	to set the logical output value. In addition, there are often other
31  *	properties that can be changed such as things like whether internal pull
32  *	ups are used, controls around interrupt behavior, drive strength, etc.
33  *	Each of these different controls vary from controller to controller.
34  *	Each of these is represented as an 'attribute', which is defined below.
35  *
36  * GPIO CONTROLLER / PROVIDER
37  *
38  *	A GPIO controller is a piece of hardware that provides accesses to and
39  *	control over GPIOs. In the OS, we call a device driver for a GPIO
40  *	controller a kgpio provider, as it provides access to and the
41  *	functionality around this. Device drivers themselves use the
42  *	<sys/gpio/kgpio_provider.h> header and related functions.
43  *
44  *	Each controller is exposed to userland through its own character device
45  *	in /devices. There are not entries in /dev for these. The providing
46  *	device driver does not have to worry about this and this takes care of
47  *	ensuring that the provider is present, allowing them to detach like
48  *	other classes of loadable modules.
49  *
50  * ATTRIBUTE
51  *
52  *	An attribute refers to a setting or property of a GPIO. While many
53  *	controllers have similar attributes, in many cases the actual set of
54  *	valid values varies between them (or potentially even from GPIO to GPIO
55  *	on a device). Attributes are stored inside of nvlist_t's (more on that
56  *	later) and consist of a few different pieces of information:
57  *
58  *	  o Name	This is how software and humans generally refer to a
59  *			name for this attribute. The attribute name is generally
60  *			made up of two parts: the provider's name and then the
61  *			actual name. This allows different providers to not
62  *			conflict with one another. These are both separated by
63  *			a ':' character. Examples here are things like
64  *			'sim:pull' which is used by the gpio_sim driver. Here
65  *			'sim' refers to the provider and 'pull' the name.
66  *
67  *	  o Value	This is the actual value of the attribute for a given
68  *			GPIO. It generally is a uint32_t (representing an enum)
69  *			or a string.
70  *
71  *	  o Protection	This indicates whether the attribute is read-only or
72  *			read-write. A read-write attribute can be updated by a
73  *			consumer.
74  *
75  *	  o Possible	This is an array of values that are valid for this
76  *			particular attribute. This information is specific to a
77  *			GPIO.
78  *
79  * DPIO -- Dedicated Purpose I/O
80  *
81  *	A DPIO is a construct that wraps up a GPIO, constraining what it can do
82  *	and freezing the ability to set all of its attributes except a small
83  *	set. Their reason for existence is to try and solve the problem that
84  *	while a GPIO controller is specific to a given piece of hardware (like a
85  *	specific CPU or ASIC), what is safe to use depends entirely on the
86  *	specifics of the way that is used. For example, which GPIOs are safe to
87  *	use on a CPU depends on the specific motherboard it's found in and the
88  *	surrounding pieces. Instead, this is where we offer the idea of the DPIO
89  *	as its purpose is dedicated.
90  *
91  *	DPIOs show up to the system as their own character device with basic
92  *	semantics around read(2), write(2), and poll(2). The DPIO devices show
93  *	up in /dev/dpio/<name> and all of the specifics of them are defined in
94  *	their own header <sys/gpio/dpio.h>.
95  *
96  *	An important part that we'll get into in the driver organization is that
97  *	each DPIO points to its corresponding GPIO controller.
98  *
99  * IOMUX -- I/O Multiplexer
100  *
101  *	An I/O multiplexer is something that exists in hardware that maps which
102  *	peripherals are actually connected to which pins. Many SoCs are designed
103  *	such that an actual pin on the device can be pointed at one of several
104  *	different peripherals.
105  *
106  *	Right now, the GPIO framework is not integrated into any kind of I/O or
107  *	pin muxing framework. This means that GPIOs that are visible may or may
108  *	not do anything based on the state of that mux. This is a known missing
109  *	piece and is something that will see further consolidation.
110  *
111  * -------------------
112  * Driver Organization
113  * -------------------
114  *
115  * To understand how this driver is organized, it's worth going into a bit more
116  * detail about the framework and what entities we track.
117  *
118  * Fundamentally a GPIO controller and is mapped to its provider driver. More
119  * specifically, the dev_info_t is the key that we used to build up and manage a
120  * controller in the kgpio_t structure. These providers will register with the
121  * kgpio kernel module when they call attach(9E) and detach(9E).
122  *
123  * When a provider registers with us, they tell us how many GPIOs they support.
124  * This gives us a set of unsigned integer GPIO IDs that are in the set [0,
125  * kgpio_ngpios). The general framework always refers to a GPIO on a controller
126  * by its numeric ID.  This ID space is contiguous, which may not be true of the
127  * actual hardware. It is not our intent that this is the same thing. Instead,
128  * for more semantics, GPIOs have a common 'name' attribute which providers fill
129  * in that userland can consume. However, the kernel identifies all GPIOs by
130  * their controller and a provider-supplied opaque ID. The kgpio driver does
131  * not track individual GPIOs.
132  *
133  * Because we need to provide character devices ourselves, the kgpio driver has
134  * its own instance which is a child of the pseudo nexus. Importantly, krtld
135  * guarantees that our module is loaded before anything that would call into us;
136  * however, it does not guarantee anything about whether a particular instance
137  * will be present. This in turn leads to us keeping global structure and state
138  * in the driver which is independent from our actual instance because the
139  * instance may come and go.
140  *
141  * In turn, the framework does keep track of all of the DPIOs that are created
142  * because these are independent character devices and minors. These are stored
143  * in data that isn't tied to the instance mostly for the reason as the core of
144  * the GPIO framework. Each DPIO's information is tracked in a 'dpio_t'
145  * structure.
146  *
147  * To facilitate the fact that the character device entry points all operate in
148  * terms of minors, we have a shared structure that is embedded in both the
149  * kgpio_t and dpio_t called a kgpio_minor_t. These are stored in a global
150  * avl_tree_t and is how minors are mapped back to their device type and actual
151  * information.
152  *
153  * The organization of data is roughly as follows (some members elided):
154  *
155  *
156  *     +-----------------------+
157  *     | Global DPIO List      |
158  *     |                       |       +-------------+   +-------------+
159  *     | list_t kgpio_g_dpios -+------>| DPIO dpio_t |-->| DPIO dpio_t |--> ...
160  *     +-----------------------+       | "foo"       |   | "bar"       |
161  *                                     |             |   |             |
162  *                                     | gpio ID     |   | gpio ID     |
163  *  +--------------------------------->| kgpio_t *   |   | kgpio_t *   |
164  *  |                                  +-------------+   +-------------+
165  *  |                                      |                |
166  *  |  +------------------------+          |   +------------+
167  *  |  | Global Controller List |          v   v
168  *  |  |                        |     +-------------+   +-------------+
169  *  |  | list_t kgpio_g_gpios --+---->| kgpio_t     |-->| kgpio_t     |--> ...
170  *  |  +------------------------+     |             |   |             |
171  *  |                                 | dev_info_t  |   | dev_info_t  |
172  *  +-------------------------------->| kgpio_ops_t |   | kgpio_ops_t |
173  *  |                                 +-------------+   +-------------+
174  *  |                                                      |
175  *  |  +-------------------------+                         |
176  *  |  | Global Minor Tracking   |                         v
177  *  |  |                         |                    +---------------------+
178  *  +--| avl_tree_t kgpio_minors |                    | GPIO Provider       |
179  *     +-------------------------+                    |                     |
180  *                                                    | A hardware-specific |
181  *                                                    | driver              |
182  *                                                    +---------------------+
183  *
184  * In more detail, all of our global data is protected by the kgpio_g_mutex and
185  * all such data is prefixed with 'kgpio_g_'. As GPIO Provider drivers register
186  * with kgpio framework via kgpio_register(), we create a kgpio_t for them and
187  * insert them into the global kgpio_g_dpios list. At that point, we do a few
188  * additional things:
189  *
190  *   o If our main kgpio(4D) instance is attached, then we will go through and
191  *     create a minor node for the controller. If not, this will be deferred
192  *     until it does attach.
193  *
194  *   o We will register a DDI callback for when the module is removed from the
195  *     system, which is a step past being detached. This is what allows us to
196  *     call back a provider when someone wants to use it, just as the /devices
197  *     devfs file system normally does.
198  *
199  * At that point, we will flow data and back and forth via ioctls on the
200  * controller minor nodes. As information is asked for by userland, the kgpio
201  * driver will call back into the provider with the provided kgpio_ops_t
202  * operations vector and the driver's private data (both passed in at
203  * registration time).
204  *
205  * Only when a user comes and asks to create a DPIO via the
206  * KGPIO_IOC_DPIO_CREATE ioctl will we go through and at that point create a
207  * dpio_t. The dpio_t is stored in its own global list and each dpio_t points to
208  * the corresponding kgpio_t controller and contains the GPIO that it should
209  * use. In addition, there are a number of fields set at creation time which
210  * relate to the capabilities of the DPIO which are what govern whether the DPIO
211  * supports read(9E), write(9E), etc.
212  *
213  * When a DPIO is created a minor node is created with the type
214  * DDI_NT_GPIO_DPIO. While users can give a DPIO any name they want, we prefix
215  * each name in /devices with 'dpio:'. This ensures that a user's name for a
216  * DPIO will not conflict with any controllers that may come and go in the
217  * system. The devfsadm(8) plugs for GPIO subsystem will ensure that a DPIO is
218  * created under /dev/dpio with the user's requested name. The 'dpio:' leading
219  * portion of the /devices minor node will not be present.
220  *
221  * There is one final type of minor node that exists, which is called 'dpinfo'
222  * which is used to provide static, creation-time based information about DPIOs.
223  * This exists because we generally want to support the ability to both create
224  * DPIOs that honor O_EXCL/FEXCL and DPIOs that only the kernel can open. As
225  * such, this minor can be used to query about basic information about a DPIO
226  * without requiring one to be able to open it (which may not be possible).
227  *
228  * ---------
229  * Data Flow
230  * ---------
231  *
232  * There are two different high-leveling goals in the data design in this
233  * system:
234  *
235  *   o Hardware should be the single source of truth (where possible) for the
236  *     current values of a GPIO's attributes. That is why there is no caching of
237  *     data either in this driver or in the individual providers. Doing
238  *     anything else allows for things to get out of sync.
239  *
240  *   o Where possible, all data about a GPIO should be something that we can
241  *     atomically change. In general, it can be very hard to trace a series of
242  *     valid steps from point a to point b for a GPIO, if you cannot change
243  *     multiple attributes at once. While there are always complications here
244  *     because of pin and I/O muxing, this is why there is no individual
245  *     attribute get and set routines.
246  *
247  * When getting and setting information, a GPIO's attributes are all stored in a
248  * single nvlist_t. Here, each key is the name of an attribute which points to
249  * its corresponding value -- generally a string or uint32_t. In addition, there
250  * is an embedded metadata nvlist_t that has information such as the protection
251  * or supported values for a given GPIO.
252  *
253  * All of this information is considered GPIO-specific because each GPIO in a
254  * system may have readily different capabilities and functionality. While there
255  * are common attributes which are defined in <sys/gpio/kgpio_provider.h>, the
256  * expectation is that each provider defines its own attributes (other than
257  * name) in their own header file that generally should be found in
258  * <sys/gpio/driver.h>, where driver is the name of the driver. Let's look at an
259  * example of this structure if we had four attributes present:
260  *
261  * nvlist_t
262  *	"name"		-> string
263  *	"zen:output"	-> uint32
264  *	"zen:input"	-> uint32
265  *	"zen:pull"	-> uint32
266  *	"metadata"	-> nvlist_t
267  *			"name"		-> nvlist_t
268  *					"protection"	-> uint32
269  *			"zen:output":	-> nvlist_t
270  *					"protection"	-> uint32
271  *					"possible"	-> uint32[]
272  *			"zen:input":	-> nvlist_t
273  *					"protection"	-> uint32
274  *					"possible"	-> uint32[]
275  *			"zen:pull":	-> nvlist_t
276  *					"protection"	-> uint32
277  *					"possible"	-> uint32[]
278  *
279  * Basically what we see here is that every attribute is a top-level key. The
280  * metadata is an nvlist_t where each key is the of an attribute which points to
281  * an nvlist_t. The type of "possible" will match its underlying data type. The
282  * metadata information is only provided by providers themselves when getting an
283  * attribute. When an attribute is set, there is no metadata present. As in the
284  * case of "name", something like the possible values can be omitted (in this
285  * case because it's read-only). While metadata is strictly optional, it is
286  * useful to include as it helps users understand what is going on.
287  *
288  * When coming up with attributes, there is no need for there to be a strict 1:1
289  * mapping with hardware fields. In fact, providers should try to phrase things
290  * such that people cannot create a state that is unsupported. For example, some
291  * hardware may have two register settings: one for whether something is level
292  * triggered and one for which edges should generate the interrupt. In this
293  * case, if done simply, one could set an illegal value which is level triggered
294  * on both the rising and falling edge which the hardware warns against. Rather
295  * than allowing this to happen, the provider should instead come up with a
296  * single semantic attribute so that way users can't end up in illegal states.
297  *
298  * Next we should turn our attention to the data flow for DPIOs. Where as GPIOs
299  * allow the provider to define everything about them, DPIOs are different.
300  * Instead, our DPIO operation vectors are all about taking narrowly defined
301  * types in <sys/gpio/dpio.h> such as the dpio_input_t and the dpio_output_t and
302  * having the provider map that to hardware states. Right now we have a limited
303  * number of input and output values. Providers may not have a way to map every
304  * possible state to one of our values. Similarly, there may be values that they
305  * cannot represent in their hardware implementation. In these cases, providers
306  * must fail the various DPIO requests. We require that consumers always read
307  * and write a uint32_t value and that is enforced for providers. This is done
308  * to give us future flexibility in the set of values we may support.
309  *
310  * ------------------------------------------
311  * Provider Lifecycle, Locking, and Lifetimes
312  * ------------------------------------------
313  *
314  * The most nuanced piece of this driver and framework is that we have to refer
315  * to other driver's dev_info_t data structures and we want to allow those
316  * things to be detached normally. A normal driver would attach and create minor
317  * nodes, then detach when it no longer exists. However, when this detach is not
318  * the driver being removed, devfs would notice this and when a minor node is
319  * accessed bring it back to life. While this is a nice feature, like with the
320  * kernel sensor subsystem, we end up having to do a bunch of this ourselves
321  * because we are responsible for all the minors.
322  *
323  * This tradeoff centralizes the complexity in one spot rather than having each
324  * provider have to reimplement cb_ops and more that they otherwise wouldn't
325  * even need to or have to think about minors (which helps if they have their
326  * own for any reason). With that in mind, it's worth laying out some
327  * understanding of how this works and when we need to check and worry about
328  * this:
329  *
330  *   o If a GPIO controller is actively open, that is someone called open(9E) on
331  *     its minor, then we know that the dev_info_t is attached and present.
332  *
333  *   o Whenever a DPIO exists, it always has a hold on its underlying
334  *     controller, regardless of whether the controller is open or not.
335  *
336  *   o When a GPIO provider driver detaches, it will call back into us. At that
337  *     point we consider it invalid.
338  *
339  *   o When a GPIO provider driver registers with us, we know it is valid.
340  *
341  *   o The DDI will call back into us when the device driver is actually removed
342  *     from the system (e.g. rem_drv), giving us a cue as to when everything is
343  *     fully gone and we can finally tear down our state.
344  *
345  * With this in mind, our actual task and rules are fairly straightforward and
346  * can be summarized as: when we are in open(9E) and are opening a controller,
347  * we must check if it is valid (KGPIO_F_VALID) and if not, attempt to make it
348  * valid again. Any other character device operation that is coming in we don't
349  * have to worry about it because it is in that state by definition. This state
350  * diagram can be summarized as:
351  *
352  *           |
353  *           +-------<-----------------------------------<---------+
354  *           |                                                     |
355  *           | . . driver calls kgpio_register()                   |
356  *           v                                                     |
357  *       +-------+                                                 |
358  *       | Valid |                                                 |
359  *       +-------+                                                 ^
360  *           |                                                     |
361  *           | . . driver calls kgpio_unregister().                |
362  *           v                                                     |
363  *      +---------+                                                |
364  *      | Invalid |                                                |
365  *      +---------+                                                |
366  *        |     |                                                  |
367  *        |     | . . user calls open on a controller              |
368  *        |     |     minor node                                   |
369  *        |     +------------------+                               |
370  *        |                        |                               ^
371  *        |                        |                               |
372  *        |                        v                               |
373  *        |               +-------------------+                    |
374  *        |               | ndi_devi_config() |-->-.---------------+
375  *        |               +-------------------+    . . driver attach(9E) called
376  *        |                                |
377  *        | . . DDI's unbind callback      |
378  *        |     fires as driver is         |
379  *        |     being removed              |
380  *        v                                | . . attach failed or there
381  *   +---------+                           |     was no call to
382  *   | kgpio_t |<--------------------------+     kgpio_register() again
383  *   | Deleted |
384  *   +---------+
385  *
386  * The heavy lifting is done in the rather involved function, kgpio_hold_by_id.
387  * In that, if we find that the KGPIO_F_VALID and KGPIO_F_HELD are both present,
388  * then we're in the earlier simple case described above. Otherwise, if not, we
389  * then have to consider the fact that multiple threads may all be trying to get
390  * here for some reason (e.g. concurrent calls to open(9E)).
391  *
392  * The first thread that takes control of the process of validating something
393  * sets the KGPIO_F_META_WORK flag. Any other thread that finds this flag set
394  * simply waits on it to finish. When these blocked threads are signaled, they
395  * restart the entire validation process again. Once the meta flag is owned, we
396  * proceed to take the NDI hold which ensures that the dev_info_t shouldn't be
397  * able to go away. At that point, we will attempt to attach the driver if it's
398  * not attached. If it is, then we are done.
399  *
400  * The NDI hold will persist as long as the device is open. Similarly, as
401  * mentioned above, each DPIO that exists puts a similar NDI hold on the
402  * underlying dev_info_t.
403  *
404  * The benefit of this whole dance is that it guarantees that an open controller
405  * node cannot disappear at all during any other cb_ops, simplifying lifetime
406  * considerations. Basically when calling open(9E) we need to consider it, but
407  * once open, we're good until close(9E).
408  *
409  * This ties in directly into the locking hierarchy in the system. There are
410  * three classes of locks that exist, which are ordered by the order in which
411  * they should be taken.
412  *
413  *  1. The global kgpio_g_mutex, which protects all of the global data
414  *     structures.
415  *  2. The mutex embedded in the dpio_t structure.
416  *  3. The mutex embedded in the kgpio_t structure.
417  *
418  * When dealing with locking, one must always take the kgpio_g_mutex before one
419  * ever takes either of the kgpio_mutex or dpio_mutex inside the kgpio_t and
420  * dpio_t. Most of the data that is required for the DPIO to perform I/O on the
421  * underlying GPIO is read-only data. In general, one should not hold both a
422  * dpio_t and kgpio_t mutex at the same time. Finally, if you need to call into
423  * the NDI or enter a parent, none of our locks should be held.
424  *
425  * The lifetime of the dpio_t structure is tied to someone creating and
426  * destroying it with ioctls (KGPIO_IOC_DPIO_CREATE and KGPIO_IOC_DPIO_DESTROY).
427  * A DPIO cannot be destroyed if someone is using it. This means that like the
428  * kgpio_t, once you get through the open(9E) call, you can assume that it will
429  * always be valid. In addition, the kgpio_t that is attached to it always will
430  * be. Unlike the kgpio_t, the dpio_t hold process is much simpler. As long as
431  * the dpio is findable in the global list (with the global mutex held), then it
432  * is valid.
433  *
434  * Ideally, the combination of these two pieces leads to making the actual
435  * design and implementation here much simpler in other parts and ultimately,
436  * makes the system easier to reason about.
437  *
438  * ---------------------------------
439  * Future Integrations, Shortcomings
440  * ---------------------------------
441  *
442  * At this time, the implementation of the framework has been designed around
443  * erring on the side of simplicity and enabling end to end functionality.
444  * Several of the choices such as using nvlist_t's, the presence of metadata,
445  * and the design of DPIOs are focused on that. Here are things that this
446  * currently doesn't do and may have varying degrees of challenges:
447  *
448  *   o The attribute and DPIO interface are not designed around the need to
449  *     sometimes implement various peripherals via bit-banging GPIOs. For such
450  *     cases, an alternative set of interfaces which allows a consumer to batch
451  *     up a series of changes to a GPIO with any optional delays that are all
452  *     executed at once is probably what should be used. Because the initial
453  *     needs do not require this, we have not pretended to come up with a good
454  *     consumerless API.
455  *
456  *   o Right now we are using simple intrusive lists for DPIOs and GPIOs. There
457  *     is no easy way to go from a GPIO and see which DPIOs point into it. When
458  *     this becomes a bottelneck (e.g. as part of delivering polling results),
459  *     then that would be the time to improve things here and add something akin
460  *     to an AVL to the kgpio_t that includes all of its DPIOs.
461  *
462  *   o We currently don't support any chpoll(9E) interfaces. The intent here is
463  *     that there would be a single pollhead per dpio_t that is shared between
464  *     anyone who calls chpoll(9E) on the dpio_t. This would be paired with a
465  *     callback function for a provider to call back into us. Importantly
466  *     though, when that is added, we should ensure that the providers are
467  *     instructed not to hold any locks across the call.
468  *
469  *   o Right now there is no integration with pin and I/O muxing, meaning that
470  *     it is possible that anything set in the GPIO controller's hardware may
471  *     have no effect. This is an area of future research and work.
472  *
473  *   o There is currently a forced 1:1 relationship between the provider and the
474  *     dev_info_t. The provider also can't determine its own name. While these
475  *     are simpler problems to solve, the broader problem (which extends beyond
476  *     just the GPIO framework) is how to name and relate providers to semantic
477  *     things that a user actually knows about and may not have a stable
478  *     /devices path for the consumer to rely upon.
479  */
480 
481 #include <sys/types.h>
482 #include <sys/file.h>
483 #include <sys/errno.h>
484 #include <sys/open.h>
485 #include <sys/cred.h>
486 #include <sys/ddi.h>
487 #include <sys/sunddi.h>
488 #include <sys/stat.h>
489 #include <sys/conf.h>
490 #include <sys/devops.h>
491 #include <sys/cmn_err.h>
492 #include <sys/list.h>
493 #include <sys/stddef.h>
494 #include <sys/sunndi.h>
495 #include <sys/esunddi.h>
496 #include <sys/taskq.h>
497 #include <sys/id_space.h>
498 #include <sys/sysmacros.h>
499 #include <sys/avl.h>
500 #include <sys/stdbool.h>
501 #include <sys/ctype.h>
502 #include <sys/fs/dv_node.h>
503 
504 #include <sys/gpio/kgpio_provider.h>
505 #include <sys/gpio/kgpio.h>
506 #include <sys/gpio/dpio.h>
507 
508 #define	KGPIO_CTRL_NAMELEN	DPIO_NAMELEN
509 
510 typedef enum {
511 	/*
512 	 * This flag is used to indicate that the minor node is registered. It
513 	 * is possible for this not to happen if a provider comes in before the
514 	 * kgpio instance is force attached.
515 	 */
516 	KGPIO_F_MINOR_VALID	= 1 << 0,
517 	/*
518 	 * This flag tracks the notion of whether or not we believe the
519 	 * underlying driver instance is active and attached. When the producer
520 	 * is deatching this will be cleared and this is our call to try to open
521 	 * it up again.
522 	 */
523 	KGPIO_F_VALID		= 1 << 1,
524 	/*
525 	 * This indicates that the underlying driver instance represented by the
526 	 * kgpio_t has a DDI hold on it. This is established in a controller's
527 	 * first open and removed when it is closed. Note, this is used as part
528 	 * of manipulating the controller node. DPIOs will also have holds on
529 	 * the underlying dev_info_t that are tracked with their lifetime.
530 	 */
531 	KGPIO_F_HELD		= 1 << 2,
532 	/*
533 	 * This flag is a stage beyond having cleared KGPIO_F_VALID. At this
534 	 * point, the driver this is associated with is actually going away and
535 	 * therefore this truly is getting cleaned up.
536 	 */
537 	KGPIO_F_REMOVED		= 1 << 3,
538 	/*
539 	 * This flag is used to synchronize the act of holding and/or attaching
540 	 * a given kgpio. There can only be one at a time. This is only ever
541 	 * used in open. close(9E) does not require this because of the
542 	 * exclusion guarantees of the kernel.
543 	 */
544 	KGPIO_F_META_WORK	= 1 << 4
545 } kgpio_flags_t;
546 
547 struct kgpio;
548 struct dpio;
549 
550 typedef enum {
551 	/*
552 	 * This is a GPIO controller. It is represented by a kgpio_t.
553 	 */
554 	KGPIO_MINOR_T_CTRL,
555 	/*
556 	 * This is a DPIO entry. It is represented by a dpio_t.
557 	 */
558 	KGPIO_MINOR_T_DPIO,
559 	/*
560 	 * This is a general interface that is used to get static information
561 	 * about DPIOs. Nothing in the kminor_data is valid.
562 	 */
563 	KGPIO_MINOR_T_DPINFO
564 } kgpio_minor_type_t;
565 
566 typedef struct kgpio_minor {
567 	avl_node_t kminor_avl;
568 	id_t kminor_id;
569 	kgpio_minor_type_t kminor_type;
570 	union {
571 		struct dpio *kminor_dpio;
572 		struct kgpio *kminor_ctrl;
573 	} kminor_data;
574 } kgpio_minor_t;
575 
576 typedef struct kgpio {
577 	kgpio_minor_t kgpio_minor;
578 	list_node_t kgpio_link;
579 	dev_info_t *kgpio_dip;
580 	uint32_t kgpio_ngpios;
581 	const kgpio_ops_t *kgpio_ops;
582 	void *kgpio_drv;
583 	ddi_unbind_callback_t kgpio_cb;
584 	char kgpio_mname[KGPIO_CTRL_NAMELEN];
585 	kmutex_t kgpio_mutex;
586 	kcondvar_t kgpio_cv;
587 	kgpio_flags_t kgpio_flags;
588 	uint32_t kgpio_ndpios;
589 } kgpio_t;
590 
591 /*
592  * This is designed to give us space for 'dpio:' and then whatever name
593  * the user gives us. This is done to avoid having someone try to create a dpio
594  * that would conflict with a controller name.
595  */
596 #define	KGPIO_DPIO_INT_NAMELEN	(KGPIO_DPIO_NAMELEN + 8)
597 
598 typedef enum {
599 	/*
600 	 * This is used to indicate that the dpio is actually open.
601 	 */
602 	DPIO_S_OPEN		= 1 << 0,
603 	/*
604 	 * This indicates that the DPIO is open exclusively right now.
605 	 */
606 	DPIO_S_EXCL		= 1 << 1
607 } dpio_status_t;
608 
609 typedef struct dpio {
610 	kgpio_minor_t dpio_minor;
611 	list_node_t dpio_link;
612 	char dpio_name[KGPIO_DPIO_INT_NAMELEN];
613 	kgpio_t *dpio_kgpio;
614 	uint32_t dpio_gpio_num;
615 	dpio_caps_t dpio_caps;
616 	dpio_flags_t dpio_flags;
617 	/*
618 	 * All fields above this point are read-only and set at DPIO creation
619 	 * time.
620 	 */
621 	kmutex_t dpio_mutex;
622 	hrtime_t dpio_last_intr;
623 	hrtime_t dpio_last_write;
624 	dpio_status_t dpio_status;
625 } dpio_t;
626 
627 /*
628  * Various definitions related to minor numbers. The first minor is what we use
629  * for the kgpio id_space. This starts at two as we reserve the minor number 1
630  * for the dpinfo entry and we assume that 0 is reserved to aid in debugging /
631  * initialization.
632  */
633 #define	KGPIO_MINOR_DPINFO	1
634 #define	KGPIO_MINOR_FIRST	2
635 #define	KGPIO_MINOR_NAME_DPINFO	"dpinfo"
636 
637 /*
638  * This is the maximum size of a user nvlist_t that we're willing to consider in
639  * the kernel. This value is a rough swag of what we think the maximum size
640  * nvlist would ever be for a single GPIO with headroom. This is here in case
641  * someone has need to tune it to unblock something.
642  */
643 size_t kgpio_max_user_nvl = 512 * 1024;
644 
645 static dev_info_t *kgpio_g_dip;
646 static kmutex_t kgpio_g_mutex;
647 static list_t kgpio_g_gpios;
648 static list_t kgpio_g_dpios;
649 static avl_tree_t kgpio_g_minors;
650 static id_space_t *kgpio_g_ids;
651 static kgpio_minor_t kgpio_g_dpinfo;
652 
653 static int
kgpio_minor_comparator(const void * l,const void * r)654 kgpio_minor_comparator(const void *l, const void *r)
655 {
656 	const kgpio_minor_t *kml = l;
657 	const kgpio_minor_t *kmr = r;
658 
659 	if (kml->kminor_id > kmr->kminor_id) {
660 		return (1);
661 	} else if (kml->kminor_id < kmr->kminor_id) {
662 		return (-1);
663 	} else {
664 		return (0);
665 	}
666 }
667 
668 static kgpio_t *
kgpio_find_by_dip(dev_info_t * dip)669 kgpio_find_by_dip(dev_info_t *dip)
670 {
671 	kgpio_t *k;
672 
673 	ASSERT(MUTEX_HELD(&kgpio_g_mutex));
674 	for (k = list_head(&kgpio_g_gpios); k != NULL;
675 	    k = list_next(&kgpio_g_gpios, k)) {
676 		if (k->kgpio_dip == dip) {
677 			return (k);
678 		}
679 	}
680 
681 	return (NULL);
682 }
683 
684 static kgpio_minor_t *
kgpio_minor_find(id_t minor)685 kgpio_minor_find(id_t minor)
686 {
687 	kgpio_minor_t idx = { 0 };
688 
689 	ASSERT(MUTEX_HELD(&kgpio_g_mutex));
690 	idx.kminor_id = minor;
691 
692 	return (avl_find(&kgpio_g_minors, &idx, NULL));
693 }
694 
695 static void
kgpio_dpio_cleanup(dpio_t * dpio)696 kgpio_dpio_cleanup(dpio_t *dpio)
697 {
698 	if (dpio->dpio_minor.kminor_id > 0) {
699 		id_free(kgpio_g_ids, dpio->dpio_minor.kminor_id);
700 		dpio->dpio_minor.kminor_id = 0;
701 	}
702 	ddi_remove_minor_node(kgpio_g_dip, dpio->dpio_name);
703 	mutex_destroy(&dpio->dpio_mutex);
704 	kmem_free(dpio, sizeof (dpio_t));
705 }
706 
707 static void
kgpio_cleanup(kgpio_t * kgpio)708 kgpio_cleanup(kgpio_t *kgpio)
709 {
710 	if (kgpio->kgpio_minor.kminor_id > 0) {
711 		id_free(kgpio_g_ids, kgpio->kgpio_minor.kminor_id);
712 		kgpio->kgpio_minor.kminor_id = 0;
713 	}
714 	cv_destroy(&kgpio->kgpio_cv);
715 	mutex_destroy(&kgpio->kgpio_mutex);
716 	kmem_free(kgpio, sizeof (kgpio_t));
717 }
718 
719 static void
kgpio_unbind_taskq(void * arg)720 kgpio_unbind_taskq(void *arg)
721 {
722 	kgpio_t *kgpio = arg;
723 
724 	mutex_enter(&kgpio_g_mutex);
725 	if ((kgpio->kgpio_flags & KGPIO_F_MINOR_VALID) != 0) {
726 		kgpio->kgpio_flags &= ~KGPIO_F_MINOR_VALID;
727 		(void) ddi_remove_minor_node(kgpio_g_dip, kgpio->kgpio_mname);
728 	}
729 	mutex_exit(&kgpio_g_mutex);
730 
731 	kgpio_cleanup(kgpio);
732 }
733 
734 static void
kgpio_unbind_cb(void * arg,dev_info_t * dip)735 kgpio_unbind_cb(void *arg, dev_info_t *dip)
736 {
737 	kgpio_t *kgpio = arg;
738 
739 	/*
740 	 * We have reached here because a driver that was registered with us is
741 	 * actually going away. As such it is now time for us to finally let go
742 	 * of it and free it so as to no longer attempt to keep it around and
743 	 * reattach it. At this point in time we are still in the context of the
744 	 * detaching thread in the devinfo tree. As such, here we note that it
745 	 * is going away and in the system taskq do the work to finish cleaning
746 	 * it up. After this point it cannot be looked up and held, so only
747 	 * existing opens that are racing with us will be here.
748 	 */
749 	mutex_enter(&kgpio_g_mutex);
750 	list_remove(&kgpio_g_gpios, kgpio);
751 	avl_remove(&kgpio_g_minors, &kgpio->kgpio_minor);
752 	kgpio->kgpio_flags |= KGPIO_F_REMOVED;
753 	mutex_exit(&kgpio_g_mutex);
754 
755 	(void) taskq_dispatch(system_taskq, kgpio_unbind_taskq, kgpio,
756 	    TQ_SLEEP);
757 }
758 
759 int
kgpio_unregister(dev_info_t * dip)760 kgpio_unregister(dev_info_t *dip)
761 {
762 	kgpio_t *kgpio;
763 
764 	if (dip == NULL) {
765 		return (EINVAL);
766 	}
767 
768 	if (!DEVI_IS_ATTACHING(dip) && !DEVI_IS_DETACHING(dip)) {
769 		return (EAGAIN);
770 	}
771 
772 	mutex_enter(&kgpio_g_mutex);
773 	kgpio = kgpio_find_by_dip(dip);
774 	if (kgpio == NULL) {
775 		mutex_exit(&kgpio_g_mutex);
776 		return (ENOENT);
777 	}
778 	kgpio->kgpio_flags &= ~KGPIO_F_VALID;
779 	mutex_exit(&kgpio_g_mutex);
780 
781 	return (0);
782 }
783 
784 /*
785  * Attempt to create a minor node for the kgpio. Because of the fact that the
786  * producer can register before we have a dev_info_t there's not a lot we can do
787  * other than complain and hope someone notices on failure.
788  */
789 static void
kgpio_create_minor(kgpio_t * kgpio)790 kgpio_create_minor(kgpio_t *kgpio)
791 {
792 	ASSERT(MUTEX_HELD(&kgpio->kgpio_mutex));
793 
794 	if (ddi_create_minor_node(kgpio_g_dip, kgpio->kgpio_mname, S_IFCHR,
795 	    (minor_t)kgpio->kgpio_minor.kminor_id, DDI_NT_GPIO_CTRL, 0) != 0) {
796 		dev_err(kgpio_g_dip, CE_WARN, "failed to create minor node "
797 		    "%s", kgpio->kgpio_mname);
798 	} else {
799 		kgpio->kgpio_flags |= KGPIO_F_MINOR_VALID;
800 	}
801 }
802 
803 int
kgpio_register(dev_info_t * dip,const kgpio_ops_t * ops,void * arg,uint32_t ngpio)804 kgpio_register(dev_info_t *dip, const kgpio_ops_t *ops, void *arg,
805     uint32_t ngpio)
806 {
807 	kgpio_t *kgpio;
808 
809 	if (dip == NULL || ops == NULL || ops->kgo_get == NULL ||
810 	    ops->kgo_set == NULL || ngpio == 0) {
811 		return (EINVAL);
812 	}
813 
814 	if (!DEVI_IS_ATTACHING(dip)) {
815 		return (EAGAIN);
816 	}
817 
818 	mutex_enter(&kgpio_g_mutex);
819 	kgpio = kgpio_find_by_dip(dip);
820 	if (kgpio != NULL) {
821 		mutex_enter(&kgpio->kgpio_mutex);
822 		if ((kgpio->kgpio_flags & KGPIO_F_VALID) != 0) {
823 			mutex_exit(&kgpio->kgpio_mutex);
824 			mutex_exit(&kgpio_g_mutex);
825 			return (EEXIST);
826 		}
827 
828 		if (kgpio->kgpio_ngpios != ngpio) {
829 			dev_err(dip, CE_WARN, "failed to register with gpio "
830 			    "framework, number of GPIOs changed from %u to %u",
831 			    kgpio->kgpio_ngpios, ngpio);
832 			mutex_exit(&kgpio->kgpio_mutex);
833 			mutex_exit(&kgpio_g_mutex);
834 			return (ESTALE);
835 		}
836 
837 		/*
838 		 * We've found a match for this gpio. Assume that the pointers
839 		 * it's given us have changed, but otherwise, we don't need to
840 		 * recreate anything in the kgpio_t.
841 		 */
842 		kgpio->kgpio_flags |= KGPIO_F_VALID;
843 		kgpio->kgpio_ops = ops;
844 		kgpio->kgpio_drv = arg;
845 		mutex_exit(&kgpio->kgpio_mutex);
846 		mutex_exit(&kgpio_g_mutex);
847 		return (0);
848 	}
849 
850 	kgpio = kmem_zalloc(sizeof (kgpio_t), KM_SLEEP);
851 	kgpio->kgpio_dip = dip;
852 	kgpio->kgpio_ngpios = ngpio;
853 	kgpio->kgpio_ops = ops;
854 	kgpio->kgpio_drv = arg;
855 
856 	mutex_init(&kgpio->kgpio_mutex, NULL, MUTEX_DRIVER, NULL);
857 	cv_init(&kgpio->kgpio_cv, NULL, CV_DRIVER, NULL);
858 
859 	if (snprintf(kgpio->kgpio_mname, sizeof (kgpio->kgpio_mname), "%s%d",
860 	    ddi_driver_name(dip), ddi_get_instance(dip)) >=
861 	    sizeof (kgpio->kgpio_mname)) {
862 		mutex_exit(&kgpio_g_mutex);
863 		dev_err(dip, CE_WARN, "failed to register with gpio framework: "
864 		    "controller minor name overflow");
865 		kgpio_cleanup(kgpio);
866 		return (EOVERFLOW);
867 	}
868 
869 	kgpio->kgpio_minor.kminor_id = id_alloc_nosleep(kgpio_g_ids);
870 	if (kgpio->kgpio_minor.kminor_id == -1) {
871 		mutex_exit(&kgpio_g_mutex);
872 		kgpio_cleanup(kgpio);
873 		return (ENOSPC);
874 	}
875 	kgpio->kgpio_minor.kminor_type = KGPIO_MINOR_T_CTRL;
876 	kgpio->kgpio_minor.kminor_data.kminor_ctrl = kgpio;
877 
878 	kgpio->kgpio_cb.ddiub_cb = kgpio_unbind_cb;
879 	kgpio->kgpio_cb.ddiub_arg = kgpio;
880 	e_ddi_register_unbind_callback(dip, &kgpio->kgpio_cb);
881 	kgpio->kgpio_flags |= KGPIO_F_VALID;
882 
883 	/*
884 	 * At this point the kgpio_t is set up. The last thing we need to see is
885 	 * if we actually have our dev_info_t so we can create minors. It is
886 	 * possible for this not to be the case when the first gpio provider is
887 	 * attaching because the krtld reference only guarantees that the kgpio
888 	 * _init() entry point has been called and not attach. We attempt to use
889 	 * a ddi-forceattach attribute to make this less likely.
890 	 */
891 	if (kgpio_g_dip != NULL) {
892 		mutex_enter(&kgpio->kgpio_mutex);
893 		kgpio_create_minor(kgpio);
894 		mutex_exit(&kgpio->kgpio_mutex);
895 	}
896 
897 	list_insert_tail(&kgpio_g_gpios, kgpio);
898 	avl_add(&kgpio_g_minors, &kgpio->kgpio_minor);
899 
900 	mutex_exit(&kgpio_g_mutex);
901 
902 	return (0);
903 }
904 
905 void
kgpio_nvl_attr_fill_str(nvlist_t * nvl,nvlist_t * meta,const char * key,const char * val,uint_t npos,char * const * pos,kgpio_prot_t prot)906 kgpio_nvl_attr_fill_str(nvlist_t *nvl, nvlist_t *meta, const char *key,
907     const char *val, uint_t npos, char *const *pos, kgpio_prot_t prot)
908 {
909 	nvlist_t *info = fnvlist_alloc();
910 
911 	fnvlist_add_string(nvl, key, val);
912 
913 	fnvlist_add_uint32(info, KGPIO_ATTR_PROT, (uint32_t)prot);
914 	if (npos > 0) {
915 		fnvlist_add_string_array(info, KGPIO_ATTR_POS, pos, npos);
916 	}
917 	fnvlist_add_nvlist(meta, key, info);
918 	fnvlist_free(info);
919 
920 }
921 
922 void
kgpio_nvl_attr_fill_u32(nvlist_t * nvl,nvlist_t * meta,const char * key,uint32_t val,uint_t npos,uint32_t * pos,kgpio_prot_t prot)923 kgpio_nvl_attr_fill_u32(nvlist_t *nvl, nvlist_t *meta, const char *key,
924     uint32_t val, uint_t npos, uint32_t *pos, kgpio_prot_t prot)
925 {
926 	nvlist_t *info = fnvlist_alloc();
927 
928 	fnvlist_add_uint32(nvl, key, val);
929 
930 	fnvlist_add_uint32(info, KGPIO_ATTR_PROT, (uint32_t)prot);
931 	if (npos > 0) {
932 		fnvlist_add_uint32_array(info, KGPIO_ATTR_POS, pos, npos);
933 	}
934 	fnvlist_add_nvlist(meta, key, info);
935 	fnvlist_free(info);
936 }
937 
938 static void
kgpio_release(kgpio_t * kgpio)939 kgpio_release(kgpio_t *kgpio)
940 {
941 	ddi_release_devi(kgpio->kgpio_dip);
942 
943 	mutex_enter(&kgpio->kgpio_mutex);
944 	VERIFY(kgpio->kgpio_flags & KGPIO_F_HELD);
945 	kgpio->kgpio_flags &= ~KGPIO_F_HELD;
946 	mutex_exit(&kgpio->kgpio_mutex);
947 }
948 
949 static void
kgpio_release_meta(kgpio_t * kgpio)950 kgpio_release_meta(kgpio_t *kgpio)
951 {
952 	mutex_enter(&kgpio->kgpio_mutex);
953 	VERIFY(kgpio->kgpio_flags & KGPIO_F_META_WORK);
954 	kgpio->kgpio_flags &= ~KGPIO_F_META_WORK;
955 	cv_broadcast(&kgpio->kgpio_cv);
956 	mutex_exit(&kgpio->kgpio_mutex);
957 }
958 
959 static int
kgpio_hold_by_id(id_t id)960 kgpio_hold_by_id(id_t id)
961 {
962 	kgpio_t *kgpio;
963 	dev_info_t *pdip;
964 	kgpio_minor_t *minor;
965 
966 restart:
967 	mutex_enter(&kgpio_g_mutex);
968 	minor = kgpio_minor_find(id);
969 	if (minor == NULL) {
970 		mutex_exit(&kgpio_g_mutex);
971 		return (ESTALE);
972 	}
973 	if (minor->kminor_type != KGPIO_MINOR_T_CTRL) {
974 		mutex_exit(&kgpio_g_mutex);
975 		return (ENXIO);
976 	}
977 	kgpio = minor->kminor_data.kminor_ctrl;
978 
979 	mutex_enter(&kgpio->kgpio_mutex);
980 	if ((kgpio->kgpio_flags & KGPIO_F_REMOVED) != 0) {
981 		mutex_exit(&kgpio->kgpio_mutex);
982 		mutex_exit(&kgpio_g_mutex);
983 		return (ESTALE);
984 	}
985 
986 	/*
987 	 * First, check if the node that we're looking at is both active and
988 	 * held. If it is then there is nothing more that we need to do and can
989 	 * acknowledge the open. We don't need to account for how many folks
990 	 * have opened it due to the kernel's accounting.
991 	 */
992 	if ((kgpio->kgpio_flags & (KGPIO_F_VALID | KGPIO_F_HELD)) ==
993 	    (KGPIO_F_VALID | KGPIO_F_HELD)) {
994 		mutex_exit(&kgpio->kgpio_mutex);
995 		mutex_exit(&kgpio_g_mutex);
996 		return (0);
997 	}
998 
999 	/*
1000 	 * This driver is either inactive and needs to be attached or it's not
1001 	 * held. In either case we need to make sure that only one open(9E) can
1002 	 * end up in here at a time. Note, while doing all this we drop the
1003 	 * global and local lock. This will cause us to restart this entire
1004 	 * loop.
1005 	 */
1006 	if ((kgpio->kgpio_flags & KGPIO_F_META_WORK) != 0) {
1007 		mutex_exit(&kgpio_g_mutex);
1008 		while ((kgpio->kgpio_flags & KGPIO_F_META_WORK) != 0) {
1009 			int cv = cv_wait_sig(&kgpio->kgpio_cv,
1010 			    &kgpio->kgpio_mutex);
1011 			if (cv == 0) {
1012 				mutex_exit(&kgpio->kgpio_mutex);
1013 				return (EINTR);
1014 			}
1015 		}
1016 
1017 		/*
1018 		 * We're no longer waiting. However, we basically have to take
1019 		 * another lap through here to check through all the core state
1020 		 * again because we dropped the kgpio_g_mutex.
1021 		 */
1022 		mutex_exit(&kgpio->kgpio_mutex);
1023 		goto restart;
1024 	}
1025 
1026 	/*
1027 	 * At this point we can obtain ownership for performing meta work on
1028 	 * this kgpio. Once we claim this we will need to drop our locks and
1029 	 * related to perform all of the related NDI operations. However,
1030 	 * because the meta work flag is set, this structure can't disappear.
1031 	 */
1032 	kgpio->kgpio_flags |= KGPIO_F_META_WORK;
1033 	pdip = ddi_get_parent(kgpio->kgpio_dip);
1034 	mutex_exit(&kgpio->kgpio_mutex);
1035 	mutex_exit(&kgpio_g_mutex);
1036 
1037 	/*
1038 	 * This is required to ensure that the driver can't go away.
1039 	 */
1040 	ndi_devi_enter(pdip);
1041 	e_ddi_hold_devi(kgpio->kgpio_dip);
1042 	ndi_devi_exit(pdip);
1043 
1044 	/*
1045 	 * Because we dropped the main lock, we need to see if we lost a race
1046 	 * again and if so unwind.
1047 	 */
1048 	mutex_enter(&kgpio->kgpio_mutex);
1049 	kgpio->kgpio_flags |= KGPIO_F_HELD;
1050 	if ((kgpio->kgpio_flags & KGPIO_F_REMOVED) != 0) {
1051 		mutex_exit(&kgpio->kgpio_mutex);
1052 		kgpio_release(kgpio);
1053 		kgpio_release_meta(kgpio);
1054 		return (ESTALE);
1055 	}
1056 
1057 	/*
1058 	 * If the instance isn't valid yet, try to go and prod it via the NDI to
1059 	 * wake up. This needs to happen if an instance gets detached, for
1060 	 * example.
1061 	 */
1062 	if ((kgpio->kgpio_flags & KGPIO_F_VALID) == 0) {
1063 		mutex_exit(&kgpio->kgpio_mutex);
1064 		(void) ndi_devi_config(pdip, NDI_NO_EVENT);
1065 		mutex_enter(&kgpio->kgpio_mutex);
1066 
1067 		/*
1068 		 * Check one last time for validity. If this has failed or its
1069 		 * been removed, finally give up.
1070 		 */
1071 		ASSERT(kgpio->kgpio_flags & KGPIO_F_META_WORK);
1072 		if ((kgpio->kgpio_flags & KGPIO_F_REMOVED) != 0 ||
1073 		    (kgpio->kgpio_flags & KGPIO_F_VALID) == 0) {
1074 			mutex_exit(&kgpio->kgpio_mutex);
1075 			kgpio_release(kgpio);
1076 			kgpio_release_meta(kgpio);
1077 			return (ESTALE);
1078 		}
1079 	}
1080 
1081 	/*
1082 	 * OK, at this point we actually did it. We should be both VALID and
1083 	 * HELD. We can release the meta work flag and we now should be good to
1084 	 * go.
1085 	 */
1086 	ASSERT(kgpio->kgpio_flags & KGPIO_F_META_WORK);
1087 	ASSERT(kgpio->kgpio_flags & KGPIO_F_HELD);
1088 	ASSERT(kgpio->kgpio_flags & KGPIO_F_VALID);
1089 	mutex_exit(&kgpio->kgpio_mutex);
1090 
1091 	kgpio_release_meta(kgpio);
1092 
1093 	return (0);
1094 }
1095 
1096 static int
kgpio_open(dev_t * devp,int flag,int otyp,cred_t * credp)1097 kgpio_open(dev_t *devp, int flag, int otyp, cred_t *credp)
1098 {
1099 	kgpio_minor_t *minor;
1100 	dpio_t *dpio;
1101 
1102 	if (drv_priv(credp) != 0)
1103 		return (EPERM);
1104 
1105 	mutex_enter(&kgpio_g_mutex);
1106 	minor = kgpio_minor_find((id_t)getminor(*devp));
1107 	if (minor == NULL) {
1108 		mutex_exit(&kgpio_g_mutex);
1109 		return (ESTALE);
1110 	}
1111 
1112 	switch (minor->kminor_type) {
1113 	case KGPIO_MINOR_T_CTRL:
1114 		/*
1115 		 * Opening a controller is awkward. By definition we have a
1116 		 * valid minor number and we have kgpio; however, depending on
1117 		 * the state of the actual controller it may not be held right
1118 		 * now. In addition, while we have found a minor right now for
1119 		 * this, when we go to potentially reattach it, if required, it
1120 		 * may disappear. So, as weird as this is, now that we believe
1121 		 * that this is a controller, we're going to call into the kgpio
1122 		 * hold logic, which will itself end up taking and dropping the
1123 		 * global locks across ndi calls. This mean that we're going to
1124 		 * drop the lock and must ignore the minor we just found. This
1125 		 * is ok, because the hold logic will validate the type and
1126 		 * related again.
1127 		 */
1128 		mutex_exit(&kgpio_g_mutex);
1129 
1130 		if (otyp != OTYP_CHR)
1131 			return (ENOTSUP);
1132 
1133 		if ((flag & (FNDELAY | FNONBLOCK | FEXCL)) != 0)
1134 			return (EINVAL);
1135 
1136 		if ((flag & FREAD) != FREAD)
1137 			return (EINVAL);
1138 
1139 		return (kgpio_hold_by_id((id_t)getminor(*devp)));
1140 	case KGPIO_MINOR_T_DPIO:
1141 		dpio = minor->kminor_data.kminor_dpio;
1142 		mutex_enter(&dpio->dpio_mutex);
1143 		mutex_exit(&kgpio_g_mutex);
1144 
1145 		/*
1146 		 * Verify the basics that we expect for a DPIO.
1147 		 *  o It must be a character device.
1148 		 *  o If a DPIO has been flagged with requiring kernel access
1149 		 *    then FKLYR must be specified. If it is not, then it is an
1150 		 *    error.
1151 		 *  o We don't care about FNDELAY | FNONBLOCK, they will be
1152 		 *    honored for read(9E) and write(9E) and checked in the
1153 		 *    uio(9S).
1154 		 *  o If the DPIO_S_EXCL status flag is set, then we have to
1155 		 *    return that this device is already busy.
1156 		 *  o If someone has asked for FEXCL, it is only allowed to
1157 		 *    succeed if the device isn't already open.
1158 		 */
1159 		if ((dpio->dpio_flags & DPIO_F_KERNEL) != 0 &&
1160 		    (flag & FKLYR) == 0) {
1161 			mutex_exit(&dpio->dpio_mutex);
1162 			return (EPERM);
1163 		}
1164 
1165 		if (otyp != OTYP_CHR) {
1166 			mutex_exit(&dpio->dpio_mutex);
1167 			return (ENOTSUP);
1168 		}
1169 
1170 		if ((dpio->dpio_status & DPIO_S_EXCL) != 0) {
1171 			mutex_exit(&dpio->dpio_mutex);
1172 			return (EBUSY);
1173 		}
1174 
1175 		if ((flag & FEXCL) != 0) {
1176 			if ((dpio->dpio_status & DPIO_S_OPEN) != 0) {
1177 				mutex_exit(&dpio->dpio_mutex);
1178 				return (EBUSY);
1179 			}
1180 			dpio->dpio_status |= DPIO_S_EXCL;
1181 		}
1182 
1183 		dpio->dpio_status |= DPIO_S_OPEN;
1184 		mutex_exit(&dpio->dpio_mutex);
1185 		return (0);
1186 	case KGPIO_MINOR_T_DPINFO:
1187 		mutex_exit(&kgpio_g_mutex);
1188 
1189 		/*
1190 		 * For the DPIO Information device, this really just is used to
1191 		 * get information and read-only ioctls. There is no special
1192 		 * support for anything here. We do require read access as
1193 		 * without that there isn't much to really do.
1194 		 */
1195 		if (otyp != OTYP_CHR) {
1196 			return (ENOTSUP);
1197 		}
1198 
1199 		if ((flag & (FNDELAY | FNONBLOCK | FEXCL)) != 0) {
1200 			return (EINVAL);
1201 		}
1202 
1203 		if ((flag & FREAD) != FREAD) {
1204 			return (EINVAL);
1205 		}
1206 
1207 		return (0);
1208 	default:
1209 		mutex_exit(&kgpio_g_mutex);
1210 		return (ENXIO);
1211 	}
1212 }
1213 
1214 static int
kgpio_ioctl_ctrl_info(kgpio_t * kgpio,intptr_t arg,int mode)1215 kgpio_ioctl_ctrl_info(kgpio_t *kgpio, intptr_t arg, int mode)
1216 {
1217 	kgpio_ctrl_info_t info;
1218 
1219 	ASSERT(MUTEX_HELD(&kgpio->kgpio_mutex));
1220 
1221 	if ((mode & FREAD) == 0) {
1222 		return (EBADF);
1223 	}
1224 
1225 	bzero(&info, sizeof (info));
1226 	info.kci_ngroups = 0;
1227 	info.kci_ngpios = kgpio->kgpio_ngpios;
1228 	info.kci_ndpios = kgpio->kgpio_ndpios;
1229 	(void) ddi_pathname(kgpio->kgpio_dip, info.kci_devpath);
1230 
1231 	if (ddi_copyout(&info, (void *)arg, sizeof (info), mode & FKIOCTL) !=
1232 	    0) {
1233 		return (EFAULT);
1234 	}
1235 
1236 	return (0);
1237 }
1238 
1239 static int
kgpio_ioctl_gpio_info(kgpio_t * kgpio,intptr_t arg,int mode)1240 kgpio_ioctl_gpio_info(kgpio_t *kgpio, intptr_t arg, int mode)
1241 {
1242 	int ret;
1243 	uint_t model;
1244 	char *pack = NULL;
1245 	size_t pack_size = 0;
1246 	kgpio_gpio_info_t info;
1247 #ifdef	_MULTI_DATAMODEL
1248 	kgpio_gpio_info32_t info32;
1249 #endif
1250 
1251 	ASSERT(MUTEX_HELD(&kgpio->kgpio_mutex));
1252 
1253 	if ((mode & FREAD) == 0) {
1254 		return (EBADF);
1255 	}
1256 
1257 	model = ddi_model_convert_from(mode);
1258 	switch (model) {
1259 #ifdef	_MULTI_DATAMODEL
1260 	case DDI_MODEL_ILP32:
1261 		if (ddi_copyin((void *)arg, &info32, sizeof (info32),
1262 		    mode & FKIOCTL) != 0) {
1263 			return (EFAULT);
1264 		}
1265 
1266 		info.kgi_id = info32.kgi_id;
1267 		info.kgi_flags = info32.kgi_flags;
1268 		info.kgi_attr = info32.kgi_attr;
1269 		info.kgi_attr_len = info32.kgi_attr_len;
1270 		break;
1271 #endif	/* _MULTI_DATAMODEL */
1272 	case DDI_MODEL_NONE:
1273 		if (ddi_copyin((void *)arg, &info, sizeof (info),
1274 		    mode & FKIOCTL) != 0) {
1275 			return (EFAULT);
1276 		}
1277 		break;
1278 	default:
1279 		return (ENOTSUP);
1280 	}
1281 
1282 	if (info.kgi_id >= kgpio->kgpio_ngpios) {
1283 		return (ENOENT);
1284 	}
1285 
1286 	nvlist_t *attr = fnvlist_alloc();
1287 	ret = kgpio->kgpio_ops->kgo_get(kgpio->kgpio_drv, info.kgi_id, attr);
1288 	if (ret != 0) {
1289 		goto out;
1290 	}
1291 
1292 	pack = fnvlist_pack(attr, &pack_size);
1293 	if (info.kgi_attr_len >= pack_size) {
1294 		if (ddi_copyout(pack, (void *)info.kgi_attr, pack_size,
1295 		    mode & FKIOCTL) != 0) {
1296 			ret = EFAULT;
1297 			goto out;
1298 		}
1299 		ret = 0;
1300 	} else {
1301 		ret = EOVERFLOW;
1302 	}
1303 
1304 	info.kgi_attr_len = pack_size;
1305 	switch (model) {
1306 #ifdef	_MULTI_DATAMODEL
1307 	case DDI_MODEL_ILP32:
1308 		if (info.kgi_attr_len > UINT32_MAX) {
1309 			info32.kgi_attr_len = UINT32_MAX;
1310 			ret = EOVERFLOW;
1311 		} else {
1312 			info32.kgi_attr_len = info.kgi_attr_len;
1313 		}
1314 
1315 		if (ddi_copyout(&info32, (void *)arg, sizeof (info32),
1316 		    mode & FKIOCTL) != 0) {
1317 			ret = EFAULT;
1318 			goto out;
1319 		}
1320 		break;
1321 #endif	/* _MULTI_DATAMODEL */
1322 	case DDI_MODEL_NONE:
1323 		if (ddi_copyout(&info, (void *)arg, sizeof (info),
1324 		    mode & FKIOCTL) != 0) {
1325 			ret = EFAULT;
1326 			goto out;
1327 		}
1328 	}
1329 
1330 out:
1331 	if (pack != NULL) {
1332 		ASSERT3U(pack_size, !=, 0);
1333 		fnvlist_pack_free(pack, pack_size);
1334 	}
1335 	nvlist_free(attr);
1336 	return (ret);
1337 }
1338 
1339 static int
kgpio_ioctl_gpio_update(kgpio_t * kgpio,intptr_t arg,int mode)1340 kgpio_ioctl_gpio_update(kgpio_t *kgpio, intptr_t arg, int mode)
1341 {
1342 	int ret;
1343 	uint_t model;
1344 	char *user_data = NULL;
1345 	nvlist_t *attr_nvl = NULL, *err_nvl = NULL;
1346 	kgpio_update_t kgu;
1347 #ifdef	_MULTI_DATAMODEL
1348 	kgpio_update32_t kgu32;
1349 #endif
1350 
1351 	ASSERT(MUTEX_HELD(&kgpio->kgpio_mutex));
1352 
1353 	if ((mode & FWRITE) == 0) {
1354 		return (EBADF);
1355 	}
1356 
1357 	model = ddi_model_convert_from(mode);
1358 	switch (model) {
1359 #ifdef	_MULTI_DATAMODEL
1360 	case DDI_MODEL_ILP32:
1361 		if (ddi_copyin((void *)arg, &kgu32, sizeof (kgu32),
1362 		    mode & FKIOCTL) != 0) {
1363 			return (EFAULT);
1364 		}
1365 
1366 		kgu.kgu_id = kgu32.kgu_id;
1367 		kgu.kgu_flags = kgu32.kgu_flags;
1368 		kgu.kgu_attr = kgu32.kgu_attr;
1369 		kgu.kgu_attr_len = kgu32.kgu_attr_len;
1370 		kgu.kgu_err = kgu32.kgu_err;
1371 		kgu.kgu_err_len = kgu32.kgu_err_len;
1372 		break;
1373 #endif	/* _MULTI_DATAMODEL */
1374 	case DDI_MODEL_NONE:
1375 		if (ddi_copyin((void *)arg, &kgu, sizeof (kgu),
1376 		    mode & FKIOCTL) != 0) {
1377 			return (EFAULT);
1378 		}
1379 		break;
1380 	default:
1381 		return (ENOTSUP);
1382 	}
1383 
1384 	/*
1385 	 * We need to go back and verify that this GPIO doesn't correspond to a
1386 	 * DPIO at all. This means we need the global mutex again. It's safe for
1387 	 * us to drop and reacquire the kgpio's lock as because we're in the
1388 	 * context of the open device, it can't go away.
1389 	 */
1390 	mutex_exit(&kgpio->kgpio_mutex);
1391 	mutex_enter(&kgpio_g_mutex);
1392 	mutex_enter(&kgpio->kgpio_mutex);
1393 
1394 	for (dpio_t *dpio = list_head(&kgpio_g_dpios); dpio != NULL;
1395 	    dpio = list_next(&kgpio_g_dpios, dpio)) {
1396 		if (dpio->dpio_kgpio == kgpio &&
1397 		    dpio->dpio_gpio_num == kgu.kgu_id) {
1398 			mutex_exit(&kgpio_g_mutex);
1399 			return (EROFS);
1400 		}
1401 	}
1402 	mutex_exit(&kgpio_g_mutex);
1403 
1404 	if (kgu.kgu_attr_len > kgpio_max_user_nvl) {
1405 		return (E2BIG);
1406 	}
1407 
1408 	if (kgu.kgu_id >= kgpio->kgpio_ngpios) {
1409 		return (ENOENT);
1410 	}
1411 
1412 	user_data = kmem_alloc(kgpio_max_user_nvl, KM_NOSLEEP_LAZY);
1413 	if (user_data == NULL) {
1414 		return (ENOMEM);
1415 	}
1416 
1417 	if (ddi_copyin((void *)kgu.kgu_attr, user_data, kgu.kgu_attr_len,
1418 	    mode & FKIOCTL) != 0) {
1419 		ret = EFAULT;
1420 		goto err;
1421 	}
1422 
1423 	if (nvlist_unpack(user_data, kgu.kgu_attr_len, &attr_nvl, 0) != 0) {
1424 		ret = EINVAL;
1425 		goto err;
1426 	}
1427 
1428 	err_nvl = fnvlist_alloc();
1429 	ret = kgpio->kgpio_ops->kgo_set(kgpio->kgpio_drv, kgu.kgu_id, attr_nvl,
1430 	    err_nvl);
1431 	/*
1432 	 * If this failed and we had an error nvlist, then we don't return an
1433 	 * errno and instead translate this into the structure that we copy out.
1434 	 * We always zero out the flags and then will set what appropriate bits
1435 	 * we need. This next if statement will zero out ret, indicating to us
1436 	 * that we should attempt to copy out this structure. If anything in the
1437 	 * process of trying to copy out errors fails, then we don't worry about
1438 	 * that and return a larger error because that is indicative of failure
1439 	 * it just means userland can't get as much info as we wished.
1440 	 */
1441 	kgu.kgu_flags = 0;
1442 	if (ret != 0 && nvlist_next_nvpair(err_nvl, NULL) != NULL) {
1443 		size_t err_len;
1444 
1445 		kgu.kgu_flags |= KGPIO_UPDATE_ERROR;
1446 		ret = nvlist_size(err_nvl, &err_len, NV_ENCODE_NATIVE);
1447 
1448 		if (ret == 0 && err_len <= MIN(kgu.kgu_err_len,
1449 		    kgpio_max_user_nvl)) {
1450 			ret = nvlist_pack(err_nvl, &user_data, &err_len,
1451 			    NV_ENCODE_NATIVE, 0);
1452 			if (ret != 0) {
1453 				goto err;
1454 			}
1455 
1456 			kgu.kgu_err_len = err_len;
1457 			if (ddi_copyout(user_data, (void *)kgu.kgu_err, err_len,
1458 			    mode & FKIOCTL) != 0) {
1459 				ret = EFAULT;
1460 			} else {
1461 				kgu.kgu_flags |= KGPIO_UPDATE_ERR_NVL_VALID;
1462 				ret = 0;
1463 			}
1464 		}
1465 	}
1466 
1467 	if (ret != 0) {
1468 		goto err;
1469 	}
1470 
1471 	switch (model) {
1472 #ifdef	_MULTI_DATAMODEL
1473 	case DDI_MODEL_ILP32:
1474 		/*
1475 		 * Other values should still hold from copyin, hence we only
1476 		 * update those that we would have changed here.
1477 		 */
1478 		kgu32.kgu_flags = kgu.kgu_flags;
1479 		kgu32.kgu_err_len = kgu.kgu_err_len;
1480 
1481 		if (ddi_copyout(&kgu32, (void *)arg, sizeof (kgu32),
1482 		    mode & FKIOCTL) != 0) {
1483 			ret = EFAULT;
1484 		}
1485 		break;
1486 #endif	/* _MULTI_DATAMODEL */
1487 	case DDI_MODEL_NONE:
1488 		if (ddi_copyout(&kgu, (void *)arg, sizeof (kgu),
1489 		    mode & FKIOCTL) != 0) {
1490 			ret = EFAULT;
1491 		}
1492 		break;
1493 	default:
1494 		ret = ENOTSUP;
1495 	}
1496 
1497 err:
1498 	if (err_nvl != NULL) {
1499 		nvlist_free(err_nvl);
1500 	}
1501 
1502 	if (attr_nvl != NULL) {
1503 		nvlist_free(attr_nvl);
1504 	}
1505 
1506 	if (user_data != NULL) {
1507 		kmem_free(user_data, kgpio_max_user_nvl);
1508 	}
1509 	return (ret);
1510 }
1511 
1512 static bool
kgpio_valid_name(const char * name,size_t buflen)1513 kgpio_valid_name(const char *name, size_t buflen)
1514 {
1515 	size_t i;
1516 
1517 	for (i = 0; i < buflen; i++) {
1518 		if (name[i] == '\0')
1519 			break;
1520 
1521 		/*
1522 		 * Right now we constrain GPIO names to be alphanumeric and
1523 		 * allow for separators to exist. However, for file system
1524 		 * simplicity we constrain the first character to be
1525 		 * alphanumeric.
1526 		 */
1527 		if (i == 0 && !isalnum(name[i])) {
1528 			return (false);
1529 		} else if (!isalnum(name[i]) && name[i] != '_' &&
1530 		    name[i] != '.' && name[i] != '-' && name[i] != '+') {
1531 			return (false);
1532 		}
1533 	}
1534 
1535 	if (i == 0 || i == buflen) {
1536 		return (false);
1537 	}
1538 
1539 	return (true);
1540 }
1541 
1542 static int
kgpio_ioctl_dpio_create(kgpio_t * kgpio,intptr_t arg,int mode)1543 kgpio_ioctl_dpio_create(kgpio_t *kgpio, intptr_t arg, int mode)
1544 {
1545 	int ret;
1546 	dpio_caps_t sup_caps, caps = 0;
1547 	const kgpio_dpio_flags_t all_flags = KGPIO_DPIO_F_READ |
1548 	    KGPIO_DPIO_F_WRITE | KGPIO_DPIO_F_KERNEL;
1549 	kgpio_dpio_create_t create;
1550 	char name[KGPIO_DPIO_INT_NAMELEN];
1551 	size_t namelen;
1552 
1553 	ASSERT(MUTEX_HELD(&kgpio->kgpio_mutex));
1554 
1555 	if ((mode & FWRITE) == 0) {
1556 		return (EBADF);
1557 	}
1558 
1559 	if (ddi_copyin((void *)arg, &create, sizeof (kgpio_dpio_create_t),
1560 	    mode & FKIOCTL) != 0) {
1561 		return (EFAULT);
1562 	}
1563 
1564 	if (create.kdc_id >= kgpio->kgpio_ngpios) {
1565 		return (ENOENT);
1566 	}
1567 
1568 	if (!kgpio_valid_name(create.kdc_name, sizeof (create.kdc_name))) {
1569 		return (EINVAL);
1570 	}
1571 	namelen = snprintf(name, sizeof (name), "dpio:%s", create.kdc_name);
1572 	ASSERT3U(namelen, <, KGPIO_DPIO_INT_NAMELEN);
1573 
1574 	/*
1575 	 * It is perfectly fine to create a DPIO with no flags. That is then
1576 	 * something which is constrained with its current attributes, providing
1577 	 * the system guarantees that it should not change, though it is a
1578 	 * little weird.
1579 	 */
1580 	if ((create.kdc_flags & ~all_flags) != 0) {
1581 		return (EINVAL);
1582 	}
1583 
1584 	if (kgpio->kgpio_ops->kgo_cap == NULL) {
1585 		return (ENOTSUP);
1586 	}
1587 	ret = kgpio->kgpio_ops->kgo_cap(kgpio->kgpio_drv, create.kdc_id,
1588 	    &sup_caps);
1589 	if (ret != 0) {
1590 		return (ret);
1591 	}
1592 
1593 	if ((create.kdc_flags & KGPIO_DPIO_F_READ) != 0) {
1594 		if (kgpio->kgpio_ops->kgo_input == NULL ||
1595 		    (sup_caps & DPIO_C_READ) == 0) {
1596 			return (ENOTSUP);
1597 		}
1598 		caps |= DPIO_C_READ;
1599 	}
1600 
1601 	if ((create.kdc_flags & KGPIO_DPIO_F_WRITE) != 0) {
1602 		if (kgpio->kgpio_ops->kgo_output_state == NULL ||
1603 		    kgpio->kgpio_ops->kgo_output == NULL ||
1604 		    (sup_caps & DPIO_C_WRITE) == 0) {
1605 			return (ENOTSUP);
1606 		}
1607 		caps |= DPIO_C_WRITE;
1608 	}
1609 
1610 	if ((caps & DPIO_C_READ) != 0 && (sup_caps & DPIO_C_POLL) != 0) {
1611 		caps |= DPIO_C_POLL;
1612 	}
1613 
1614 	/*
1615 	 * At this point, everything that we have for the DPIO is valid. The
1616 	 * remaining things we need to try and do are:
1617 	 *
1618 	 *  o Ensure that there isn't a DPIO with this name already.
1619 	 *  o Ensure that there isn't a DPIO already using this particular
1620 	 *    GPIO.
1621 	 *  o Create our DPIO structure, get underlying caps, and ultimately
1622 	 *    create our minor.
1623 	 *
1624 	 * To do this, we need to acquire the global lock to ensure that we
1625 	 * don't end up racing with anyone else. We've already gotten all
1626 	 * information that we need from the kgpio controller and because we
1627 	 * looked up and ensured the underlying controller is held, it should
1628 	 * not disappear on us as we drop the lock.
1629 	 */
1630 	mutex_exit(&kgpio->kgpio_mutex);
1631 	mutex_enter(&kgpio_g_mutex);
1632 	mutex_enter(&kgpio->kgpio_mutex);
1633 
1634 	for (dpio_t *dpio = list_head(&kgpio_g_dpios); dpio != NULL;
1635 	    dpio = list_next(&kgpio_g_dpios, dpio)) {
1636 		if (dpio->dpio_kgpio == kgpio &&
1637 		    dpio->dpio_gpio_num == create.kdc_id) {
1638 			mutex_exit(&kgpio_g_mutex);
1639 			return (EBUSY);
1640 		}
1641 
1642 		if (strcmp(name, dpio->dpio_name) == 0) {
1643 			mutex_exit(&kgpio_g_mutex);
1644 			return (EEXIST);
1645 		}
1646 	}
1647 
1648 	dpio_t *dpio = kmem_zalloc(sizeof (dpio_t), KM_NOSLEEP_LAZY);
1649 	if (dpio == NULL) {
1650 		mutex_exit(&kgpio_g_mutex);
1651 		return (ENOMEM);
1652 	}
1653 
1654 	dpio->dpio_kgpio = kgpio;
1655 	dpio->dpio_gpio_num = create.kdc_id;
1656 	dpio->dpio_caps = caps;
1657 	if ((create.kdc_flags & KGPIO_DPIO_F_KERNEL) != 0) {
1658 		dpio->dpio_flags |= DPIO_F_KERNEL;
1659 	}
1660 	/*
1661 	 * Note, we have a guarantee that the name length here is less than the
1662 	 * actual buffer size. The NUL termination comes from the kmem_zalloc
1663 	 * earlier.
1664 	 */
1665 	bcopy(name, dpio->dpio_name, namelen);
1666 	mutex_init(&dpio->dpio_mutex, NULL, MUTEX_DRIVER, NULL);
1667 
1668 	dpio->dpio_minor.kminor_id = id_alloc_nosleep(kgpio_g_ids);
1669 	if (dpio->dpio_minor.kminor_id == -1) {
1670 		mutex_exit(&kgpio_g_mutex);
1671 		kgpio_dpio_cleanup(dpio);
1672 		return (ENOSPC);
1673 	}
1674 	dpio->dpio_minor.kminor_type = KGPIO_MINOR_T_DPIO;
1675 	dpio->dpio_minor.kminor_data.kminor_dpio = dpio;
1676 
1677 	if (ddi_create_minor_node(kgpio_g_dip, dpio->dpio_name, S_IFCHR,
1678 	    (minor_t)dpio->dpio_minor.kminor_id, DDI_NT_GPIO_DPIO, 0) !=
1679 	    DDI_SUCCESS) {
1680 		mutex_exit(&kgpio_g_mutex);
1681 		kgpio_dpio_cleanup(dpio);
1682 		return (EIO);
1683 	}
1684 
1685 	list_insert_tail(&kgpio_g_dpios, dpio);
1686 	avl_add(&kgpio_g_minors, &dpio->dpio_minor);
1687 	kgpio->kgpio_ndpios++;
1688 	mutex_exit(&kgpio_g_mutex);
1689 
1690 	/*
1691 	 * This was successful, there is one last dance that we must do. We must
1692 	 * place a hold on the kgpio's dip. And of course, no lock holding
1693 	 * across the ndi hold.
1694 	 */
1695 	mutex_exit(&kgpio->kgpio_mutex);
1696 	e_ddi_hold_devi(kgpio->kgpio_dip);
1697 	mutex_enter(&kgpio->kgpio_mutex);
1698 
1699 	return (0);
1700 }
1701 
1702 static int
kgpio_ioctl_dpio_destroy(kgpio_t * kgpio,intptr_t arg,int mode)1703 kgpio_ioctl_dpio_destroy(kgpio_t *kgpio, intptr_t arg, int mode)
1704 {
1705 	dpio_t *dpio;
1706 	kgpio_dpio_destroy_t destroy;
1707 
1708 	ASSERT(MUTEX_HELD(&kgpio->kgpio_mutex));
1709 
1710 	if ((mode & FWRITE) == 0) {
1711 		return (EBADF);
1712 	}
1713 
1714 	if (ddi_copyin((void *)arg, &destroy, sizeof (kgpio_dpio_destroy_t),
1715 	    mode & FKIOCTL) != 0) {
1716 		return (EFAULT);
1717 	}
1718 
1719 	if (destroy.kdd_id >= kgpio->kgpio_ngpios) {
1720 		return (ENOENT);
1721 	}
1722 
1723 	mutex_exit(&kgpio->kgpio_mutex);
1724 	mutex_enter(&kgpio_g_mutex);
1725 	for (dpio = list_head(&kgpio_g_dpios); dpio != NULL;
1726 	    dpio = list_next(&kgpio_g_dpios, dpio)) {
1727 		if (dpio->dpio_kgpio == kgpio &&
1728 		    dpio->dpio_gpio_num == destroy.kdd_id) {
1729 			break;
1730 		}
1731 	}
1732 
1733 	if (dpio == NULL) {
1734 		mutex_enter(&kgpio->kgpio_mutex);
1735 		mutex_exit(&kgpio_g_mutex);
1736 		return (ENOENT);
1737 	}
1738 
1739 	if ((dpio->dpio_status & DPIO_S_OPEN) != 0) {
1740 		mutex_enter(&kgpio->kgpio_mutex);
1741 		mutex_exit(&kgpio_g_mutex);
1742 		return (EBUSY);
1743 	}
1744 
1745 	/*
1746 	 * OK, time to tear all this down. Remove it from global visibility as
1747 	 * it's not open. After this point, we no longer need the kgpio_g_lock.
1748 	 */
1749 	list_remove(&kgpio_g_dpios, dpio);
1750 	avl_remove(&kgpio_g_minors, &dpio->dpio_minor);
1751 	mutex_exit(&kgpio_g_mutex);
1752 
1753 	/*
1754 	 * At this point, it should be safe to destroy the dpio and then clean
1755 	 * up the remaining tracking on the kgpio. Over there, we need to need
1756 	 * to drop our corresponding hold and decrement the overall count.
1757 	 *
1758 	 * To ensure that devfs notices that the minor goes away, we basically
1759 	 * have to flag the directory for rebuild. As such, we do this somewhat
1760 	 * via a constrained max power way -- by asking it to clean up after
1761 	 * ourselves. This will of course be busy, but it does mean that a
1762 	 * rebuild flag will show up.
1763 	 */
1764 	kgpio_dpio_cleanup(dpio);
1765 	(void) devfs_clean(ddi_get_parent(kgpio_g_dip), "kgpio@0", 0);
1766 	ddi_release_devi(kgpio->kgpio_dip);
1767 
1768 	mutex_enter(&kgpio->kgpio_mutex);
1769 	VERIFY3P(kgpio->kgpio_ndpios, >, 0);
1770 	kgpio->kgpio_ndpios--;
1771 
1772 	return (0);
1773 }
1774 
1775 static int
kgpio_ioctl_dpio_info_common(const dpio_t * dpio,dpio_info_t * infop,intptr_t arg,int mode)1776 kgpio_ioctl_dpio_info_common(const dpio_t *dpio, dpio_info_t *infop,
1777     intptr_t arg, int mode)
1778 {
1779 	if ((mode & FREAD) == 0) {
1780 		return (EBADF);
1781 	}
1782 
1783 	bcopy(dpio->dpio_kgpio->kgpio_mname, infop->dpi_ctrl,
1784 	    sizeof (dpio->dpio_kgpio->kgpio_mname));
1785 	infop->dpi_gpio = dpio->dpio_gpio_num;
1786 	infop->dpi_caps = dpio->dpio_caps;
1787 	infop->dpi_flags = dpio->dpio_flags;
1788 
1789 	if (ddi_copyout(infop, (void *)arg, sizeof (dpio_info_t),
1790 	    mode & FKIOCTL) != 0) {
1791 		return (EFAULT);
1792 	}
1793 
1794 	return (0);
1795 }
1796 
1797 static int
kgpio_ioctl_dpio_info_specific(dpio_t * dpio,intptr_t arg,int mode)1798 kgpio_ioctl_dpio_info_specific(dpio_t *dpio, intptr_t arg, int mode)
1799 {
1800 	dpio_info_t info;
1801 
1802 	ASSERT(MUTEX_HELD(&dpio->dpio_mutex));
1803 
1804 	bzero(&info, sizeof (info));
1805 	bcopy(dpio->dpio_name, info.dpi_dpio, sizeof (dpio->dpio_name));
1806 	return (kgpio_ioctl_dpio_info_common(dpio, &info, arg, mode));
1807 }
1808 
1809 static int
kgpio_ioctl_dpio_time(dpio_t * dpio,intptr_t arg,int mode)1810 kgpio_ioctl_dpio_time(dpio_t *dpio, intptr_t arg, int mode)
1811 {
1812 	dpio_timing_t time;
1813 
1814 	ASSERT(MUTEX_HELD(&dpio->dpio_mutex));
1815 
1816 	if ((mode & FREAD) == 0) {
1817 		return (EBADF);
1818 	}
1819 
1820 	bzero(&time, sizeof (time));
1821 	time.dpt_last_input_intr = dpio->dpio_last_intr;
1822 	time.dpt_last_write = dpio->dpio_last_write;
1823 
1824 	if (ddi_copyout(&time, (void *)arg, sizeof (dpio_timing_t),
1825 	    mode & FKIOCTL) != 0) {
1826 		return (EFAULT);
1827 	}
1828 
1829 	return (0);
1830 }
1831 
1832 static int
kgpio_ioctl_dpio_curout(dpio_t * dpio,intptr_t arg,int mode)1833 kgpio_ioctl_dpio_curout(dpio_t *dpio, intptr_t arg, int mode)
1834 {
1835 	int ret;
1836 	dpio_curout_t curout;
1837 	kgpio_t *kgpio = dpio->dpio_kgpio;
1838 
1839 	ASSERT(MUTEX_HELD(&dpio->dpio_mutex));
1840 
1841 	if ((mode & FREAD) == 0) {
1842 		return (EBADF);
1843 	}
1844 
1845 	bzero(&curout, sizeof (curout));
1846 	if ((dpio->dpio_caps & DPIO_C_WRITE) == 0) {
1847 		return (ENOTSUP);
1848 	}
1849 
1850 	mutex_exit(&dpio->dpio_mutex);
1851 	mutex_enter(&kgpio->kgpio_mutex);
1852 	ret = kgpio->kgpio_ops->kgo_output_state(kgpio->kgpio_drv,
1853 	    dpio->dpio_gpio_num, &curout.dps_curout);
1854 	mutex_exit(&kgpio->kgpio_mutex);
1855 	mutex_enter(&dpio->dpio_mutex);
1856 
1857 	if (ret != 0) {
1858 		return (ret);
1859 
1860 	}
1861 
1862 	if (ddi_copyout(&curout, (void *)arg, sizeof (dpio_curout_t),
1863 	    mode & FKIOCTL) != 0) {
1864 		return (EFAULT);
1865 	}
1866 
1867 	return (0);
1868 }
1869 
1870 static int
kgpio_ioctl_dpio_info_search(intptr_t arg,int mode)1871 kgpio_ioctl_dpio_info_search(intptr_t arg, int mode)
1872 {
1873 	size_t len;
1874 	dpio_info_t info;
1875 
1876 	ASSERT(MUTEX_HELD(&kgpio_g_mutex));
1877 
1878 	if (ddi_copyin((void *)arg, &info, sizeof (dpio_info_t),
1879 	    mode & FKIOCTL) != 0) {
1880 		return (EFAULT);
1881 	}
1882 
1883 	len = strnlen(info.dpi_dpio, sizeof (info.dpi_dpio));
1884 	if (len == 0 || len == sizeof (info.dpi_dpio)) {
1885 		return (EINVAL);
1886 	}
1887 
1888 	for (dpio_t *dpio = list_head(&kgpio_g_dpios); dpio != NULL;
1889 	    dpio = list_next(&kgpio_g_dpios, dpio)) {
1890 		if (strcmp(dpio->dpio_name, info.dpi_dpio) == 0) {
1891 			return (kgpio_ioctl_dpio_info_common(dpio, &info, arg,
1892 			    mode));
1893 		}
1894 	}
1895 
1896 	return (ENOENT);
1897 }
1898 
1899 static int
kgpio_ioctl_gpio_name2id(kgpio_t * kgpio,intptr_t arg,int mode)1900 kgpio_ioctl_gpio_name2id(kgpio_t *kgpio, intptr_t arg, int mode)
1901 {
1902 	int ret;
1903 	kgpio_ioc_name2id_t id;
1904 	size_t len;
1905 
1906 	ASSERT(MUTEX_HELD(&kgpio->kgpio_mutex));
1907 
1908 	if ((mode & FREAD) == 0) {
1909 		return (EBADF);
1910 	}
1911 
1912 	if (ddi_copyin((void *)arg, &id, sizeof (id), mode & FKIOCTL) != 0) {
1913 		return (EFAULT);
1914 	}
1915 
1916 	len = strnlen(id.kin_name, sizeof (id.kin_name));
1917 	if (len == 0 || len == sizeof (id.kin_name)) {
1918 		return (EINVAL);
1919 	}
1920 
1921 	ret = kgpio->kgpio_ops->kgo_name2id(kgpio->kgpio_drv, id.kin_name,
1922 	    &id.kin_id);
1923 	if (ret != 0) {
1924 		return (ret);
1925 	}
1926 
1927 	if (ddi_copyout(&id, (void *)arg, sizeof (id), mode & FKIOCTL) != 0) {
1928 		return (EFAULT);
1929 	}
1930 
1931 	return (0);
1932 }
1933 
1934 static int
kgpio_ioctl(dev_t dev,int cmd,intptr_t arg,int mode,cred_t * credp,int * rvalp)1935 kgpio_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
1936     int *rvalp)
1937 {
1938 	int ret;
1939 	kgpio_minor_t *minor;
1940 	kgpio_t *kgpio;
1941 	dpio_t *dpio;
1942 
1943 	mutex_enter(&kgpio_g_mutex);
1944 	minor = kgpio_minor_find((id_t)getminor(dev));
1945 	VERIFY3P(minor, !=, NULL);
1946 	switch (minor->kminor_type) {
1947 	case KGPIO_MINOR_T_CTRL:
1948 		kgpio = minor->kminor_data.kminor_ctrl;
1949 		VERIFY3P(kgpio, !=, NULL);
1950 
1951 		mutex_enter(&kgpio->kgpio_mutex);
1952 		mutex_exit(&kgpio_g_mutex);
1953 		ASSERT(kgpio->kgpio_flags & KGPIO_F_VALID);
1954 		ASSERT(kgpio->kgpio_flags & KGPIO_F_HELD);
1955 
1956 		switch (cmd) {
1957 		case KGPIO_IOC_CTRL_INFO:
1958 			ret = kgpio_ioctl_ctrl_info(kgpio, arg, mode);
1959 			break;
1960 		case KGPIO_IOC_GPIO_INFO:
1961 			ret = kgpio_ioctl_gpio_info(kgpio, arg, mode);
1962 			break;
1963 		case KGPIO_IOC_GPIO_UPDATE:
1964 			ret = kgpio_ioctl_gpio_update(kgpio, arg, mode);
1965 			break;
1966 		case KGPIO_IOC_DPIO_CREATE:
1967 			ret = kgpio_ioctl_dpio_create(kgpio, arg, mode);
1968 			break;
1969 		case KGPIO_IOC_DPIO_DESTROY:
1970 			ret = kgpio_ioctl_dpio_destroy(kgpio, arg, mode);
1971 			break;
1972 		case KGPIO_IOC_GPIO_NAME2ID:
1973 			ret = kgpio_ioctl_gpio_name2id(kgpio, arg, mode);
1974 			break;
1975 		default:
1976 			ret = ENOTTY;
1977 			break;
1978 		}
1979 
1980 		mutex_exit(&kgpio->kgpio_mutex);
1981 		break;
1982 	case KGPIO_MINOR_T_DPIO:
1983 		dpio = minor->kminor_data.kminor_dpio;
1984 		VERIFY3P(dpio, !=, NULL);
1985 		mutex_enter(&dpio->dpio_mutex);
1986 		mutex_exit(&kgpio_g_mutex);
1987 
1988 		switch (cmd) {
1989 		case DPIO_IOC_INFO:
1990 			ret = kgpio_ioctl_dpio_info_specific(dpio, arg, mode);
1991 			break;
1992 		case DPIO_IOC_TIMING:
1993 			ret = kgpio_ioctl_dpio_time(dpio, arg, mode);
1994 			break;
1995 		case DPIO_IOC_CUROUT:
1996 			ret = kgpio_ioctl_dpio_curout(dpio, arg, mode);
1997 			break;
1998 		default:
1999 			ret = ENOTTY;
2000 			break;
2001 		}
2002 		mutex_exit(&dpio->dpio_mutex);
2003 		break;
2004 	case KGPIO_MINOR_T_DPINFO:
2005 		switch (cmd) {
2006 		case DPIO_IOC_INFO:
2007 			ret = kgpio_ioctl_dpio_info_search(arg, mode);
2008 			break;
2009 		default:
2010 			ret = ENOTTY;
2011 			break;
2012 		}
2013 		mutex_exit(&kgpio_g_mutex);
2014 		break;
2015 	default:
2016 		mutex_exit(&kgpio_g_mutex);
2017 		return (ENXIO);
2018 	}
2019 	return (ret);
2020 }
2021 
2022 static int
kgpio_read(dev_t dev,struct uio * uiop,cred_t * credp)2023 kgpio_read(dev_t dev, struct uio *uiop, cred_t *credp)
2024 {
2025 	int ret;
2026 	kgpio_minor_t *minor;
2027 	dpio_t *dpio;
2028 	kgpio_t *kgpio;
2029 	dpio_input_t input;
2030 	offset_t off;
2031 
2032 	mutex_enter(&kgpio_g_mutex);
2033 	minor = kgpio_minor_find((id_t)getminor(dev));
2034 	VERIFY3P(minor, !=, NULL);
2035 
2036 	if (minor->kminor_type != KGPIO_MINOR_T_DPIO) {
2037 		mutex_exit(&kgpio_g_mutex);
2038 		return (ENXIO);
2039 	}
2040 
2041 	dpio = minor->kminor_data.kminor_dpio;
2042 	VERIFY3P(dpio, !=, NULL);
2043 	mutex_exit(&kgpio_g_mutex);
2044 
2045 	if ((dpio->dpio_caps & DPIO_C_READ) == 0) {
2046 		return (ENOTSUP);
2047 	}
2048 
2049 	if (uiop->uio_resid <= 0) {
2050 		return (EINVAL);
2051 	}
2052 
2053 	if (uiop->uio_resid < sizeof (input)) {
2054 		return (EOVERFLOW);
2055 	}
2056 
2057 	kgpio = dpio->dpio_kgpio;
2058 	mutex_enter(&kgpio->kgpio_mutex);
2059 	ret = kgpio->kgpio_ops->kgo_input(kgpio->kgpio_drv, dpio->dpio_gpio_num,
2060 	    &input);
2061 	mutex_exit(&kgpio->kgpio_mutex);
2062 	if (ret != 0) {
2063 		return (ret);
2064 	}
2065 
2066 	off = uiop->uio_loffset;
2067 	ret = uiomove(&input, sizeof (input), UIO_READ, uiop);
2068 	uiop->uio_loffset = off;
2069 
2070 	return (ret);
2071 }
2072 
2073 static int
kgpio_write(dev_t dev,struct uio * uiop,cred_t * credp)2074 kgpio_write(dev_t dev, struct uio *uiop, cred_t *credp)
2075 {
2076 	int ret;
2077 	kgpio_minor_t *minor;
2078 	dpio_t *dpio;
2079 	kgpio_t *kgpio;
2080 	dpio_output_t output;
2081 	offset_t off;
2082 
2083 	mutex_enter(&kgpio_g_mutex);
2084 	minor = kgpio_minor_find((id_t)getminor(dev));
2085 	VERIFY3P(minor, !=, NULL);
2086 
2087 	if (minor->kminor_type != KGPIO_MINOR_T_DPIO) {
2088 		mutex_exit(&kgpio_g_mutex);
2089 		return (ENXIO);
2090 	}
2091 
2092 	dpio = minor->kminor_data.kminor_dpio;
2093 	VERIFY3P(dpio, !=, NULL);
2094 	mutex_exit(&kgpio_g_mutex);
2095 
2096 	if ((dpio->dpio_caps & DPIO_C_WRITE) == 0) {
2097 		return (ENOTSUP);
2098 	}
2099 
2100 	if (uiop->uio_resid < sizeof (output)) {
2101 		return (EINVAL);
2102 	}
2103 
2104 	off = uiop->uio_loffset;
2105 	ret = uiomove(&output, sizeof (output), UIO_WRITE, uiop);
2106 	uiop->uio_loffset = off;
2107 	if (ret != 0) {
2108 		return (ret);
2109 	}
2110 
2111 	switch (output) {
2112 	case DPIO_OUTPUT_LOW:
2113 	case DPIO_OUTPUT_HIGH:
2114 	case DPIO_OUTPUT_DISABLE:
2115 		break;
2116 	default:
2117 		return (EINVAL);
2118 	}
2119 
2120 	kgpio = dpio->dpio_kgpio;
2121 	mutex_enter(&kgpio->kgpio_mutex);
2122 	ret = kgpio->kgpio_ops->kgo_output(kgpio->kgpio_drv,
2123 	    dpio->dpio_gpio_num, output);
2124 	mutex_exit(&kgpio->kgpio_mutex);
2125 
2126 	if (ret == 0) {
2127 		mutex_enter(&dpio->dpio_mutex);
2128 		dpio->dpio_last_write = gethrtime();
2129 		mutex_exit(&dpio->dpio_mutex);
2130 	}
2131 
2132 	return (ret);
2133 }
2134 
2135 static int
kgpio_close(dev_t dev,int flag,int otyp,cred_t * credp)2136 kgpio_close(dev_t dev, int flag, int otyp, cred_t *credp)
2137 {
2138 	kgpio_minor_t *minor;
2139 	kgpio_t *kgpio;
2140 	dpio_t *dpio;
2141 
2142 	if (otyp != OTYP_CHR) {
2143 		return (EINVAL);
2144 	}
2145 
2146 	mutex_enter(&kgpio_g_mutex);
2147 	minor = kgpio_minor_find((id_t)getminor(dev));
2148 	VERIFY3P(minor, !=, NULL);
2149 	switch (minor->kminor_type) {
2150 	case KGPIO_MINOR_T_CTRL:
2151 		kgpio = minor->kminor_data.kminor_ctrl;
2152 		VERIFY3P(kgpio, !=, NULL);
2153 
2154 		mutex_enter(&kgpio->kgpio_mutex);
2155 		ASSERT(kgpio->kgpio_flags & KGPIO_F_VALID);
2156 		ASSERT(kgpio->kgpio_flags & KGPIO_F_HELD);
2157 
2158 		/*
2159 		 * The system guarantees that we are mutually exclusive with
2160 		 * open(9E).  As such, it's safe for us to go ahead and clear
2161 		 * this out. Note, we drop all of our locks to honor the general
2162 		 * lock ordering of no NDI activity with locks held.
2163 		 */
2164 		mutex_exit(&kgpio_g_mutex);
2165 		mutex_exit(&kgpio->kgpio_mutex);
2166 
2167 		kgpio_release(kgpio);
2168 		return (0);
2169 	case KGPIO_MINOR_T_DPIO:
2170 		dpio = minor->kminor_data.kminor_dpio;
2171 		VERIFY3P(dpio, !=, NULL);
2172 		mutex_enter(&dpio->dpio_mutex);
2173 		mutex_exit(&kgpio_g_mutex);
2174 
2175 		/*
2176 		 * Because of the last-close style behavior, the only thing that
2177 		 * we need to do is to make sure that we clear out our state
2178 		 * flags and indicate that we are no longer open and no longer
2179 		 * exclusive, if we were.
2180 		 */
2181 		dpio->dpio_status &= ~(DPIO_S_EXCL | DPIO_S_OPEN);
2182 		mutex_exit(&dpio->dpio_mutex);
2183 		return (0);
2184 	case KGPIO_MINOR_T_DPINFO:
2185 		mutex_exit(&kgpio_g_mutex);
2186 		/*
2187 		 * There is nothing special to do to close the dpio information
2188 		 * based minor device as there is no state or other logic
2189 		 * associated with it.
2190 		 */
2191 		return (0);
2192 	default:
2193 		mutex_exit(&kgpio_g_mutex);
2194 		return (ENXIO);
2195 	}
2196 }
2197 
2198 static int
kgpio_attach(dev_info_t * dip,ddi_attach_cmd_t cmd)2199 kgpio_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
2200 {
2201 	switch (cmd) {
2202 	case DDI_ATTACH:
2203 		break;
2204 	case DDI_RESUME:
2205 		return (DDI_SUCCESS);
2206 	default:
2207 		return (DDI_FAILURE);
2208 	}
2209 
2210 	if (ddi_get_instance(dip) != 0) {
2211 		dev_err(dip, CE_WARN, "asked to attach non-zero instance");
2212 		return (DDI_FAILURE);
2213 	}
2214 
2215 	mutex_enter(&kgpio_g_mutex);
2216 	if (kgpio_g_dip != NULL) {
2217 		mutex_exit(&kgpio_g_mutex);
2218 		dev_err(dip, CE_WARN, "asked to attach a second kgpio "
2219 		    "instance");
2220 		return (DDI_FAILURE);
2221 	}
2222 
2223 	/*
2224 	 * Set up the dpio minor, which always uses minor number 1, note this is
2225 	 * reserved outside of the id_space, so we don't have to allocate or
2226 	 * worry about failure.
2227 	 */
2228 	if (ddi_create_minor_node(dip, KGPIO_MINOR_NAME_DPINFO, S_IFCHR,
2229 	    KGPIO_MINOR_DPINFO, DDI_PSEUDO, 0) != 0) {
2230 		dev_err(dip, CE_WARN, "failed to create dpinfo minor");
2231 		mutex_exit(&kgpio_g_mutex);
2232 		return (DDI_FAILURE);
2233 	}
2234 
2235 	kgpio_g_dpinfo.kminor_id = KGPIO_MINOR_DPINFO;
2236 	kgpio_g_dpinfo.kminor_type = KGPIO_MINOR_T_DPINFO;
2237 	avl_add(&kgpio_g_minors, &kgpio_g_dpinfo);
2238 	kgpio_g_dip = dip;
2239 
2240 	/*
2241 	 * At this point, we need to check for any drivers that beat us and
2242 	 * register them.
2243 	 */
2244 	for (kgpio_t *k = list_head(&kgpio_g_gpios); k != NULL;
2245 	    k = list_next(&kgpio_g_gpios, k)) {
2246 		mutex_enter(&k->kgpio_mutex);
2247 		ASSERT0(k->kgpio_flags & KGPIO_F_MINOR_VALID);
2248 		kgpio_create_minor(k);
2249 		mutex_exit(&k->kgpio_mutex);
2250 	}
2251 	mutex_exit(&kgpio_g_mutex);
2252 	return (DDI_SUCCESS);
2253 }
2254 
2255 static int
kgpio_getinfo(dev_info_t * dip,ddi_info_cmd_t cmd,void * arg,void ** resultp)2256 kgpio_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd, void *arg, void **resultp)
2257 {
2258 	switch (cmd) {
2259 	case DDI_INFO_DEVT2DEVINFO:
2260 		*resultp = kgpio_g_dip;
2261 		break;
2262 	case DDI_INFO_DEVT2INSTANCE:
2263 		*resultp = (void *)(uintptr_t)ddi_get_instance(kgpio_g_dip);
2264 		break;
2265 	default:
2266 		return (DDI_FAILURE);
2267 	}
2268 
2269 	return (DDI_SUCCESS);
2270 }
2271 
2272 static int
kgpio_detach(dev_info_t * dip,ddi_detach_cmd_t cmd)2273 kgpio_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
2274 {
2275 	switch (cmd) {
2276 	case DDI_DETACH:
2277 		break;
2278 	case DDI_SUSPEND:
2279 		return (DDI_SUCCESS);
2280 	default:
2281 		return (DDI_FAILURE);
2282 	}
2283 
2284 	mutex_enter(&kgpio_g_mutex);
2285 	if (dip != kgpio_g_dip) {
2286 		mutex_exit(&kgpio_g_mutex);
2287 		dev_err(dip, CE_WARN, "asked to detach dip that is not the "
2288 		    "current kgpio dip");
2289 		return (DDI_FAILURE);
2290 	}
2291 
2292 	if (list_is_empty(&kgpio_g_gpios) == 0) {
2293 		mutex_exit(&kgpio_g_mutex);
2294 		return (DDI_FAILURE);
2295 	}
2296 
2297 	avl_remove(&kgpio_g_minors, &kgpio_g_dpinfo);
2298 	ddi_remove_minor_node(dip, KGPIO_MINOR_NAME_DPINFO);
2299 	kgpio_g_dip = NULL;
2300 	mutex_exit(&kgpio_g_mutex);
2301 	return (DDI_SUCCESS);
2302 }
2303 
2304 static struct cb_ops kgpio_cb_ops = {
2305 	.cb_open = kgpio_open,
2306 	.cb_close = kgpio_close,
2307 	.cb_strategy = nodev,
2308 	.cb_print = nodev,
2309 	.cb_dump = nodev,
2310 	.cb_read = kgpio_read,
2311 	.cb_write = kgpio_write,
2312 	.cb_ioctl = kgpio_ioctl,
2313 	.cb_devmap = nodev,
2314 	.cb_mmap = nodev,
2315 	.cb_segmap = nodev,
2316 	.cb_chpoll = nochpoll,
2317 	.cb_prop_op = ddi_prop_op,
2318 	.cb_flag = D_MP,
2319 	.cb_rev = CB_REV,
2320 	.cb_aread = nodev,
2321 	.cb_awrite = nodev
2322 };
2323 
2324 static struct dev_ops kgpio_dev_ops = {
2325 	.devo_rev = DEVO_REV,
2326 	.devo_refcnt = 0,
2327 	.devo_getinfo = kgpio_getinfo,
2328 	.devo_identify = nulldev,
2329 	.devo_probe = nulldev,
2330 	.devo_attach = kgpio_attach,
2331 	.devo_detach = kgpio_detach,
2332 	.devo_reset = nodev,
2333 	.devo_quiesce = ddi_quiesce_not_needed,
2334 	.devo_cb_ops = &kgpio_cb_ops
2335 };
2336 
2337 static struct modldrv kgpio_modldrv = {
2338 	.drv_modops = &mod_driverops,
2339 	.drv_linkinfo = "Kernel GPIO Framework",
2340 	.drv_dev_ops = &kgpio_dev_ops
2341 };
2342 
2343 static struct modlinkage kgpio_modlinkage = {
2344 	.ml_rev = MODREV_1,
2345 	.ml_linkage = { &kgpio_modldrv, NULL }
2346 };
2347 
2348 static void
kgpio_init(void)2349 kgpio_init(void)
2350 {
2351 	mutex_init(&kgpio_g_mutex, NULL, MUTEX_DRIVER, NULL);
2352 	list_create(&kgpio_g_gpios, sizeof (kgpio_t),
2353 	    offsetof(kgpio_t, kgpio_link));
2354 	list_create(&kgpio_g_dpios, sizeof (dpio_t),
2355 	    offsetof(dpio_t, dpio_link));
2356 	avl_create(&kgpio_g_minors, kgpio_minor_comparator,
2357 	    sizeof (kgpio_minor_t), offsetof(kgpio_minor_t, kminor_avl));
2358 	kgpio_g_ids = id_space_create("kgpios", KGPIO_MINOR_FIRST, L_MAXMIN32);
2359 }
2360 
2361 static void
kgpio_fini(void)2362 kgpio_fini(void)
2363 {
2364 	id_space_destroy(kgpio_g_ids);
2365 	avl_destroy(&kgpio_g_minors);
2366 	list_destroy(&kgpio_g_dpios);
2367 	list_destroy(&kgpio_g_gpios);
2368 	mutex_destroy(&kgpio_g_mutex);
2369 }
2370 
2371 int
_init(void)2372 _init(void)
2373 {
2374 	int err;
2375 
2376 	kgpio_init();
2377 	err = mod_install(&kgpio_modlinkage);
2378 	if (err != 0) {
2379 		kgpio_fini();
2380 		return (err);
2381 	}
2382 
2383 	return (0);
2384 }
2385 
2386 int
_info(struct modinfo * modinfop)2387 _info(struct modinfo *modinfop)
2388 {
2389 	return (mod_info(&kgpio_modlinkage, modinfop));
2390 }
2391 
2392 int
_fini(void)2393 _fini(void)
2394 {
2395 	int err;
2396 
2397 	mutex_enter(&kgpio_g_mutex);
2398 	if (list_is_empty(&kgpio_g_gpios) == 0) {
2399 		mutex_exit(&kgpio_g_mutex);
2400 		return (EBUSY);
2401 	}
2402 	mutex_exit(&kgpio_g_mutex);
2403 
2404 
2405 	err = mod_remove(&kgpio_modlinkage);
2406 	if (err != 0) {
2407 		return (err);
2408 	}
2409 
2410 	kgpio_fini();
2411 	return (0);
2412 }
2413