xref: /freebsd/sys/contrib/dev/acpica/components/events/evregion.c (revision 1323ec571215a77ddd21294f0871979d5ad6b992)
1 /******************************************************************************
2  *
3  * Module Name: evregion - Operation Region support
4  *
5  *****************************************************************************/
6 
7 /******************************************************************************
8  *
9  * 1. Copyright Notice
10  *
11  * Some or all of this work - Copyright (c) 1999 - 2022, Intel Corp.
12  * All rights reserved.
13  *
14  * 2. License
15  *
16  * 2.1. This is your license from Intel Corp. under its intellectual property
17  * rights. You may have additional license terms from the party that provided
18  * you this software, covering your right to use that party's intellectual
19  * property rights.
20  *
21  * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
22  * copy of the source code appearing in this file ("Covered Code") an
23  * irrevocable, perpetual, worldwide license under Intel's copyrights in the
24  * base code distributed originally by Intel ("Original Intel Code") to copy,
25  * make derivatives, distribute, use and display any portion of the Covered
26  * Code in any form, with the right to sublicense such rights; and
27  *
28  * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
29  * license (with the right to sublicense), under only those claims of Intel
30  * patents that are infringed by the Original Intel Code, to make, use, sell,
31  * offer to sell, and import the Covered Code and derivative works thereof
32  * solely to the minimum extent necessary to exercise the above copyright
33  * license, and in no event shall the patent license extend to any additions
34  * to or modifications of the Original Intel Code. No other license or right
35  * is granted directly or by implication, estoppel or otherwise;
36  *
37  * The above copyright and patent license is granted only if the following
38  * conditions are met:
39  *
40  * 3. Conditions
41  *
42  * 3.1. Redistribution of Source with Rights to Further Distribute Source.
43  * Redistribution of source code of any substantial portion of the Covered
44  * Code or modification with rights to further distribute source must include
45  * the above Copyright Notice, the above License, this list of Conditions,
46  * and the following Disclaimer and Export Compliance provision. In addition,
47  * Licensee must cause all Covered Code to which Licensee contributes to
48  * contain a file documenting the changes Licensee made to create that Covered
49  * Code and the date of any change. Licensee must include in that file the
50  * documentation of any changes made by any predecessor Licensee. Licensee
51  * must include a prominent statement that the modification is derived,
52  * directly or indirectly, from Original Intel Code.
53  *
54  * 3.2. Redistribution of Source with no Rights to Further Distribute Source.
55  * Redistribution of source code of any substantial portion of the Covered
56  * Code or modification without rights to further distribute source must
57  * include the following Disclaimer and Export Compliance provision in the
58  * documentation and/or other materials provided with distribution. In
59  * addition, Licensee may not authorize further sublicense of source of any
60  * portion of the Covered Code, and must include terms to the effect that the
61  * license from Licensee to its licensee is limited to the intellectual
62  * property embodied in the software Licensee provides to its licensee, and
63  * not to intellectual property embodied in modifications its licensee may
64  * make.
65  *
66  * 3.3. Redistribution of Executable. Redistribution in executable form of any
67  * substantial portion of the Covered Code or modification must reproduce the
68  * above Copyright Notice, and the following Disclaimer and Export Compliance
69  * provision in the documentation and/or other materials provided with the
70  * distribution.
71  *
72  * 3.4. Intel retains all right, title, and interest in and to the Original
73  * Intel Code.
74  *
75  * 3.5. Neither the name Intel nor any other trademark owned or controlled by
76  * Intel shall be used in advertising or otherwise to promote the sale, use or
77  * other dealings in products derived from or relating to the Covered Code
78  * without prior written authorization from Intel.
79  *
80  * 4. Disclaimer and Export Compliance
81  *
82  * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
83  * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
84  * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
85  * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
86  * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
87  * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
88  * PARTICULAR PURPOSE.
89  *
90  * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
91  * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
92  * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
93  * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
94  * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
95  * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
96  * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
97  * LIMITED REMEDY.
98  *
99  * 4.3. Licensee shall not export, either directly or indirectly, any of this
100  * software or system incorporating such software without first obtaining any
101  * required license or other approval from the U. S. Department of Commerce or
102  * any other agency or department of the United States Government. In the
103  * event Licensee exports any such software from the United States or
104  * re-exports any such software from a foreign destination, Licensee shall
105  * ensure that the distribution and export/re-export of the software is in
106  * compliance with all laws, regulations, orders, or other restrictions of the
107  * U.S. Export Administration Regulations. Licensee agrees that neither it nor
108  * any of its subsidiaries will export/re-export any technical data, process,
109  * software, or service, directly or indirectly, to any country for which the
110  * United States government or any agency thereof requires an export license,
111  * other governmental approval, or letter of assurance, without first obtaining
112  * such license, approval or letter.
113  *
114  *****************************************************************************
115  *
116  * Alternatively, you may choose to be licensed under the terms of the
117  * following license:
118  *
119  * Redistribution and use in source and binary forms, with or without
120  * modification, are permitted provided that the following conditions
121  * are met:
122  * 1. Redistributions of source code must retain the above copyright
123  *    notice, this list of conditions, and the following disclaimer,
124  *    without modification.
125  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
126  *    substantially similar to the "NO WARRANTY" disclaimer below
127  *    ("Disclaimer") and any redistribution must be conditioned upon
128  *    including a substantially similar Disclaimer requirement for further
129  *    binary redistribution.
130  * 3. Neither the names of the above-listed copyright holders nor the names
131  *    of any contributors may be used to endorse or promote products derived
132  *    from this software without specific prior written permission.
133  *
134  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
135  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
136  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
137  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
138  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
139  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
140  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
141  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
142  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
143  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
144  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
145  *
146  * Alternatively, you may choose to be licensed under the terms of the
147  * GNU General Public License ("GPL") version 2 as published by the Free
148  * Software Foundation.
149  *
150  *****************************************************************************/
151 
152 #include <contrib/dev/acpica/include/acpi.h>
153 #include <contrib/dev/acpica/include/accommon.h>
154 #include <contrib/dev/acpica/include/acevents.h>
155 #include <contrib/dev/acpica/include/acnamesp.h>
156 #include <contrib/dev/acpica/include/acinterp.h>
157 
158 #define _COMPONENT          ACPI_EVENTS
159         ACPI_MODULE_NAME    ("evregion")
160 
161 
162 extern UINT8        AcpiGbl_DefaultAddressSpaces[];
163 
164 /* Local prototypes */
165 
166 static void
167 AcpiEvExecuteOrphanRegMethod (
168     ACPI_NAMESPACE_NODE     *DeviceNode,
169     ACPI_ADR_SPACE_TYPE     SpaceId);
170 
171 
172 static ACPI_STATUS
173 AcpiEvRegRun (
174     ACPI_HANDLE             ObjHandle,
175     UINT32                  Level,
176     void                    *Context,
177     void                    **ReturnValue);
178 
179 
180 /*******************************************************************************
181  *
182  * FUNCTION:    AcpiEvInitializeOpRegions
183  *
184  * PARAMETERS:  None
185  *
186  * RETURN:      Status
187  *
188  * DESCRIPTION: Execute _REG methods for all Operation Regions that have
189  *              an installed default region handler.
190  *
191  ******************************************************************************/
192 
193 ACPI_STATUS
194 AcpiEvInitializeOpRegions (
195     void)
196 {
197     ACPI_STATUS             Status;
198     UINT32                  i;
199 
200 
201     ACPI_FUNCTION_TRACE (EvInitializeOpRegions);
202 
203 
204     Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
205     if (ACPI_FAILURE (Status))
206     {
207         return_ACPI_STATUS (Status);
208     }
209 
210     /* Run the _REG methods for OpRegions in each default address space */
211 
212     for (i = 0; i < ACPI_NUM_DEFAULT_SPACES; i++)
213     {
214         /*
215          * Make sure the installed handler is the DEFAULT handler. If not the
216          * default, the _REG methods will have already been run (when the
217          * handler was installed)
218          */
219         if (AcpiEvHasDefaultHandler (AcpiGbl_RootNode,
220                AcpiGbl_DefaultAddressSpaces[i]))
221         {
222             AcpiEvExecuteRegMethods (AcpiGbl_RootNode,
223                 AcpiGbl_DefaultAddressSpaces[i], ACPI_REG_CONNECT);
224         }
225     }
226 
227     (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);
228     return_ACPI_STATUS (Status);
229 }
230 
231 
232 /*******************************************************************************
233  *
234  * FUNCTION:    AcpiEvAddressSpaceDispatch
235  *
236  * PARAMETERS:  RegionObj           - Internal region object
237  *              FieldObj            - Corresponding field. Can be NULL.
238  *              Function            - Read or Write operation
239  *              RegionOffset        - Where in the region to read or write
240  *              BitWidth            - Field width in bits (8, 16, 32, or 64)
241  *              Value               - Pointer to in or out value, must be
242  *                                    a full 64-bit integer
243  *
244  * RETURN:      Status
245  *
246  * DESCRIPTION: Dispatch an address space or operation region access to
247  *              a previously installed handler.
248  *
249  * NOTE: During early initialization, we always install the default region
250  * handlers for Memory, I/O and PCI_Config. This ensures that these operation
251  * region address spaces are always available as per the ACPI specification.
252  * This is especially needed in order to support the execution of
253  * module-level AML code during loading of the ACPI tables.
254  *
255  ******************************************************************************/
256 
257 ACPI_STATUS
258 AcpiEvAddressSpaceDispatch (
259     ACPI_OPERAND_OBJECT     *RegionObj,
260     ACPI_OPERAND_OBJECT     *FieldObj,
261     UINT32                  Function,
262     UINT32                  RegionOffset,
263     UINT32                  BitWidth,
264     UINT64                  *Value)
265 {
266     ACPI_STATUS             Status;
267     ACPI_ADR_SPACE_HANDLER  Handler;
268     ACPI_ADR_SPACE_SETUP    RegionSetup;
269     ACPI_OPERAND_OBJECT     *HandlerDesc;
270     ACPI_OPERAND_OBJECT     *RegionObj2;
271     void                    *RegionContext = NULL;
272     ACPI_CONNECTION_INFO    *Context;
273     ACPI_MUTEX              ContextMutex;
274     BOOLEAN                 ContextLocked;
275     ACPI_PHYSICAL_ADDRESS   Address;
276 
277 
278     ACPI_FUNCTION_TRACE (EvAddressSpaceDispatch);
279 
280 
281     RegionObj2 = AcpiNsGetSecondaryObject (RegionObj);
282     if (!RegionObj2)
283     {
284         return_ACPI_STATUS (AE_NOT_EXIST);
285     }
286 
287     /* Ensure that there is a handler associated with this region */
288 
289     HandlerDesc = RegionObj->Region.Handler;
290     if (!HandlerDesc)
291     {
292         ACPI_ERROR ((AE_INFO,
293             "No handler for Region [%4.4s] (%p) [%s]",
294             AcpiUtGetNodeName (RegionObj->Region.Node),
295             RegionObj, AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
296 
297         return_ACPI_STATUS (AE_NOT_EXIST);
298     }
299 
300     Context = HandlerDesc->AddressSpace.Context;
301     ContextMutex = HandlerDesc->AddressSpace.ContextMutex;
302     ContextLocked = FALSE;
303 
304     /*
305      * It may be the case that the region has never been initialized.
306      * Some types of regions require special init code
307      */
308     if (!(RegionObj->Region.Flags & AOPOBJ_SETUP_COMPLETE))
309     {
310         /* This region has not been initialized yet, do it */
311 
312         RegionSetup = HandlerDesc->AddressSpace.Setup;
313         if (!RegionSetup)
314         {
315             /* No initialization routine, exit with error */
316 
317             ACPI_ERROR ((AE_INFO,
318                 "No init routine for region(%p) [%s]",
319                 RegionObj, AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
320             return_ACPI_STATUS (AE_NOT_EXIST);
321         }
322 
323         if (RegionObj->Region.SpaceId == ACPI_ADR_SPACE_PLATFORM_COMM)
324         {
325             ACPI_PCC_INFO *Ctx = HandlerDesc->AddressSpace.Context;
326 
327             Ctx->InternalBuffer = FieldObj->Field.InternalPccBuffer;
328             Ctx->Length = (UINT16) RegionObj->Region.Length;
329             Ctx->SubspaceId = (UINT8) RegionObj->Region.Address;
330         }
331 
332         /*
333          * We must exit the interpreter because the region setup will
334          * potentially execute control methods (for example, the _REG method
335          * for this region)
336          */
337         AcpiExExitInterpreter ();
338 
339         Status = RegionSetup (RegionObj, ACPI_REGION_ACTIVATE,
340             Context, &RegionContext);
341 
342         /* Re-enter the interpreter */
343 
344         AcpiExEnterInterpreter ();
345 
346         /* Check for failure of the Region Setup */
347 
348         if (ACPI_FAILURE (Status))
349         {
350             ACPI_EXCEPTION ((AE_INFO, Status,
351                 "During region initialization: [%s]",
352                 AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
353             return_ACPI_STATUS (Status);
354         }
355 
356         /* Region initialization may have been completed by RegionSetup */
357 
358         if (!(RegionObj->Region.Flags & AOPOBJ_SETUP_COMPLETE))
359         {
360             RegionObj->Region.Flags |= AOPOBJ_SETUP_COMPLETE;
361 
362             /*
363              * Save the returned context for use in all accesses to
364              * the handler for this particular region
365              */
366             if (!(RegionObj2->Extra.RegionContext))
367             {
368                 RegionObj2->Extra.RegionContext = RegionContext;
369             }
370         }
371     }
372 
373     /* We have everything we need, we can invoke the address space handler */
374 
375     Handler = HandlerDesc->AddressSpace.Handler;
376     Address = (RegionObj->Region.Address + RegionOffset);
377 
378     ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
379         "Handler %p (@%p) Address %8.8X%8.8X [%s]\n",
380         &RegionObj->Region.Handler->AddressSpace, Handler,
381         ACPI_FORMAT_UINT64 (Address),
382         AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
383 
384     if (!(HandlerDesc->AddressSpace.HandlerFlags &
385         ACPI_ADDR_HANDLER_DEFAULT_INSTALLED))
386     {
387         /*
388          * For handlers other than the default (supplied) handlers, we must
389          * exit the interpreter because the handler *might* block -- we don't
390          * know what it will do, so we can't hold the lock on the interpreter.
391          */
392         AcpiExExitInterpreter();
393     }
394 
395     /*
396      * Special handling for GenericSerialBus and GeneralPurposeIo:
397      * There are three extra parameters that must be passed to the
398      * handler via the context:
399      *   1) Connection buffer, a resource template from Connection() op
400      *   2) Length of the above buffer
401      *   3) Actual access length from the AccessAs() op
402      *
403      * Since we pass these extra parameters via the context, which is
404      * shared between threads, we must lock the context to avoid these
405      * parameters being changed from another thread before the handler
406      * has completed running.
407      *
408      * In addition, for GeneralPurposeIo, the Address and BitWidth fields
409      * are defined as follows:
410      *   1) Address is the pin number index of the field (bit offset from
411      *      the previous Connection)
412      *   2) BitWidth is the actual bit length of the field (number of pins)
413      */
414     if ((RegionObj->Region.SpaceId == ACPI_ADR_SPACE_GSBUS ||
415          RegionObj->Region.SpaceId == ACPI_ADR_SPACE_GPIO) &&
416         Context &&
417         FieldObj)
418     {
419 
420         Status = AcpiOsAcquireMutex (ContextMutex, ACPI_WAIT_FOREVER);
421         if (ACPI_FAILURE (Status))
422         {
423             goto ReEnterInterpreter;
424         }
425 
426         ContextLocked = TRUE;
427 
428         /* Get the Connection (ResourceTemplate) buffer */
429 
430         Context->Connection = FieldObj->Field.ResourceBuffer;
431         Context->Length = FieldObj->Field.ResourceLength;
432         Context->AccessLength = FieldObj->Field.AccessLength;
433 
434         if (RegionObj->Region.SpaceId == ACPI_ADR_SPACE_GPIO)
435         {
436             Address = FieldObj->Field.PinNumberIndex;
437             BitWidth = FieldObj->Field.BitLength;
438         }
439     }
440 
441     /* Call the handler */
442 
443     Status = Handler (Function, Address, BitWidth, Value, Context,
444         RegionObj2->Extra.RegionContext);
445 
446     if (ContextLocked)
447     {
448         AcpiOsReleaseMutex (ContextMutex);
449     }
450 
451     if (ACPI_FAILURE (Status))
452     {
453         ACPI_EXCEPTION ((AE_INFO, Status, "Returned by Handler for [%s]",
454             AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
455 
456         /*
457          * Special case for an EC timeout. These are seen so frequently
458          * that an additional error message is helpful
459          */
460         if ((RegionObj->Region.SpaceId == ACPI_ADR_SPACE_EC) &&
461             (Status == AE_TIME))
462         {
463             ACPI_ERROR ((AE_INFO,
464                 "Timeout from EC hardware or EC device driver"));
465         }
466     }
467 
468 ReEnterInterpreter:
469     if (!(HandlerDesc->AddressSpace.HandlerFlags &
470         ACPI_ADDR_HANDLER_DEFAULT_INSTALLED))
471     {
472         /*
473          * We just returned from a non-default handler, we must re-enter the
474          * interpreter
475          */
476         AcpiExEnterInterpreter ();
477     }
478 
479     return_ACPI_STATUS (Status);
480 }
481 
482 
483 /*******************************************************************************
484  *
485  * FUNCTION:    AcpiEvDetachRegion
486  *
487  * PARAMETERS:  RegionObj           - Region Object
488  *              AcpiNsIsLocked      - Namespace Region Already Locked?
489  *
490  * RETURN:      None
491  *
492  * DESCRIPTION: Break the association between the handler and the region
493  *              this is a two way association.
494  *
495  ******************************************************************************/
496 
497 void
498 AcpiEvDetachRegion (
499     ACPI_OPERAND_OBJECT     *RegionObj,
500     BOOLEAN                 AcpiNsIsLocked)
501 {
502     ACPI_OPERAND_OBJECT     *HandlerObj;
503     ACPI_OPERAND_OBJECT     *ObjDesc;
504     ACPI_OPERAND_OBJECT     *StartDesc;
505     ACPI_OPERAND_OBJECT     **LastObjPtr;
506     ACPI_ADR_SPACE_SETUP    RegionSetup;
507     void                    **RegionContext;
508     ACPI_OPERAND_OBJECT     *RegionObj2;
509     ACPI_STATUS             Status;
510 
511 
512     ACPI_FUNCTION_TRACE (EvDetachRegion);
513 
514 
515     RegionObj2 = AcpiNsGetSecondaryObject (RegionObj);
516     if (!RegionObj2)
517     {
518         return_VOID;
519     }
520     RegionContext = &RegionObj2->Extra.RegionContext;
521 
522     /* Get the address handler from the region object */
523 
524     HandlerObj = RegionObj->Region.Handler;
525     if (!HandlerObj)
526     {
527         /* This region has no handler, all done */
528 
529         return_VOID;
530     }
531 
532     /* Find this region in the handler's list */
533 
534     ObjDesc = HandlerObj->AddressSpace.RegionList;
535     StartDesc = ObjDesc;
536     LastObjPtr = &HandlerObj->AddressSpace.RegionList;
537 
538     while (ObjDesc)
539     {
540         /* Is this the correct Region? */
541 
542         if (ObjDesc == RegionObj)
543         {
544             ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
545                 "Removing Region %p from address handler %p\n",
546                 RegionObj, HandlerObj));
547 
548             /* This is it, remove it from the handler's list */
549 
550             *LastObjPtr = ObjDesc->Region.Next;
551             ObjDesc->Region.Next = NULL;        /* Must clear field */
552 
553             if (AcpiNsIsLocked)
554             {
555                 Status = AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);
556                 if (ACPI_FAILURE (Status))
557                 {
558                     return_VOID;
559                 }
560             }
561 
562             /* Now stop region accesses by executing the _REG method */
563 
564             Status = AcpiEvExecuteRegMethod (RegionObj, ACPI_REG_DISCONNECT);
565             if (ACPI_FAILURE (Status))
566             {
567                 ACPI_EXCEPTION ((AE_INFO, Status, "from region _REG, [%s]",
568                     AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
569             }
570 
571             if (AcpiNsIsLocked)
572             {
573                 Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
574                 if (ACPI_FAILURE (Status))
575                 {
576                     return_VOID;
577                 }
578             }
579 
580             /*
581              * If the region has been activated, call the setup handler with
582              * the deactivate notification
583              */
584             if (RegionObj->Region.Flags & AOPOBJ_SETUP_COMPLETE)
585             {
586                 RegionSetup = HandlerObj->AddressSpace.Setup;
587                 Status = RegionSetup (RegionObj, ACPI_REGION_DEACTIVATE,
588                     HandlerObj->AddressSpace.Context, RegionContext);
589 
590                 /*
591                  * RegionContext should have been released by the deactivate
592                  * operation. We don't need access to it anymore here.
593                  */
594                 if (RegionContext)
595                 {
596                     *RegionContext = NULL;
597                 }
598 
599                 /* Init routine may fail, Just ignore errors */
600 
601                 if (ACPI_FAILURE (Status))
602                 {
603                     ACPI_EXCEPTION ((AE_INFO, Status,
604                         "from region handler - deactivate, [%s]",
605                         AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
606                 }
607 
608                 RegionObj->Region.Flags &= ~(AOPOBJ_SETUP_COMPLETE);
609             }
610 
611             /*
612              * Remove handler reference in the region
613              *
614              * NOTE: this doesn't mean that the region goes away, the region
615              * is just inaccessible as indicated to the _REG method
616              *
617              * If the region is on the handler's list, this must be the
618              * region's handler
619              */
620             RegionObj->Region.Handler = NULL;
621             AcpiUtRemoveReference (HandlerObj);
622 
623             return_VOID;
624         }
625 
626         /* Walk the linked list of handlers */
627 
628         LastObjPtr = &ObjDesc->Region.Next;
629         ObjDesc = ObjDesc->Region.Next;
630 
631         /* Prevent infinite loop if list is corrupted */
632 
633         if (ObjDesc == StartDesc)
634         {
635             ACPI_ERROR ((AE_INFO,
636                 "Circular handler list in region object %p",
637                 RegionObj));
638             return_VOID;
639         }
640     }
641 
642     /* If we get here, the region was not in the handler's region list */
643 
644     ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
645         "Cannot remove region %p from address handler %p\n",
646         RegionObj, HandlerObj));
647 
648     return_VOID;
649 }
650 
651 
652 /*******************************************************************************
653  *
654  * FUNCTION:    AcpiEvAttachRegion
655  *
656  * PARAMETERS:  HandlerObj          - Handler Object
657  *              RegionObj           - Region Object
658  *              AcpiNsIsLocked      - Namespace Region Already Locked?
659  *
660  * RETURN:      None
661  *
662  * DESCRIPTION: Create the association between the handler and the region
663  *              this is a two way association.
664  *
665  ******************************************************************************/
666 
667 ACPI_STATUS
668 AcpiEvAttachRegion (
669     ACPI_OPERAND_OBJECT     *HandlerObj,
670     ACPI_OPERAND_OBJECT     *RegionObj,
671     BOOLEAN                 AcpiNsIsLocked)
672 {
673 
674     ACPI_FUNCTION_TRACE (EvAttachRegion);
675 
676 
677     /* Install the region's handler */
678 
679     if (RegionObj->Region.Handler)
680     {
681         return_ACPI_STATUS (AE_ALREADY_EXISTS);
682     }
683 
684     ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
685         "Adding Region [%4.4s] %p to address handler %p [%s]\n",
686         AcpiUtGetNodeName (RegionObj->Region.Node),
687         RegionObj, HandlerObj,
688         AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
689 
690     /* Link this region to the front of the handler's list */
691 
692     RegionObj->Region.Next = HandlerObj->AddressSpace.RegionList;
693     HandlerObj->AddressSpace.RegionList = RegionObj;
694     RegionObj->Region.Handler = HandlerObj;
695     AcpiUtAddReference (HandlerObj);
696 
697     return_ACPI_STATUS (AE_OK);
698 }
699 
700 
701 /*******************************************************************************
702  *
703  * FUNCTION:    AcpiEvExecuteRegMethod
704  *
705  * PARAMETERS:  RegionObj           - Region object
706  *              Function            - Passed to _REG: On (1) or Off (0)
707  *
708  * RETURN:      Status
709  *
710  * DESCRIPTION: Execute _REG method for a region
711  *
712  ******************************************************************************/
713 
714 ACPI_STATUS
715 AcpiEvExecuteRegMethod (
716     ACPI_OPERAND_OBJECT     *RegionObj,
717     UINT32                  Function)
718 {
719     ACPI_EVALUATE_INFO      *Info;
720     ACPI_OPERAND_OBJECT     *Args[3];
721     ACPI_OPERAND_OBJECT     *RegionObj2;
722     const ACPI_NAME         *RegNamePtr = ACPI_CAST_PTR (ACPI_NAME, METHOD_NAME__REG);
723     ACPI_NAMESPACE_NODE     *MethodNode;
724     ACPI_NAMESPACE_NODE     *Node;
725     ACPI_STATUS             Status;
726 
727 
728     ACPI_FUNCTION_TRACE (EvExecuteRegMethod);
729 
730 
731     if (!AcpiGbl_NamespaceInitialized ||
732         RegionObj->Region.Handler == NULL)
733     {
734         return_ACPI_STATUS (AE_OK);
735     }
736 
737     RegionObj2 = AcpiNsGetSecondaryObject (RegionObj);
738     if (!RegionObj2)
739     {
740         return_ACPI_STATUS (AE_NOT_EXIST);
741     }
742 
743     /*
744      * Find any "_REG" method associated with this region definition.
745      * The method should always be updated as this function may be
746      * invoked after a namespace change.
747      */
748     Node = RegionObj->Region.Node->Parent;
749     Status = AcpiNsSearchOneScope (
750         *RegNamePtr, Node, ACPI_TYPE_METHOD, &MethodNode);
751     if (ACPI_SUCCESS (Status))
752     {
753         /*
754          * The _REG method is optional and there can be only one per
755          * region definition. This will be executed when the handler is
756          * attached or removed.
757          */
758         RegionObj2->Extra.Method_REG = MethodNode;
759     }
760     if (RegionObj2->Extra.Method_REG == NULL)
761     {
762         return_ACPI_STATUS (AE_OK);
763     }
764 
765     /* _REG(DISCONNECT) should be paired with _REG(CONNECT) */
766 
767     if ((Function == ACPI_REG_CONNECT &&
768         RegionObj->Common.Flags & AOPOBJ_REG_CONNECTED) ||
769         (Function == ACPI_REG_DISCONNECT &&
770          !(RegionObj->Common.Flags & AOPOBJ_REG_CONNECTED)))
771     {
772         return_ACPI_STATUS (AE_OK);
773     }
774 
775     /* Allocate and initialize the evaluation information block */
776 
777     Info = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_EVALUATE_INFO));
778     if (!Info)
779     {
780         return_ACPI_STATUS (AE_NO_MEMORY);
781     }
782 
783     Info->PrefixNode = RegionObj2->Extra.Method_REG;
784     Info->RelativePathname = NULL;
785     Info->Parameters = Args;
786     Info->Flags = ACPI_IGNORE_RETURN_VALUE;
787 
788     /*
789      * The _REG method has two arguments:
790      *
791      * Arg0 - Integer:
792      *  Operation region space ID Same value as RegionObj->Region.SpaceId
793      *
794      * Arg1 - Integer:
795      *  connection status 1 for connecting the handler, 0 for disconnecting
796      *  the handler (Passed as a parameter)
797      */
798     Args[0] = AcpiUtCreateIntegerObject ((UINT64) RegionObj->Region.SpaceId);
799     if (!Args[0])
800     {
801         Status = AE_NO_MEMORY;
802         goto Cleanup1;
803     }
804 
805     Args[1] = AcpiUtCreateIntegerObject ((UINT64) Function);
806     if (!Args[1])
807     {
808         Status = AE_NO_MEMORY;
809         goto Cleanup2;
810     }
811 
812     Args[2] = NULL; /* Terminate list */
813 
814     /* Execute the method, no return value */
815 
816     ACPI_DEBUG_EXEC (
817         AcpiUtDisplayInitPathname (ACPI_TYPE_METHOD, Info->PrefixNode, NULL));
818 
819     Status = AcpiNsEvaluate (Info);
820     AcpiUtRemoveReference (Args[1]);
821 
822     if (ACPI_FAILURE (Status))
823     {
824         goto Cleanup2;
825     }
826 
827     if (Function == ACPI_REG_CONNECT)
828     {
829         RegionObj->Common.Flags |= AOPOBJ_REG_CONNECTED;
830     }
831     else
832     {
833         RegionObj->Common.Flags &= ~AOPOBJ_REG_CONNECTED;
834     }
835 
836 Cleanup2:
837     AcpiUtRemoveReference (Args[0]);
838 
839 Cleanup1:
840     ACPI_FREE (Info);
841     return_ACPI_STATUS (Status);
842 }
843 
844 
845 /*******************************************************************************
846  *
847  * FUNCTION:    AcpiEvExecuteRegMethods
848  *
849  * PARAMETERS:  Node            - Namespace node for the device
850  *              SpaceId         - The address space ID
851  *              Function        - Passed to _REG: On (1) or Off (0)
852  *
853  * RETURN:      None
854  *
855  * DESCRIPTION: Run all _REG methods for the input Space ID;
856  *              Note: assumes namespace is locked, or system init time.
857  *
858  ******************************************************************************/
859 
860 void
861 AcpiEvExecuteRegMethods (
862     ACPI_NAMESPACE_NODE     *Node,
863     ACPI_ADR_SPACE_TYPE     SpaceId,
864     UINT32                  Function)
865 {
866     ACPI_REG_WALK_INFO      Info;
867 
868 
869     ACPI_FUNCTION_TRACE (EvExecuteRegMethods);
870 
871     /*
872      * These address spaces do not need a call to _REG, since the ACPI
873      * specification defines them as: "must always be accessible". Since
874      * they never change state (never become unavailable), no need to ever
875      * call _REG on them. Also, a DataTable is not a "real" address space,
876      * so do not call _REG. September 2018.
877      */
878     if ((SpaceId == ACPI_ADR_SPACE_SYSTEM_MEMORY) ||
879         (SpaceId == ACPI_ADR_SPACE_SYSTEM_IO) ||
880         (SpaceId == ACPI_ADR_SPACE_DATA_TABLE))
881     {
882         return_VOID;
883     }
884 
885     Info.SpaceId = SpaceId;
886     Info.Function = Function;
887     Info.RegRunCount = 0;
888 
889     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_NAMES,
890         "    Running _REG methods for SpaceId %s\n",
891         AcpiUtGetRegionName (Info.SpaceId)));
892 
893     /*
894      * Run all _REG methods for all Operation Regions for this space ID. This
895      * is a separate walk in order to handle any interdependencies between
896      * regions and _REG methods. (i.e. handlers must be installed for all
897      * regions of this Space ID before we can run any _REG methods)
898      */
899     (void) AcpiNsWalkNamespace (ACPI_TYPE_ANY, Node, ACPI_UINT32_MAX,
900         ACPI_NS_WALK_UNLOCK, AcpiEvRegRun, NULL, &Info, NULL);
901 
902     /*
903      * Special case for EC and GPIO: handle "orphan" _REG methods with
904      * no region.
905      */
906     if (SpaceId == ACPI_ADR_SPACE_EC || SpaceId == ACPI_ADR_SPACE_GPIO)
907     {
908         AcpiEvExecuteOrphanRegMethod (Node, SpaceId);
909     }
910 
911     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_NAMES,
912         "    Executed %u _REG methods for SpaceId %s\n",
913         Info.RegRunCount, AcpiUtGetRegionName (Info.SpaceId)));
914 
915     return_VOID;
916 }
917 
918 
919 /*******************************************************************************
920  *
921  * FUNCTION:    AcpiEvRegRun
922  *
923  * PARAMETERS:  WalkNamespace callback
924  *
925  * DESCRIPTION: Run _REG method for region objects of the requested spaceID
926  *
927  ******************************************************************************/
928 
929 static ACPI_STATUS
930 AcpiEvRegRun (
931     ACPI_HANDLE             ObjHandle,
932     UINT32                  Level,
933     void                    *Context,
934     void                    **ReturnValue)
935 {
936     ACPI_OPERAND_OBJECT     *ObjDesc;
937     ACPI_NAMESPACE_NODE     *Node;
938     ACPI_STATUS             Status;
939     ACPI_REG_WALK_INFO      *Info;
940 
941 
942     Info = ACPI_CAST_PTR (ACPI_REG_WALK_INFO, Context);
943 
944     /* Convert and validate the device handle */
945 
946     Node = AcpiNsValidateHandle (ObjHandle);
947     if (!Node)
948     {
949         return (AE_BAD_PARAMETER);
950     }
951 
952     /*
953      * We only care about regions and objects that are allowed to have
954      * address space handlers
955      */
956     if ((Node->Type != ACPI_TYPE_REGION) &&
957         (Node != AcpiGbl_RootNode))
958     {
959         return (AE_OK);
960     }
961 
962     /* Check for an existing internal object */
963 
964     ObjDesc = AcpiNsGetAttachedObject (Node);
965     if (!ObjDesc)
966     {
967         /* No object, just exit */
968 
969         return (AE_OK);
970     }
971 
972     /* Object is a Region */
973 
974     if (ObjDesc->Region.SpaceId != Info->SpaceId)
975     {
976         /* This region is for a different address space, just ignore it */
977 
978         return (AE_OK);
979     }
980 
981     Info->RegRunCount++;
982     Status = AcpiEvExecuteRegMethod (ObjDesc, Info->Function);
983     return (Status);
984 }
985 
986 
987 /*******************************************************************************
988  *
989  * FUNCTION:    AcpiEvExecuteOrphanRegMethod
990  *
991  * PARAMETERS:  DeviceNode          - Namespace node for an ACPI device
992  *              SpaceId             - The address space ID
993  *
994  * RETURN:      None
995  *
996  * DESCRIPTION: Execute an "orphan" _REG method that appears under an ACPI
997  *              device. This is a _REG method that has no corresponding region
998  *              within the device's scope. ACPI tables depending on these
999  *              "orphan" _REG methods have been seen for both EC and GPIO
1000  *              Operation Regions. Presumably the Windows ACPI implementation
1001  *              always calls the _REG method independent of the presence of
1002  *              an actual Operation Region with the correct address space ID.
1003  *
1004  *  MUTEX:      Assumes the namespace is locked
1005  *
1006  ******************************************************************************/
1007 
1008 static void
1009 AcpiEvExecuteOrphanRegMethod (
1010     ACPI_NAMESPACE_NODE     *DeviceNode,
1011     ACPI_ADR_SPACE_TYPE     SpaceId)
1012 {
1013     ACPI_HANDLE             RegMethod;
1014     ACPI_NAMESPACE_NODE     *NextNode;
1015     ACPI_STATUS             Status;
1016     ACPI_OBJECT_LIST        Args;
1017     ACPI_OBJECT             Objects[2];
1018 
1019 
1020     ACPI_FUNCTION_TRACE (EvExecuteOrphanRegMethod);
1021 
1022 
1023     if (!DeviceNode)
1024     {
1025         return_VOID;
1026     }
1027 
1028     /* Namespace is currently locked, must release */
1029 
1030     (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);
1031 
1032     /* Get a handle to a _REG method immediately under the EC device */
1033 
1034     Status = AcpiGetHandle (DeviceNode, METHOD_NAME__REG, &RegMethod);
1035     if (ACPI_FAILURE (Status))
1036     {
1037         goto Exit; /* There is no _REG method present */
1038     }
1039 
1040     /*
1041      * Execute the _REG method only if there is no Operation Region in
1042      * this scope with the Embedded Controller space ID. Otherwise, it
1043      * will already have been executed. Note, this allows for Regions
1044      * with other space IDs to be present; but the code below will then
1045      * execute the _REG method with the EmbeddedControl SpaceID argument.
1046      */
1047     NextNode = AcpiNsGetNextNode (DeviceNode, NULL);
1048     while (NextNode)
1049     {
1050         if ((NextNode->Type == ACPI_TYPE_REGION) &&
1051             (NextNode->Object) &&
1052             (NextNode->Object->Region.SpaceId == SpaceId))
1053         {
1054             goto Exit; /* Do not execute the _REG */
1055         }
1056 
1057         NextNode = AcpiNsGetNextNode (DeviceNode, NextNode);
1058     }
1059 
1060     /* Evaluate the _REG(SpaceId,Connect) method */
1061 
1062     Args.Count = 2;
1063     Args.Pointer = Objects;
1064     Objects[0].Type = ACPI_TYPE_INTEGER;
1065     Objects[0].Integer.Value = SpaceId;
1066     Objects[1].Type = ACPI_TYPE_INTEGER;
1067     Objects[1].Integer.Value = ACPI_REG_CONNECT;
1068 
1069     (void) AcpiEvaluateObject (RegMethod, NULL, &Args, NULL);
1070 
1071 Exit:
1072     /* We ignore all errors from above, don't care */
1073 
1074     (void) AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
1075     return_VOID;
1076 }
1077