xref: /illumos-gate/usr/src/cmd/acpi/iasl/aslopt.c (revision 8119dad84d6416f13557b0ba8e2aaf9064cbcfd3)
1 /******************************************************************************
2  *
3  * Module Name: aslopt- Compiler optimizations
4  *
5  *****************************************************************************/
6 
7 /******************************************************************************
8  *
9  * 1. Copyright Notice
10  *
11  * Some or all of this work - Copyright (c) 1999 - 2018, 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 "aslcompiler.h"
153 #include "aslcompiler.y.h"
154 
155 #include "acparser.h"
156 #include "amlcode.h"
157 #include "acnamesp.h"
158 
159 
160 #define _COMPONENT          ACPI_COMPILER
161         ACPI_MODULE_NAME    ("aslopt")
162 
163 
164 static UINT32               OptTotal = 0;
165 
166 /* Local prototypes */
167 
168 static ACPI_STATUS
169 OptSearchToRoot (
170     ACPI_PARSE_OBJECT       *Op,
171     ACPI_WALK_STATE         *WalkState,
172     ACPI_NAMESPACE_NODE     *CurrentNode,
173     ACPI_NAMESPACE_NODE     *TargetNode,
174     ACPI_BUFFER             *TargetPath,
175     char                    **NewPath);
176 
177 static ACPI_STATUS
178 OptBuildShortestPath (
179     ACPI_PARSE_OBJECT       *Op,
180     ACPI_WALK_STATE         *WalkState,
181     ACPI_NAMESPACE_NODE     *CurrentNode,
182     ACPI_NAMESPACE_NODE     *TargetNode,
183     ACPI_BUFFER             *CurrentPath,
184     ACPI_BUFFER             *TargetPath,
185     ACPI_SIZE               AmlNameStringLength,
186     UINT8                   IsDeclaration,
187     char                    **ReturnNewPath);
188 
189 static ACPI_STATUS
190 OptOptimizeNameDeclaration (
191     ACPI_PARSE_OBJECT       *Op,
192     ACPI_WALK_STATE         *WalkState,
193     ACPI_NAMESPACE_NODE     *CurrentNode,
194     ACPI_NAMESPACE_NODE     *TargetNode,
195     char                    *AmlNameString,
196     char                    **NewPath);
197 
198 
199 /*******************************************************************************
200  *
201  * FUNCTION:    OptSearchToRoot
202  *
203  * PARAMETERS:  Op                  - Current parser op
204  *              WalkState           - Current state
205  *              CurrentNode         - Where we are in the namespace
206  *              TargetNode          - Node to which we are referring
207  *              TargetPath          - External full path to the target node
208  *              NewPath             - Where the optimized path is returned
209  *
210  * RETURN:      Status
211  *
212  * DESCRIPTION: Attempt to optimize a reference to a single 4-character ACPI
213  *              name utilizing the search-to-root name resolution algorithm
214  *              that is used by AML interpreters.
215  *
216  ******************************************************************************/
217 
218 static ACPI_STATUS
219 OptSearchToRoot (
220     ACPI_PARSE_OBJECT       *Op,
221     ACPI_WALK_STATE         *WalkState,
222     ACPI_NAMESPACE_NODE     *CurrentNode,
223     ACPI_NAMESPACE_NODE     *TargetNode,
224     ACPI_BUFFER             *TargetPath,
225     char                    **NewPath)
226 {
227     ACPI_NAMESPACE_NODE     *Node;
228     ACPI_GENERIC_STATE      ScopeInfo;
229     ACPI_STATUS             Status;
230     char                    *Path;
231 
232 
233     ACPI_FUNCTION_NAME (OptSearchToRoot);
234 
235 
236     /*
237      * Check if search-to-root can be utilized. Use the last NameSeg of
238      * the NamePath and 1) See if can be found and 2) If found, make
239      * sure that it is the same node that we want. If there is another
240      * name in the search path before the one we want, the nodes will
241      * not match, and we cannot use this optimization.
242      */
243     Path = &(((char *) TargetPath->Pointer)[
244         TargetPath->Length - ACPI_NAME_SIZE]);
245     ScopeInfo.Scope.Node = CurrentNode;
246 
247     /* Lookup the NameSeg using SEARCH_PARENT (search-to-root) */
248 
249     Status = AcpiNsLookup (&ScopeInfo, Path, ACPI_TYPE_ANY, ACPI_IMODE_EXECUTE,
250         ACPI_NS_SEARCH_PARENT | ACPI_NS_DONT_OPEN_SCOPE,
251         WalkState, &(Node));
252     if (ACPI_FAILURE (Status))
253     {
254         return (Status);
255     }
256 
257     /*
258      * We found the name, but we must check to make sure that the node
259      * matches. Otherwise, there is another identical name in the search
260      * path that precludes the use of this optimization.
261      */
262     if (Node != TargetNode)
263     {
264         /*
265          * This means that another object with the same name was found first,
266          * and we cannot use this optimization.
267          */
268         return (AE_NOT_FOUND);
269     }
270 
271     /* Found the node, we can use this optimization */
272 
273     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
274         "NAMESEG:   %-24s", Path));
275 
276     /* We must allocate a new string for the name (TargetPath gets deleted) */
277 
278     *NewPath = UtLocalCacheCalloc (ACPI_NAME_SIZE + 1);
279     strcpy (*NewPath, Path);
280 
281     if (strncmp (*NewPath, "_T_", 3))
282     {
283         AslError (ASL_OPTIMIZATION, ASL_MSG_SINGLE_NAME_OPTIMIZATION,
284             Op, *NewPath);
285     }
286 
287     return (AE_OK);
288 }
289 
290 
291 /*******************************************************************************
292  *
293  * FUNCTION:    OptBuildShortestPath
294  *
295  * PARAMETERS:  Op                  - Current parser op
296  *              WalkState           - Current state
297  *              CurrentNode         - Where we are in the namespace
298  *              TargetNode          - Node to which we are referring
299  *              CurrentPath         - External full path to the current node
300  *              TargetPath          - External full path to the target node
301  *              AmlNameStringLength - Length of the original namepath
302  *              IsDeclaration       - TRUE for declaration, FALSE for reference
303  *              ReturnNewPath       - Where the optimized path is returned
304  *
305  * RETURN:      Status
306  *
307  * DESCRIPTION: Build an optimal NamePath using carats
308  *
309  ******************************************************************************/
310 
311 static ACPI_STATUS
312 OptBuildShortestPath (
313     ACPI_PARSE_OBJECT       *Op,
314     ACPI_WALK_STATE         *WalkState,
315     ACPI_NAMESPACE_NODE     *CurrentNode,
316     ACPI_NAMESPACE_NODE     *TargetNode,
317     ACPI_BUFFER             *CurrentPath,
318     ACPI_BUFFER             *TargetPath,
319     ACPI_SIZE               AmlNameStringLength,
320     UINT8                   IsDeclaration,
321     char                    **ReturnNewPath)
322 {
323     UINT32                  NumCommonSegments;
324     UINT32                  MaxCommonSegments;
325     UINT32                  Index;
326     UINT32                  NumCarats;
327     UINT32                  i;
328     char                    *NewPathInternal;
329     char                    *NewPathExternal;
330     ACPI_NAMESPACE_NODE     *Node;
331     ACPI_GENERIC_STATE      ScopeInfo;
332     ACPI_STATUS             Status;
333     BOOLEAN                 SubPath = FALSE;
334 
335 
336     ACPI_FUNCTION_NAME (OptBuildShortestPath);
337 
338 
339     ScopeInfo.Scope.Node = CurrentNode;
340 
341     /*
342      * Determine the maximum number of NameSegs that the Target and Current paths
343      * can possibly have in common. (To optimize, we have to have at least 1)
344      *
345      * Note: The external NamePath string lengths are always a multiple of 5
346      * (ACPI_NAME_SIZE + separator)
347      */
348     MaxCommonSegments = TargetPath->Length / ACPI_PATH_SEGMENT_LENGTH;
349     if (CurrentPath->Length < TargetPath->Length)
350     {
351         MaxCommonSegments = CurrentPath->Length / ACPI_PATH_SEGMENT_LENGTH;
352     }
353 
354     /*
355      * Determine how many NameSegs the two paths have in common.
356      * (Starting from the root)
357      */
358     for (NumCommonSegments = 0;
359          NumCommonSegments < MaxCommonSegments;
360          NumCommonSegments++)
361     {
362         /* Compare two single NameSegs */
363 
364         Index = (NumCommonSegments * ACPI_PATH_SEGMENT_LENGTH) + 1;
365 
366         if (!ACPI_COMPARE_NAME (
367             &(ACPI_CAST_PTR (char, TargetPath->Pointer)) [Index],
368             &(ACPI_CAST_PTR (char, CurrentPath->Pointer)) [Index]))
369         {
370             /* Mismatch */
371 
372             break;
373         }
374     }
375 
376     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, " COMMON: %u",
377         NumCommonSegments));
378 
379     /* There must be at least 1 common NameSeg in order to optimize */
380 
381     if (NumCommonSegments == 0)
382     {
383         return (AE_NOT_FOUND);
384     }
385 
386     if (NumCommonSegments == MaxCommonSegments)
387     {
388         if (CurrentPath->Length == TargetPath->Length)
389         {
390             ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, " SAME PATH"));
391             return (AE_NOT_FOUND);
392         }
393         else
394         {
395             ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, " SUBPATH"));
396             SubPath = TRUE;
397         }
398     }
399 
400     /* Determine how many prefix Carats are required */
401 
402     NumCarats = (CurrentPath->Length / ACPI_PATH_SEGMENT_LENGTH) -
403         NumCommonSegments;
404 
405     /*
406      * Construct a new target string
407      */
408     NewPathExternal =
409         ACPI_ALLOCATE_ZEROED (TargetPath->Length + NumCarats + 1);
410 
411     /* Insert the Carats into the Target string */
412 
413     for (i = 0; i < NumCarats; i++)
414     {
415         NewPathExternal[i] = AML_PARENT_PREFIX;
416     }
417 
418     /*
419      * Copy only the necessary (optimal) segments from the original
420      * target string
421      */
422     Index = (NumCommonSegments * ACPI_PATH_SEGMENT_LENGTH) + 1;
423 
424     /* Special handling for exact subpath in a name declaration */
425 
426     if (IsDeclaration && SubPath &&
427         (CurrentPath->Length > TargetPath->Length))
428     {
429         /*
430          * The current path is longer than the target, and the target is a
431          * subpath of the current path. We must include one more NameSeg of
432          * the target path
433          */
434         Index -= ACPI_PATH_SEGMENT_LENGTH;
435 
436         /* Special handling for Scope() operator */
437 
438         if (Op->Asl.AmlOpcode == AML_SCOPE_OP)
439         {
440             NewPathExternal[i] = AML_PARENT_PREFIX;
441             i++;
442             ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, "(EXTRA ^)"));
443         }
444     }
445 
446     /* Make sure we haven't gone off the end of the target path */
447 
448     if (Index > TargetPath->Length)
449     {
450         Index = TargetPath->Length;
451     }
452 
453     strcpy (&NewPathExternal[i],
454         &(ACPI_CAST_PTR (char, TargetPath->Pointer))[Index]);
455     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, " %-24s", NewPathExternal));
456 
457     /*
458      * Internalize the new target string and check it against the original
459      * string to make sure that this is in fact an optimization. If the
460      * original string is already optimal, there is no point in continuing.
461      */
462     Status = AcpiNsInternalizeName (NewPathExternal, &NewPathInternal);
463     if (ACPI_FAILURE (Status))
464     {
465         AslCoreSubsystemError (Op, Status, "Internalizing new NamePath",
466             ASL_NO_ABORT);
467         goto Cleanup;
468     }
469 
470     if (strlen (NewPathInternal) >= AmlNameStringLength)
471     {
472         ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
473             " NOT SHORTER (New %u old %u)",
474             (UINT32) strlen (NewPathInternal),
475             (UINT32) AmlNameStringLength));
476 
477         ACPI_FREE (NewPathInternal);
478         Status = AE_NOT_FOUND;
479         goto Cleanup;
480     }
481 
482     /*
483      * Check to make sure that the optimization finds the node we are
484      * looking for. This is simply a sanity check on the new
485      * path that has been created.
486      */
487     Status = AcpiNsLookup (&ScopeInfo, NewPathInternal,
488         ACPI_TYPE_ANY, ACPI_IMODE_EXECUTE,
489         ACPI_NS_DONT_OPEN_SCOPE, WalkState, &(Node));
490     if (ACPI_SUCCESS (Status))
491     {
492         /* Found the namepath, but make sure the node is correct */
493 
494         if (Node == TargetNode)
495         {
496             /* The lookup matched the node, accept this optimization */
497 
498             AslError (ASL_OPTIMIZATION, ASL_MSG_NAME_OPTIMIZATION,
499                 Op, NewPathExternal);
500             *ReturnNewPath = NewPathInternal;
501         }
502         else
503         {
504             /* Node is not correct, do not use this optimization */
505 
506             Status = AE_NOT_FOUND;
507             ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, " ***** WRONG NODE"));
508             AslError (ASL_WARNING, ASL_MSG_COMPILER_INTERNAL, Op,
509                 "Not using optimized name - found wrong node");
510         }
511     }
512     else
513     {
514         /* The lookup failed, we obviously cannot use this optimization */
515 
516         ACPI_FREE (NewPathInternal);
517 
518         ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, " ***** NOT FOUND"));
519         AslError (ASL_WARNING, ASL_MSG_COMPILER_INTERNAL, Op,
520             "Not using optimized name - did not find node");
521     }
522 
523 Cleanup:
524 
525     ACPI_FREE (NewPathExternal);
526     return (Status);
527 }
528 
529 
530 /*******************************************************************************
531  *
532  * FUNCTION:    OptOptimizeNameDeclaration
533  *
534  * PARAMETERS:  Op                  - Current parser op
535  *              WalkState           - Current state
536  *              CurrentNode         - Where we are in the namespace
537  *              AmlNameString       - Unoptimized namepath
538  *              NewPath             - Where the optimized path is returned
539  *
540  * RETURN:      Status. AE_OK If path is optimized
541  *
542  * DESCRIPTION: Perform a simple optimization of removing an extraneous
543  *              backslash prefix if we are already at the root scope.
544  *
545  ******************************************************************************/
546 
547 static ACPI_STATUS
548 OptOptimizeNameDeclaration (
549     ACPI_PARSE_OBJECT       *Op,
550     ACPI_WALK_STATE         *WalkState,
551     ACPI_NAMESPACE_NODE     *CurrentNode,
552     ACPI_NAMESPACE_NODE     *TargetNode,
553     char                    *AmlNameString,
554     char                    **NewPath)
555 {
556     ACPI_STATUS             Status;
557     char                    *NewPathExternal;
558     ACPI_NAMESPACE_NODE     *Node;
559 
560 
561     ACPI_FUNCTION_TRACE (OptOptimizeNameDeclaration);
562 
563 
564     if (((CurrentNode == AcpiGbl_RootNode) ||
565         (Op->Common.Parent->Asl.ParseOpcode == PARSEOP_DEFINITION_BLOCK)) &&
566             (ACPI_IS_ROOT_PREFIX (AmlNameString[0])))
567     {
568         /*
569          * The current scope is the root, and the namepath has a root prefix
570          * that is therefore extraneous. Remove it.
571          */
572         *NewPath = &AmlNameString[1];
573 
574         /* Debug output */
575 
576         Status = AcpiNsExternalizeName (ACPI_UINT32_MAX, *NewPath,
577             NULL, &NewPathExternal);
578         if (ACPI_FAILURE (Status))
579         {
580             AslCoreSubsystemError (Op, Status, "Externalizing NamePath",
581                 ASL_NO_ABORT);
582             return (Status);
583         }
584 
585         /*
586          * Check to make sure that the optimization finds the node we are
587          * looking for. This is simply a sanity check on the new
588          * path that has been created.
589          *
590          * We know that we are at the root, so NULL is used for the scope.
591          */
592         Status = AcpiNsLookup (NULL, *NewPath,
593             ACPI_TYPE_ANY, ACPI_IMODE_EXECUTE,
594             ACPI_NS_DONT_OPEN_SCOPE, WalkState, &(Node));
595         if (ACPI_SUCCESS (Status))
596         {
597             /* Found the namepath, but make sure the node is correct */
598 
599             if (Node == TargetNode)
600             {
601                 /* The lookup matched the node, accept this optimization */
602 
603                 AslError (ASL_OPTIMIZATION, ASL_MSG_NAME_OPTIMIZATION,
604                     Op, NewPathExternal);
605 
606                 ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
607                     "AT ROOT:   %-24s", NewPathExternal));
608             }
609             else
610             {
611                 /* Node is not correct, do not use this optimization */
612 
613                 Status = AE_NOT_FOUND;
614                 ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
615                     " ***** WRONG NODE"));
616                 AslError (ASL_WARNING, ASL_MSG_COMPILER_INTERNAL, Op,
617                     "Not using optimized name - found wrong node");
618             }
619         }
620         else
621         {
622             /* The lookup failed, we obviously cannot use this optimization */
623 
624             ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
625                 " ***** NOT FOUND"));
626             AslError (ASL_WARNING, ASL_MSG_COMPILER_INTERNAL, Op,
627                 "Not using optimized name - did not find node");
628         }
629 
630         ACPI_FREE (NewPathExternal);
631         return (Status);
632     }
633 
634     /* Could not optimize */
635 
636     return (AE_NOT_FOUND);
637 }
638 
639 
640 /*******************************************************************************
641  *
642  * FUNCTION:    OptOptimizeNamePath
643  *
644  * PARAMETERS:  Op                  - Current parser op
645  *              Flags               - Opcode info flags
646  *              WalkState           - Current state
647  *              AmlNameString       - Unoptimized namepath
648  *              TargetNode          - Node to which AmlNameString refers
649  *
650  * RETURN:      None. If path is optimized, the Op is updated with new path
651  *
652  * DESCRIPTION: Optimize a Named Declaration or Reference to the minimal length.
653  *              Must take into account both the current location in the
654  *              namespace and the actual reference path.
655  *
656  ******************************************************************************/
657 
658 void
659 OptOptimizeNamePath (
660     ACPI_PARSE_OBJECT       *Op,
661     UINT32                  Flags,
662     ACPI_WALK_STATE         *WalkState,
663     char                    *AmlNameString,
664     ACPI_NAMESPACE_NODE     *TargetNode)
665 {
666     ACPI_STATUS             Status;
667     ACPI_BUFFER             TargetPath;
668     ACPI_BUFFER             CurrentPath;
669     ACPI_SIZE               AmlNameStringLength;
670     ACPI_NAMESPACE_NODE     *CurrentNode;
671     char                    *ExternalNameString;
672     char                    *NewPath = NULL;
673     ACPI_SIZE               HowMuchShorter;
674     ACPI_PARSE_OBJECT       *NextOp;
675 
676 
677     ACPI_FUNCTION_TRACE (OptOptimizeNamePath);
678 
679 
680     /* This is an optional optimization */
681 
682     if (!Gbl_ReferenceOptimizationFlag)
683     {
684         return_VOID;
685     }
686 
687     /* Various required items */
688 
689     if (!TargetNode || !WalkState || !AmlNameString || !Op->Common.Parent)
690     {
691         return_VOID;
692     }
693 
694     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
695         "PATH OPTIMIZE: Line %5d ParentOp [%12.12s] ThisOp [%12.12s] ",
696         Op->Asl.LogicalLineNumber,
697         AcpiPsGetOpcodeName (Op->Common.Parent->Common.AmlOpcode),
698         AcpiPsGetOpcodeName (Op->Common.AmlOpcode)));
699 
700     if (!(Flags & (AML_NAMED | AML_CREATE)))
701     {
702         if (Op->Asl.CompileFlags & OP_IS_NAME_DECLARATION)
703         {
704             /* We don't want to fuss with actual name declaration nodes here */
705 
706             ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
707                 "******* NAME DECLARATION\n"));
708             return_VOID;
709         }
710     }
711 
712     /*
713      * The original path must be longer than one NameSeg (4 chars) for there
714      * to be any possibility that it can be optimized to a shorter string
715      */
716     AmlNameStringLength = strlen (AmlNameString);
717     if (AmlNameStringLength <= ACPI_NAME_SIZE)
718     {
719         ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
720             "NAMESEG %4.4s\n", AmlNameString));
721         return_VOID;
722     }
723 
724     /*
725      * We need to obtain the node that represents the current scope -- where
726      * we are right now in the namespace. We will compare this path
727      * against the Namepath, looking for commonality.
728      */
729     CurrentNode = AcpiGbl_RootNode;
730     if (WalkState->ScopeInfo)
731     {
732         CurrentNode = WalkState->ScopeInfo->Scope.Node;
733     }
734 
735     if (Flags & (AML_NAMED | AML_CREATE))
736     {
737         /* This is the declaration of a new name */
738 
739         ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, "NAME\n"));
740 
741         /*
742          * The node of interest is the parent of this node (the containing
743          * scope). The actual namespace node may be up more than one level
744          * of parse op or it may not exist at all (if we traverse back
745          * up to the root.)
746          */
747         NextOp = Op->Asl.Parent;
748         while (NextOp && (!NextOp->Asl.Node))
749         {
750             NextOp = NextOp->Asl.Parent;
751         }
752 
753         if (NextOp && NextOp->Asl.Node)
754         {
755             CurrentNode = NextOp->Asl.Node;
756         }
757         else
758         {
759             CurrentNode = AcpiGbl_RootNode;
760         }
761     }
762     else
763     {
764         /* This is a reference to an existing named object */
765 
766         ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, "REFERENCE\n"));
767     }
768 
769     /*
770      * Obtain the full paths to the two nodes that we are interested in
771      * (Target and current namespace location) in external
772      * format -- something we can easily manipulate
773      */
774     TargetPath.Length = ACPI_ALLOCATE_LOCAL_BUFFER;
775     Status = AcpiNsHandleToPathname (TargetNode, &TargetPath, FALSE);
776     if (ACPI_FAILURE (Status))
777     {
778         AslCoreSubsystemError (Op, Status, "Getting Target NamePath",
779             ASL_NO_ABORT);
780         return_VOID;
781     }
782 
783     TargetPath.Length--;    /* Subtract one for null terminator */
784 
785     /* CurrentPath is the path to this scope (where we are in the namespace) */
786 
787     CurrentPath.Length = ACPI_ALLOCATE_LOCAL_BUFFER;
788     Status = AcpiNsHandleToPathname (CurrentNode, &CurrentPath, FALSE);
789     if (ACPI_FAILURE (Status))
790     {
791         AslCoreSubsystemError (Op, Status, "Getting Current NamePath",
792             ASL_NO_ABORT);
793         return_VOID;
794     }
795 
796     CurrentPath.Length--;   /* Subtract one for null terminator */
797 
798     /* Debug output only */
799 
800     Status = AcpiNsExternalizeName (ACPI_UINT32_MAX, AmlNameString,
801         NULL, &ExternalNameString);
802     if (ACPI_FAILURE (Status))
803     {
804         AslCoreSubsystemError (Op, Status, "Externalizing NamePath",
805             ASL_NO_ABORT);
806         return_VOID;
807     }
808 
809     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
810         "CURRENT SCOPE: (%2u) %-37s FULL PATH TO NAME: (%2u) %-32s ACTUAL AML:%-32s\n",
811         (UINT32) CurrentPath.Length, (char *) CurrentPath.Pointer,
812         (UINT32) TargetPath.Length, (char *) TargetPath.Pointer,
813         ExternalNameString));
814 
815     ACPI_FREE (ExternalNameString);
816 
817     /*
818      * Attempt an optmization depending on the type of namepath
819      */
820     if (Flags & (AML_NAMED | AML_CREATE))
821     {
822         /*
823          * This is a named opcode and the namepath is a name declaration, not
824          * a reference.
825          */
826         Status = OptOptimizeNameDeclaration (Op, WalkState, CurrentNode,
827             TargetNode, AmlNameString, &NewPath);
828         if (ACPI_FAILURE (Status))
829         {
830             /*
831              * 2) now attempt to
832              *    optimize the namestring with carats (up-arrow)
833              */
834             Status = OptBuildShortestPath (Op, WalkState, CurrentNode,
835                 TargetNode, &CurrentPath, &TargetPath,
836                 AmlNameStringLength, 1, &NewPath);
837         }
838     }
839     else
840     {
841         /*
842          * This is a reference to an existing named object
843          *
844          * 1) Check if search-to-root can be utilized using the last
845          *    NameSeg of the NamePath
846          */
847         Status = OptSearchToRoot (Op, WalkState, CurrentNode,
848             TargetNode, &TargetPath, &NewPath);
849         if (ACPI_FAILURE (Status))
850         {
851             /*
852              * 2) Search-to-root could not be used, now attempt to
853              *    optimize the namestring with carats (up-arrow)
854              */
855             Status = OptBuildShortestPath (Op, WalkState, CurrentNode,
856                 TargetNode, &CurrentPath, &TargetPath,
857                 AmlNameStringLength, 0, &NewPath);
858         }
859     }
860 
861     /*
862      * Success from above indicates that the NamePath was successfully
863      * optimized. We need to update the parse op with the new name
864      */
865     if (ACPI_SUCCESS (Status))
866     {
867         HowMuchShorter = (AmlNameStringLength - strlen (NewPath));
868         OptTotal += HowMuchShorter;
869 
870         ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
871             " REDUCED BY %2u (TOTAL SAVED %2u)",
872             (UINT32) HowMuchShorter, OptTotal));
873 
874         if (Flags & AML_NAMED)
875         {
876             if (Op->Asl.AmlOpcode == AML_ALIAS_OP)
877             {
878                 /*
879                  * ALIAS is the only oddball opcode, the name declaration
880                  * (alias name) is the second operand
881                  */
882                 Op->Asl.Child->Asl.Next->Asl.Value.String = NewPath;
883                 Op->Asl.Child->Asl.Next->Asl.AmlLength = strlen (NewPath);
884             }
885             else
886             {
887                 Op->Asl.Child->Asl.Value.String = NewPath;
888                 Op->Asl.Child->Asl.AmlLength = strlen (NewPath);
889             }
890         }
891         else if (Flags & AML_CREATE)
892         {
893             /* Name must appear as the last parameter */
894 
895             NextOp = Op->Asl.Child;
896             while (!(NextOp->Asl.CompileFlags & OP_IS_NAME_DECLARATION))
897             {
898                 NextOp = NextOp->Asl.Next;
899             }
900             /* Update the parse node with the new NamePath */
901 
902             NextOp->Asl.Value.String = NewPath;
903             NextOp->Asl.AmlLength = strlen (NewPath);
904         }
905         else
906         {
907             /* Update the parse node with the new NamePath */
908 
909             Op->Asl.Value.String = NewPath;
910             Op->Asl.AmlLength = strlen (NewPath);
911         }
912     }
913     else
914     {
915         ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, " ALREADY OPTIMAL"));
916     }
917 
918     /* Cleanup path buffers */
919 
920     ACPI_FREE (TargetPath.Pointer);
921     ACPI_FREE (CurrentPath.Pointer);
922 
923     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, "\n"));
924     return_VOID;
925 }
926