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 - 2020, 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 "acpi.h"
153 #include "accommon.h"
154 #include "acevents.h"
155 #include "acnamesp.h"
156 #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_PHYSICAL_ADDRESS   Address;
274 
275 
276     ACPI_FUNCTION_TRACE (EvAddressSpaceDispatch);
277 
278 
279     RegionObj2 = AcpiNsGetSecondaryObject (RegionObj);
280     if (!RegionObj2)
281     {
282         return_ACPI_STATUS (AE_NOT_EXIST);
283     }
284 
285     /* Ensure that there is a handler associated with this region */
286 
287     HandlerDesc = RegionObj->Region.Handler;
288     if (!HandlerDesc)
289     {
290         ACPI_ERROR ((AE_INFO,
291             "No handler for Region [%4.4s] (%p) [%s]",
292             AcpiUtGetNodeName (RegionObj->Region.Node),
293             RegionObj, AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
294 
295         return_ACPI_STATUS (AE_NOT_EXIST);
296     }
297 
298     Context = HandlerDesc->AddressSpace.Context;
299 
300     /*
301      * It may be the case that the region has never been initialized.
302      * Some types of regions require special init code
303      */
304     if (!(RegionObj->Region.Flags & AOPOBJ_SETUP_COMPLETE))
305     {
306         /* This region has not been initialized yet, do it */
307 
308         RegionSetup = HandlerDesc->AddressSpace.Setup;
309         if (!RegionSetup)
310         {
311             /* No initialization routine, exit with error */
312 
313             ACPI_ERROR ((AE_INFO,
314                 "No init routine for region(%p) [%s]",
315                 RegionObj, AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
316             return_ACPI_STATUS (AE_NOT_EXIST);
317         }
318 
319         /*
320          * We must exit the interpreter because the region setup will
321          * potentially execute control methods (for example, the _REG method
322          * for this region)
323          */
324         AcpiExExitInterpreter ();
325 
326         Status = RegionSetup (RegionObj, ACPI_REGION_ACTIVATE,
327             Context, &RegionContext);
328 
329         /* Re-enter the interpreter */
330 
331         AcpiExEnterInterpreter ();
332 
333         /* Check for failure of the Region Setup */
334 
335         if (ACPI_FAILURE (Status))
336         {
337             ACPI_EXCEPTION ((AE_INFO, Status,
338                 "During region initialization: [%s]",
339                 AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
340             return_ACPI_STATUS (Status);
341         }
342 
343         /* Region initialization may have been completed by RegionSetup */
344 
345         if (!(RegionObj->Region.Flags & AOPOBJ_SETUP_COMPLETE))
346         {
347             RegionObj->Region.Flags |= AOPOBJ_SETUP_COMPLETE;
348 
349             /*
350              * Save the returned context for use in all accesses to
351              * the handler for this particular region
352              */
353             if (!(RegionObj2->Extra.RegionContext))
354             {
355                 RegionObj2->Extra.RegionContext = RegionContext;
356             }
357         }
358     }
359 
360     /* We have everything we need, we can invoke the address space handler */
361 
362     Handler = HandlerDesc->AddressSpace.Handler;
363     Address = (RegionObj->Region.Address + RegionOffset);
364 
365     /*
366      * Special handling for GenericSerialBus and GeneralPurposeIo:
367      * There are three extra parameters that must be passed to the
368      * handler via the context:
369      *   1) Connection buffer, a resource template from Connection() op
370      *   2) Length of the above buffer
371      *   3) Actual access length from the AccessAs() op
372      *
373      * In addition, for GeneralPurposeIo, the Address and BitWidth fields
374      * are defined as follows:
375      *   1) Address is the pin number index of the field (bit offset from
376      *      the previous Connection)
377      *   2) BitWidth is the actual bit length of the field (number of pins)
378      */
379     if ((RegionObj->Region.SpaceId == ACPI_ADR_SPACE_GSBUS) &&
380         Context &&
381         FieldObj)
382     {
383         /* Get the Connection (ResourceTemplate) buffer */
384 
385         Context->Connection = FieldObj->Field.ResourceBuffer;
386         Context->Length = FieldObj->Field.ResourceLength;
387         Context->AccessLength = FieldObj->Field.AccessLength;
388     }
389     if ((RegionObj->Region.SpaceId == ACPI_ADR_SPACE_GPIO) &&
390         Context &&
391         FieldObj)
392     {
393         /* Get the Connection (ResourceTemplate) buffer */
394 
395         Context->Connection = FieldObj->Field.ResourceBuffer;
396         Context->Length = FieldObj->Field.ResourceLength;
397         Context->AccessLength = FieldObj->Field.AccessLength;
398         Address = FieldObj->Field.PinNumberIndex;
399         BitWidth = FieldObj->Field.BitLength;
400     }
401 
402     ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
403         "Handler %p (@%p) Address %8.8X%8.8X [%s]\n",
404         &RegionObj->Region.Handler->AddressSpace, Handler,
405         ACPI_FORMAT_UINT64 (Address),
406         AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
407 
408     if (!(HandlerDesc->AddressSpace.HandlerFlags &
409         ACPI_ADDR_HANDLER_DEFAULT_INSTALLED))
410     {
411         /*
412          * For handlers other than the default (supplied) handlers, we must
413          * exit the interpreter because the handler *might* block -- we don't
414          * know what it will do, so we can't hold the lock on the interpreter.
415          */
416         AcpiExExitInterpreter();
417     }
418 
419     /* Call the handler */
420 
421     Status = Handler (Function, Address, BitWidth, Value, Context,
422         RegionObj2->Extra.RegionContext);
423 
424     if (ACPI_FAILURE (Status))
425     {
426         ACPI_EXCEPTION ((AE_INFO, Status, "Returned by Handler for [%s]",
427             AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
428 
429         /*
430          * Special case for an EC timeout. These are seen so frequently
431          * that an additional error message is helpful
432          */
433         if ((RegionObj->Region.SpaceId == ACPI_ADR_SPACE_EC) &&
434             (Status == AE_TIME))
435         {
436             ACPI_ERROR ((AE_INFO,
437                 "Timeout from EC hardware or EC device driver"));
438         }
439     }
440 
441     if (!(HandlerDesc->AddressSpace.HandlerFlags &
442         ACPI_ADDR_HANDLER_DEFAULT_INSTALLED))
443     {
444         /*
445          * We just returned from a non-default handler, we must re-enter the
446          * interpreter
447          */
448         AcpiExEnterInterpreter ();
449     }
450 
451     return_ACPI_STATUS (Status);
452 }
453 
454 
455 /*******************************************************************************
456  *
457  * FUNCTION:    AcpiEvDetachRegion
458  *
459  * PARAMETERS:  RegionObj           - Region Object
460  *              AcpiNsIsLocked      - Namespace Region Already Locked?
461  *
462  * RETURN:      None
463  *
464  * DESCRIPTION: Break the association between the handler and the region
465  *              this is a two way association.
466  *
467  ******************************************************************************/
468 
469 void
470 AcpiEvDetachRegion (
471     ACPI_OPERAND_OBJECT     *RegionObj,
472     BOOLEAN                 AcpiNsIsLocked)
473 {
474     ACPI_OPERAND_OBJECT     *HandlerObj;
475     ACPI_OPERAND_OBJECT     *ObjDesc;
476     ACPI_OPERAND_OBJECT     *StartDesc;
477     ACPI_OPERAND_OBJECT     **LastObjPtr;
478     ACPI_ADR_SPACE_SETUP    RegionSetup;
479     void                    **RegionContext;
480     ACPI_OPERAND_OBJECT     *RegionObj2;
481     ACPI_STATUS             Status;
482 
483 
484     ACPI_FUNCTION_TRACE (EvDetachRegion);
485 
486 
487     RegionObj2 = AcpiNsGetSecondaryObject (RegionObj);
488     if (!RegionObj2)
489     {
490         return_VOID;
491     }
492     RegionContext = &RegionObj2->Extra.RegionContext;
493 
494     /* Get the address handler from the region object */
495 
496     HandlerObj = RegionObj->Region.Handler;
497     if (!HandlerObj)
498     {
499         /* This region has no handler, all done */
500 
501         return_VOID;
502     }
503 
504     /* Find this region in the handler's list */
505 
506     ObjDesc = HandlerObj->AddressSpace.RegionList;
507     StartDesc = ObjDesc;
508     LastObjPtr = &HandlerObj->AddressSpace.RegionList;
509 
510     while (ObjDesc)
511     {
512         /* Is this the correct Region? */
513 
514         if (ObjDesc == RegionObj)
515         {
516             ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
517                 "Removing Region %p from address handler %p\n",
518                 RegionObj, HandlerObj));
519 
520             /* This is it, remove it from the handler's list */
521 
522             *LastObjPtr = ObjDesc->Region.Next;
523             ObjDesc->Region.Next = NULL;        /* Must clear field */
524 
525             if (AcpiNsIsLocked)
526             {
527                 Status = AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);
528                 if (ACPI_FAILURE (Status))
529                 {
530                     return_VOID;
531                 }
532             }
533 
534             /* Now stop region accesses by executing the _REG method */
535 
536             Status = AcpiEvExecuteRegMethod (RegionObj, ACPI_REG_DISCONNECT);
537             if (ACPI_FAILURE (Status))
538             {
539                 ACPI_EXCEPTION ((AE_INFO, Status, "from region _REG, [%s]",
540                     AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
541             }
542 
543             if (AcpiNsIsLocked)
544             {
545                 Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
546                 if (ACPI_FAILURE (Status))
547                 {
548                     return_VOID;
549                 }
550             }
551 
552             /*
553              * If the region has been activated, call the setup handler with
554              * the deactivate notification
555              */
556             if (RegionObj->Region.Flags & AOPOBJ_SETUP_COMPLETE)
557             {
558                 RegionSetup = HandlerObj->AddressSpace.Setup;
559                 Status = RegionSetup (RegionObj, ACPI_REGION_DEACTIVATE,
560                     HandlerObj->AddressSpace.Context, RegionContext);
561 
562                 /*
563                  * RegionContext should have been released by the deactivate
564                  * operation. We don't need access to it anymore here.
565                  */
566                 if (RegionContext)
567                 {
568                     *RegionContext = NULL;
569                 }
570 
571                 /* Init routine may fail, Just ignore errors */
572 
573                 if (ACPI_FAILURE (Status))
574                 {
575                     ACPI_EXCEPTION ((AE_INFO, Status,
576                         "from region handler - deactivate, [%s]",
577                         AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
578                 }
579 
580                 RegionObj->Region.Flags &= ~(AOPOBJ_SETUP_COMPLETE);
581             }
582 
583             /*
584              * Remove handler reference in the region
585              *
586              * NOTE: this doesn't mean that the region goes away, the region
587              * is just inaccessible as indicated to the _REG method
588              *
589              * If the region is on the handler's list, this must be the
590              * region's handler
591              */
592             RegionObj->Region.Handler = NULL;
593             AcpiUtRemoveReference (HandlerObj);
594 
595             return_VOID;
596         }
597 
598         /* Walk the linked list of handlers */
599 
600         LastObjPtr = &ObjDesc->Region.Next;
601         ObjDesc = ObjDesc->Region.Next;
602 
603         /* Prevent infinite loop if list is corrupted */
604 
605         if (ObjDesc == StartDesc)
606         {
607             ACPI_ERROR ((AE_INFO,
608                 "Circular handler list in region object %p",
609                 RegionObj));
610             return_VOID;
611         }
612     }
613 
614     /* If we get here, the region was not in the handler's region list */
615 
616     ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
617         "Cannot remove region %p from address handler %p\n",
618         RegionObj, HandlerObj));
619 
620     return_VOID;
621 }
622 
623 
624 /*******************************************************************************
625  *
626  * FUNCTION:    AcpiEvAttachRegion
627  *
628  * PARAMETERS:  HandlerObj          - Handler Object
629  *              RegionObj           - Region Object
630  *              AcpiNsIsLocked      - Namespace Region Already Locked?
631  *
632  * RETURN:      None
633  *
634  * DESCRIPTION: Create the association between the handler and the region
635  *              this is a two way association.
636  *
637  ******************************************************************************/
638 
639 ACPI_STATUS
640 AcpiEvAttachRegion (
641     ACPI_OPERAND_OBJECT     *HandlerObj,
642     ACPI_OPERAND_OBJECT     *RegionObj,
643     BOOLEAN                 AcpiNsIsLocked)
644 {
645 
646     ACPI_FUNCTION_TRACE (EvAttachRegion);
647 
648 
649     /* Install the region's handler */
650 
651     if (RegionObj->Region.Handler)
652     {
653         return_ACPI_STATUS (AE_ALREADY_EXISTS);
654     }
655 
656     ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
657         "Adding Region [%4.4s] %p to address handler %p [%s]\n",
658         AcpiUtGetNodeName (RegionObj->Region.Node),
659         RegionObj, HandlerObj,
660         AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
661 
662     /* Link this region to the front of the handler's list */
663 
664     RegionObj->Region.Next = HandlerObj->AddressSpace.RegionList;
665     HandlerObj->AddressSpace.RegionList = RegionObj;
666     RegionObj->Region.Handler = HandlerObj;
667     AcpiUtAddReference (HandlerObj);
668 
669     return_ACPI_STATUS (AE_OK);
670 }
671 
672 
673 /*******************************************************************************
674  *
675  * FUNCTION:    AcpiEvExecuteRegMethod
676  *
677  * PARAMETERS:  RegionObj           - Region object
678  *              Function            - Passed to _REG: On (1) or Off (0)
679  *
680  * RETURN:      Status
681  *
682  * DESCRIPTION: Execute _REG method for a region
683  *
684  ******************************************************************************/
685 
686 ACPI_STATUS
687 AcpiEvExecuteRegMethod (
688     ACPI_OPERAND_OBJECT     *RegionObj,
689     UINT32                  Function)
690 {
691     ACPI_EVALUATE_INFO      *Info;
692     ACPI_OPERAND_OBJECT     *Args[3];
693     ACPI_OPERAND_OBJECT     *RegionObj2;
694     const ACPI_NAME         *RegNamePtr = ACPI_CAST_PTR (ACPI_NAME, METHOD_NAME__REG);
695     ACPI_NAMESPACE_NODE     *MethodNode;
696     ACPI_NAMESPACE_NODE     *Node;
697     ACPI_STATUS             Status;
698 
699 
700     ACPI_FUNCTION_TRACE (EvExecuteRegMethod);
701 
702 
703     if (!AcpiGbl_NamespaceInitialized ||
704         RegionObj->Region.Handler == NULL)
705     {
706         return_ACPI_STATUS (AE_OK);
707     }
708 
709     RegionObj2 = AcpiNsGetSecondaryObject (RegionObj);
710     if (!RegionObj2)
711     {
712         return_ACPI_STATUS (AE_NOT_EXIST);
713     }
714 
715     /*
716      * Find any "_REG" method associated with this region definition.
717      * The method should always be updated as this function may be
718      * invoked after a namespace change.
719      */
720     Node = RegionObj->Region.Node->Parent;
721     Status = AcpiNsSearchOneScope (
722         *RegNamePtr, Node, ACPI_TYPE_METHOD, &MethodNode);
723     if (ACPI_SUCCESS (Status))
724     {
725         /*
726          * The _REG method is optional and there can be only one per
727          * region definition. This will be executed when the handler is
728          * attached or removed.
729          */
730         RegionObj2->Extra.Method_REG = MethodNode;
731     }
732     if (RegionObj2->Extra.Method_REG == NULL)
733     {
734         return_ACPI_STATUS (AE_OK);
735     }
736 
737     /* _REG(DISCONNECT) should be paired with _REG(CONNECT) */
738 
739     if ((Function == ACPI_REG_CONNECT &&
740         RegionObj->Common.Flags & AOPOBJ_REG_CONNECTED) ||
741         (Function == ACPI_REG_DISCONNECT &&
742          !(RegionObj->Common.Flags & AOPOBJ_REG_CONNECTED)))
743     {
744         return_ACPI_STATUS (AE_OK);
745     }
746 
747     /* Allocate and initialize the evaluation information block */
748 
749     Info = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_EVALUATE_INFO));
750     if (!Info)
751     {
752         return_ACPI_STATUS (AE_NO_MEMORY);
753     }
754 
755     Info->PrefixNode = RegionObj2->Extra.Method_REG;
756     Info->RelativePathname = NULL;
757     Info->Parameters = Args;
758     Info->Flags = ACPI_IGNORE_RETURN_VALUE;
759 
760     /*
761      * The _REG method has two arguments:
762      *
763      * Arg0 - Integer:
764      *  Operation region space ID Same value as RegionObj->Region.SpaceId
765      *
766      * Arg1 - Integer:
767      *  connection status 1 for connecting the handler, 0 for disconnecting
768      *  the handler (Passed as a parameter)
769      */
770     Args[0] = AcpiUtCreateIntegerObject ((UINT64) RegionObj->Region.SpaceId);
771     if (!Args[0])
772     {
773         Status = AE_NO_MEMORY;
774         goto Cleanup1;
775     }
776 
777     Args[1] = AcpiUtCreateIntegerObject ((UINT64) Function);
778     if (!Args[1])
779     {
780         Status = AE_NO_MEMORY;
781         goto Cleanup2;
782     }
783 
784     Args[2] = NULL; /* Terminate list */
785 
786     /* Execute the method, no return value */
787 
788     ACPI_DEBUG_EXEC (
789         AcpiUtDisplayInitPathname (ACPI_TYPE_METHOD, Info->PrefixNode, NULL));
790 
791     Status = AcpiNsEvaluate (Info);
792     AcpiUtRemoveReference (Args[1]);
793 
794     if (ACPI_FAILURE (Status))
795     {
796         goto Cleanup2;
797     }
798 
799     if (Function == ACPI_REG_CONNECT)
800     {
801         RegionObj->Common.Flags |= AOPOBJ_REG_CONNECTED;
802     }
803     else
804     {
805         RegionObj->Common.Flags &= ~AOPOBJ_REG_CONNECTED;
806     }
807 
808 Cleanup2:
809     AcpiUtRemoveReference (Args[0]);
810 
811 Cleanup1:
812     ACPI_FREE (Info);
813     return_ACPI_STATUS (Status);
814 }
815 
816 
817 /*******************************************************************************
818  *
819  * FUNCTION:    AcpiEvExecuteRegMethods
820  *
821  * PARAMETERS:  Node            - Namespace node for the device
822  *              SpaceId         - The address space ID
823  *              Function        - Passed to _REG: On (1) or Off (0)
824  *
825  * RETURN:      None
826  *
827  * DESCRIPTION: Run all _REG methods for the input Space ID;
828  *              Note: assumes namespace is locked, or system init time.
829  *
830  ******************************************************************************/
831 
832 void
833 AcpiEvExecuteRegMethods (
834     ACPI_NAMESPACE_NODE     *Node,
835     ACPI_ADR_SPACE_TYPE     SpaceId,
836     UINT32                  Function)
837 {
838     ACPI_REG_WALK_INFO      Info;
839 
840 
841     ACPI_FUNCTION_TRACE (EvExecuteRegMethods);
842 
843     /*
844      * These address spaces do not need a call to _REG, since the ACPI
845      * specification defines them as: "must always be accessible". Since
846      * they never change state (never become unavailable), no need to ever
847      * call _REG on them. Also, a DataTable is not a "real" address space,
848      * so do not call _REG. September 2018.
849      */
850     if ((SpaceId == ACPI_ADR_SPACE_SYSTEM_MEMORY) ||
851         (SpaceId == ACPI_ADR_SPACE_SYSTEM_IO) ||
852         (SpaceId == ACPI_ADR_SPACE_DATA_TABLE))
853     {
854         return_VOID;
855     }
856 
857     Info.SpaceId = SpaceId;
858     Info.Function = Function;
859     Info.RegRunCount = 0;
860 
861     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_NAMES,
862         "    Running _REG methods for SpaceId %s\n",
863         AcpiUtGetRegionName (Info.SpaceId)));
864 
865     /*
866      * Run all _REG methods for all Operation Regions for this space ID. This
867      * is a separate walk in order to handle any interdependencies between
868      * regions and _REG methods. (i.e. handlers must be installed for all
869      * regions of this Space ID before we can run any _REG methods)
870      */
871     (void) AcpiNsWalkNamespace (ACPI_TYPE_ANY, Node, ACPI_UINT32_MAX,
872         ACPI_NS_WALK_UNLOCK, AcpiEvRegRun, NULL, &Info, NULL);
873 
874     /*
875      * Special case for EC and GPIO: handle "orphan" _REG methods with
876      * no region.
877      */
878     if (SpaceId == ACPI_ADR_SPACE_EC || SpaceId == ACPI_ADR_SPACE_GPIO)
879     {
880         AcpiEvExecuteOrphanRegMethod (Node, SpaceId);
881     }
882 
883     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_NAMES,
884         "    Executed %u _REG methods for SpaceId %s\n",
885         Info.RegRunCount, AcpiUtGetRegionName (Info.SpaceId)));
886 
887     return_VOID;
888 }
889 
890 
891 /*******************************************************************************
892  *
893  * FUNCTION:    AcpiEvRegRun
894  *
895  * PARAMETERS:  WalkNamespace callback
896  *
897  * DESCRIPTION: Run _REG method for region objects of the requested spaceID
898  *
899  ******************************************************************************/
900 
901 static ACPI_STATUS
902 AcpiEvRegRun (
903     ACPI_HANDLE             ObjHandle,
904     UINT32                  Level,
905     void                    *Context,
906     void                    **ReturnValue)
907 {
908     ACPI_OPERAND_OBJECT     *ObjDesc;
909     ACPI_NAMESPACE_NODE     *Node;
910     ACPI_STATUS             Status;
911     ACPI_REG_WALK_INFO      *Info;
912 
913 
914     Info = ACPI_CAST_PTR (ACPI_REG_WALK_INFO, Context);
915 
916     /* Convert and validate the device handle */
917 
918     Node = AcpiNsValidateHandle (ObjHandle);
919     if (!Node)
920     {
921         return (AE_BAD_PARAMETER);
922     }
923 
924     /*
925      * We only care about regions and objects that are allowed to have
926      * address space handlers
927      */
928     if ((Node->Type != ACPI_TYPE_REGION) &&
929         (Node != AcpiGbl_RootNode))
930     {
931         return (AE_OK);
932     }
933 
934     /* Check for an existing internal object */
935 
936     ObjDesc = AcpiNsGetAttachedObject (Node);
937     if (!ObjDesc)
938     {
939         /* No object, just exit */
940 
941         return (AE_OK);
942     }
943 
944     /* Object is a Region */
945 
946     if (ObjDesc->Region.SpaceId != Info->SpaceId)
947     {
948         /* This region is for a different address space, just ignore it */
949 
950         return (AE_OK);
951     }
952 
953     Info->RegRunCount++;
954     Status = AcpiEvExecuteRegMethod (ObjDesc, Info->Function);
955     return (Status);
956 }
957 
958 
959 /*******************************************************************************
960  *
961  * FUNCTION:    AcpiEvExecuteOrphanRegMethod
962  *
963  * PARAMETERS:  DeviceNode          - Namespace node for an ACPI device
964  *              SpaceId             - The address space ID
965  *
966  * RETURN:      None
967  *
968  * DESCRIPTION: Execute an "orphan" _REG method that appears under an ACPI
969  *              device. This is a _REG method that has no corresponding region
970  *              within the device's scope. ACPI tables depending on these
971  *              "orphan" _REG methods have been seen for both EC and GPIO
972  *              Operation Regions. Presumably the Windows ACPI implementation
973  *              always calls the _REG method independent of the presence of
974  *              an actual Operation Region with the correct address space ID.
975  *
976  *  MUTEX:      Assumes the namespace is locked
977  *
978  ******************************************************************************/
979 
980 static void
981 AcpiEvExecuteOrphanRegMethod (
982     ACPI_NAMESPACE_NODE     *DeviceNode,
983     ACPI_ADR_SPACE_TYPE     SpaceId)
984 {
985     ACPI_HANDLE             RegMethod;
986     ACPI_NAMESPACE_NODE     *NextNode;
987     ACPI_STATUS             Status;
988     ACPI_OBJECT_LIST        Args;
989     ACPI_OBJECT             Objects[2];
990 
991 
992     ACPI_FUNCTION_TRACE (EvExecuteOrphanRegMethod);
993 
994 
995     if (!DeviceNode)
996     {
997         return_VOID;
998     }
999 
1000     /* Namespace is currently locked, must release */
1001 
1002     (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);
1003 
1004     /* Get a handle to a _REG method immediately under the EC device */
1005 
1006     Status = AcpiGetHandle (DeviceNode, METHOD_NAME__REG, &RegMethod);
1007     if (ACPI_FAILURE (Status))
1008     {
1009         goto Exit; /* There is no _REG method present */
1010     }
1011 
1012     /*
1013      * Execute the _REG method only if there is no Operation Region in
1014      * this scope with the Embedded Controller space ID. Otherwise, it
1015      * will already have been executed. Note, this allows for Regions
1016      * with other space IDs to be present; but the code below will then
1017      * execute the _REG method with the EmbeddedControl SpaceID argument.
1018      */
1019     NextNode = AcpiNsGetNextNode (DeviceNode, NULL);
1020     while (NextNode)
1021     {
1022         if ((NextNode->Type == ACPI_TYPE_REGION) &&
1023             (NextNode->Object) &&
1024             (NextNode->Object->Region.SpaceId == SpaceId))
1025         {
1026             goto Exit; /* Do not execute the _REG */
1027         }
1028 
1029         NextNode = AcpiNsGetNextNode (DeviceNode, NextNode);
1030     }
1031 
1032     /* Evaluate the _REG(SpaceId,Connect) method */
1033 
1034     Args.Count = 2;
1035     Args.Pointer = Objects;
1036     Objects[0].Type = ACPI_TYPE_INTEGER;
1037     Objects[0].Integer.Value = SpaceId;
1038     Objects[1].Type = ACPI_TYPE_INTEGER;
1039     Objects[1].Integer.Value = ACPI_REG_CONNECT;
1040 
1041     (void) AcpiEvaluateObject (RegMethod, NULL, &Args, NULL);
1042 
1043 Exit:
1044     /* We ignore all errors from above, don't care */
1045 
1046     (void) AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
1047     return_VOID;
1048 }
1049