qemu/hw/acpi/aml-build.c
<<
>>
Prefs
   1/* Support for generating ACPI tables and passing them to Guests
   2 *
   3 * Copyright (C) 2015 Red Hat Inc
   4 *
   5 * Author: Michael S. Tsirkin <mst@redhat.com>
   6 * Author: Igor Mammedov <imammedo@redhat.com>
   7 *
   8 * This program is free software; you can redistribute it and/or modify
   9 * it under the terms of the GNU General Public License as published by
  10 * the Free Software Foundation; either version 2 of the License, or
  11 * (at your option) any later version.
  12
  13 * This program is distributed in the hope that it will be useful,
  14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16 * GNU General Public License for more details.
  17
  18 * You should have received a copy of the GNU General Public License along
  19 * with this program; if not, see <http://www.gnu.org/licenses/>.
  20 */
  21
  22#include "qemu/osdep.h"
  23#include <glib/gprintf.h>
  24#include "hw/acpi/aml-build.h"
  25#include "qemu/bswap.h"
  26#include "qemu/bitops.h"
  27
  28static GArray *build_alloc_array(void)
  29{
  30    return g_array_new(false, true /* clear */, 1);
  31}
  32
  33static void build_free_array(GArray *array)
  34{
  35    g_array_free(array, true);
  36}
  37
  38static void build_prepend_byte(GArray *array, uint8_t val)
  39{
  40    g_array_prepend_val(array, val);
  41}
  42
  43static void build_append_byte(GArray *array, uint8_t val)
  44{
  45    g_array_append_val(array, val);
  46}
  47
  48static void build_append_array(GArray *array, GArray *val)
  49{
  50    g_array_append_vals(array, val->data, val->len);
  51}
  52
  53#define ACPI_NAMESEG_LEN 4
  54
  55static void
  56build_append_nameseg(GArray *array, const char *seg)
  57{
  58    int len;
  59
  60    len = strlen(seg);
  61    assert(len <= ACPI_NAMESEG_LEN);
  62
  63    g_array_append_vals(array, seg, len);
  64    /* Pad up to ACPI_NAMESEG_LEN characters if necessary. */
  65    g_array_append_vals(array, "____", ACPI_NAMESEG_LEN - len);
  66}
  67
  68static void GCC_FMT_ATTR(2, 0)
  69build_append_namestringv(GArray *array, const char *format, va_list ap)
  70{
  71    char *s;
  72    char **segs;
  73    char **segs_iter;
  74    int seg_count = 0;
  75
  76    s = g_strdup_vprintf(format, ap);
  77    segs = g_strsplit(s, ".", 0);
  78    g_free(s);
  79
  80    /* count segments */
  81    segs_iter = segs;
  82    while (*segs_iter) {
  83        ++segs_iter;
  84        ++seg_count;
  85    }
  86    /*
  87     * ACPI 5.0 spec: 20.2.2 Name Objects Encoding:
  88     * "SegCount can be from 1 to 255"
  89     */
  90    assert(seg_count > 0 && seg_count <= 255);
  91
  92    /* handle RootPath || PrefixPath */
  93    s = *segs;
  94    while (*s == '\\' || *s == '^') {
  95        build_append_byte(array, *s);
  96        ++s;
  97    }
  98
  99    switch (seg_count) {
 100    case 1:
 101        if (!*s) {
 102            build_append_byte(array, 0x00); /* NullName */
 103        } else {
 104            build_append_nameseg(array, s);
 105        }
 106        break;
 107
 108    case 2:
 109        build_append_byte(array, 0x2E); /* DualNamePrefix */
 110        build_append_nameseg(array, s);
 111        build_append_nameseg(array, segs[1]);
 112        break;
 113    default:
 114        build_append_byte(array, 0x2F); /* MultiNamePrefix */
 115        build_append_byte(array, seg_count);
 116
 117        /* handle the 1st segment manually due to prefix/root path */
 118        build_append_nameseg(array, s);
 119
 120        /* add the rest of segments */
 121        segs_iter = segs + 1;
 122        while (*segs_iter) {
 123            build_append_nameseg(array, *segs_iter);
 124            ++segs_iter;
 125        }
 126        break;
 127    }
 128    g_strfreev(segs);
 129}
 130
 131GCC_FMT_ATTR(2, 3)
 132static void build_append_namestring(GArray *array, const char *format, ...)
 133{
 134    va_list ap;
 135
 136    va_start(ap, format);
 137    build_append_namestringv(array, format, ap);
 138    va_end(ap);
 139}
 140
 141/* 5.4 Definition Block Encoding */
 142enum {
 143    PACKAGE_LENGTH_1BYTE_SHIFT = 6, /* Up to 63 - use extra 2 bits. */
 144    PACKAGE_LENGTH_2BYTE_SHIFT = 4,
 145    PACKAGE_LENGTH_3BYTE_SHIFT = 12,
 146    PACKAGE_LENGTH_4BYTE_SHIFT = 20,
 147};
 148
 149static void
 150build_prepend_package_length(GArray *package, unsigned length, bool incl_self)
 151{
 152    uint8_t byte;
 153    unsigned length_bytes;
 154
 155    if (length + 1 < (1 << PACKAGE_LENGTH_1BYTE_SHIFT)) {
 156        length_bytes = 1;
 157    } else if (length + 2 < (1 << PACKAGE_LENGTH_3BYTE_SHIFT)) {
 158        length_bytes = 2;
 159    } else if (length + 3 < (1 << PACKAGE_LENGTH_4BYTE_SHIFT)) {
 160        length_bytes = 3;
 161    } else {
 162        length_bytes = 4;
 163    }
 164
 165    /*
 166     * NamedField uses PkgLength encoding but it doesn't include length
 167     * of PkgLength itself.
 168     */
 169    if (incl_self) {
 170        /*
 171         * PkgLength is the length of the inclusive length of the data
 172         * and PkgLength's length itself when used for terms with
 173         * explitit length.
 174         */
 175        length += length_bytes;
 176    }
 177
 178    switch (length_bytes) {
 179    case 1:
 180        byte = length;
 181        build_prepend_byte(package, byte);
 182        return;
 183    case 4:
 184        byte = length >> PACKAGE_LENGTH_4BYTE_SHIFT;
 185        build_prepend_byte(package, byte);
 186        length &= (1 << PACKAGE_LENGTH_4BYTE_SHIFT) - 1;
 187        /* fall through */
 188    case 3:
 189        byte = length >> PACKAGE_LENGTH_3BYTE_SHIFT;
 190        build_prepend_byte(package, byte);
 191        length &= (1 << PACKAGE_LENGTH_3BYTE_SHIFT) - 1;
 192        /* fall through */
 193    case 2:
 194        byte = length >> PACKAGE_LENGTH_2BYTE_SHIFT;
 195        build_prepend_byte(package, byte);
 196        length &= (1 << PACKAGE_LENGTH_2BYTE_SHIFT) - 1;
 197        /* fall through */
 198    }
 199    /*
 200     * Most significant two bits of byte zero indicate how many following bytes
 201     * are in PkgLength encoding.
 202     */
 203    byte = ((length_bytes - 1) << PACKAGE_LENGTH_1BYTE_SHIFT) | length;
 204    build_prepend_byte(package, byte);
 205}
 206
 207static void
 208build_append_pkg_length(GArray *array, unsigned length, bool incl_self)
 209{
 210    GArray *tmp = build_alloc_array();
 211
 212    build_prepend_package_length(tmp, length, incl_self);
 213    build_append_array(array, tmp);
 214    build_free_array(tmp);
 215}
 216
 217static void build_package(GArray *package, uint8_t op)
 218{
 219    build_prepend_package_length(package, package->len, true);
 220    build_prepend_byte(package, op);
 221}
 222
 223static void build_extop_package(GArray *package, uint8_t op)
 224{
 225    build_package(package, op);
 226    build_prepend_byte(package, 0x5B); /* ExtOpPrefix */
 227}
 228
 229void build_append_int_noprefix(GArray *table, uint64_t value, int size)
 230{
 231    int i;
 232
 233    for (i = 0; i < size; ++i) {
 234        build_append_byte(table, value & 0xFF);
 235        value = value >> 8;
 236    }
 237}
 238
 239static void build_append_int(GArray *table, uint64_t value)
 240{
 241    if (value == 0x00) {
 242        build_append_byte(table, 0x00); /* ZeroOp */
 243    } else if (value == 0x01) {
 244        build_append_byte(table, 0x01); /* OneOp */
 245    } else if (value <= 0xFF) {
 246        build_append_byte(table, 0x0A); /* BytePrefix */
 247        build_append_int_noprefix(table, value, 1);
 248    } else if (value <= 0xFFFF) {
 249        build_append_byte(table, 0x0B); /* WordPrefix */
 250        build_append_int_noprefix(table, value, 2);
 251    } else if (value <= 0xFFFFFFFF) {
 252        build_append_byte(table, 0x0C); /* DWordPrefix */
 253        build_append_int_noprefix(table, value, 4);
 254    } else {
 255        build_append_byte(table, 0x0E); /* QWordPrefix */
 256        build_append_int_noprefix(table, value, 8);
 257    }
 258}
 259
 260/*
 261 * Build NAME(XXXX, 0x00000000) where 0x00000000 is encoded as a dword,
 262 * and return the offset to 0x00000000 for runtime patching.
 263 *
 264 * Warning: runtime patching is best avoided. Only use this as
 265 * a replacement for DataTableRegion (for guests that don't
 266 * support it).
 267 */
 268int
 269build_append_named_dword(GArray *array, const char *name_format, ...)
 270{
 271    int offset;
 272    va_list ap;
 273
 274    build_append_byte(array, 0x08); /* NameOp */
 275    va_start(ap, name_format);
 276    build_append_namestringv(array, name_format, ap);
 277    va_end(ap);
 278
 279    build_append_byte(array, 0x0C); /* DWordPrefix */
 280
 281    offset = array->len;
 282    build_append_int_noprefix(array, 0x00000000, 4);
 283    assert(array->len == offset + 4);
 284
 285    return offset;
 286}
 287
 288static GPtrArray *alloc_list;
 289
 290static Aml *aml_alloc(void)
 291{
 292    Aml *var = g_new0(typeof(*var), 1);
 293
 294    g_ptr_array_add(alloc_list, var);
 295    var->block_flags = AML_NO_OPCODE;
 296    var->buf = build_alloc_array();
 297    return var;
 298}
 299
 300static Aml *aml_opcode(uint8_t op)
 301{
 302    Aml *var = aml_alloc();
 303
 304    var->op  = op;
 305    var->block_flags = AML_OPCODE;
 306    return var;
 307}
 308
 309static Aml *aml_bundle(uint8_t op, AmlBlockFlags flags)
 310{
 311    Aml *var = aml_alloc();
 312
 313    var->op  = op;
 314    var->block_flags = flags;
 315    return var;
 316}
 317
 318static void aml_free(gpointer data, gpointer user_data)
 319{
 320    Aml *var = data;
 321    build_free_array(var->buf);
 322    g_free(var);
 323}
 324
 325Aml *init_aml_allocator(void)
 326{
 327    assert(!alloc_list);
 328    alloc_list = g_ptr_array_new();
 329    return aml_alloc();
 330}
 331
 332void free_aml_allocator(void)
 333{
 334    g_ptr_array_foreach(alloc_list, aml_free, NULL);
 335    g_ptr_array_free(alloc_list, true);
 336    alloc_list = 0;
 337}
 338
 339/* pack data with DefBuffer encoding */
 340static void build_buffer(GArray *array, uint8_t op)
 341{
 342    GArray *data = build_alloc_array();
 343
 344    build_append_int(data, array->len);
 345    g_array_prepend_vals(array, data->data, data->len);
 346    build_free_array(data);
 347    build_package(array, op);
 348}
 349
 350void aml_append(Aml *parent_ctx, Aml *child)
 351{
 352    GArray *buf = build_alloc_array();
 353    build_append_array(buf, child->buf);
 354
 355    switch (child->block_flags) {
 356    case AML_OPCODE:
 357        build_append_byte(parent_ctx->buf, child->op);
 358        break;
 359    case AML_EXT_PACKAGE:
 360        build_extop_package(buf, child->op);
 361        break;
 362    case AML_PACKAGE:
 363        build_package(buf, child->op);
 364        break;
 365    case AML_RES_TEMPLATE:
 366        build_append_byte(buf, 0x79); /* EndTag */
 367        /*
 368         * checksum operations are treated as succeeded if checksum
 369         * field is zero. [ACPI Spec 1.0b, 6.4.2.8 End Tag]
 370         */
 371        build_append_byte(buf, 0);
 372        /* fall through, to pack resources in buffer */
 373    case AML_BUFFER:
 374        build_buffer(buf, child->op);
 375        break;
 376    case AML_NO_OPCODE:
 377        break;
 378    default:
 379        assert(0);
 380        break;
 381    }
 382    build_append_array(parent_ctx->buf, buf);
 383    build_free_array(buf);
 384}
 385
 386/* ACPI 1.0b: 16.2.5.1 Namespace Modifier Objects Encoding: DefScope */
 387Aml *aml_scope(const char *name_format, ...)
 388{
 389    va_list ap;
 390    Aml *var = aml_bundle(0x10 /* ScopeOp */, AML_PACKAGE);
 391    va_start(ap, name_format);
 392    build_append_namestringv(var->buf, name_format, ap);
 393    va_end(ap);
 394    return var;
 395}
 396
 397/* ACPI 1.0b: 16.2.5.3 Type 1 Opcodes Encoding: DefReturn */
 398Aml *aml_return(Aml *val)
 399{
 400    Aml *var = aml_opcode(0xA4 /* ReturnOp */);
 401    aml_append(var, val);
 402    return var;
 403}
 404
 405/* ACPI 1.0b: 16.2.6.3 Debug Objects Encoding: DebugObj */
 406Aml *aml_debug(void)
 407{
 408    Aml *var = aml_alloc();
 409    build_append_byte(var->buf, 0x5B); /* ExtOpPrefix */
 410    build_append_byte(var->buf, 0x31); /* DebugOp */
 411    return var;
 412}
 413
 414/*
 415 * ACPI 1.0b: 16.2.3 Data Objects Encoding:
 416 * encodes: ByteConst, WordConst, DWordConst, QWordConst, ZeroOp, OneOp
 417 */
 418Aml *aml_int(const uint64_t val)
 419{
 420    Aml *var = aml_alloc();
 421    build_append_int(var->buf, val);
 422    return var;
 423}
 424
 425/*
 426 * helper to construct NameString, which returns Aml object
 427 * for using with aml_append or other aml_* terms
 428 */
 429Aml *aml_name(const char *name_format, ...)
 430{
 431    va_list ap;
 432    Aml *var = aml_alloc();
 433    va_start(ap, name_format);
 434    build_append_namestringv(var->buf, name_format, ap);
 435    va_end(ap);
 436    return var;
 437}
 438
 439/* ACPI 1.0b: 16.2.5.1 Namespace Modifier Objects Encoding: DefName */
 440Aml *aml_name_decl(const char *name, Aml *val)
 441{
 442    Aml *var = aml_opcode(0x08 /* NameOp */);
 443    build_append_namestring(var->buf, "%s", name);
 444    aml_append(var, val);
 445    return var;
 446}
 447
 448/* ACPI 1.0b: 16.2.6.1 Arg Objects Encoding */
 449Aml *aml_arg(int pos)
 450{
 451    uint8_t op = 0x68 /* ARG0 op */ + pos;
 452
 453    assert(pos <= 6);
 454    return aml_opcode(op);
 455}
 456
 457/* ACPI 2.0a: 17.2.4.4 Type 2 Opcodes Encoding: DefToInteger */
 458Aml *aml_to_integer(Aml *arg)
 459{
 460    Aml *var = aml_opcode(0x99 /* ToIntegerOp */);
 461    aml_append(var, arg);
 462    build_append_byte(var->buf, 0x00 /* NullNameOp */);
 463    return var;
 464}
 465
 466/* ACPI 2.0a: 17.2.4.4 Type 2 Opcodes Encoding: DefToHexString */
 467Aml *aml_to_hexstring(Aml *src, Aml *dst)
 468{
 469    Aml *var = aml_opcode(0x98 /* ToHexStringOp */);
 470    aml_append(var, src);
 471    if (dst) {
 472        aml_append(var, dst);
 473    } else {
 474        build_append_byte(var->buf, 0x00 /* NullNameOp */);
 475    }
 476    return var;
 477}
 478
 479/* ACPI 2.0a: 17.2.4.4 Type 2 Opcodes Encoding: DefToBuffer */
 480Aml *aml_to_buffer(Aml *src, Aml *dst)
 481{
 482    Aml *var = aml_opcode(0x96 /* ToBufferOp */);
 483    aml_append(var, src);
 484    if (dst) {
 485        aml_append(var, dst);
 486    } else {
 487        build_append_byte(var->buf, 0x00 /* NullNameOp */);
 488    }
 489    return var;
 490}
 491
 492/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefStore */
 493Aml *aml_store(Aml *val, Aml *target)
 494{
 495    Aml *var = aml_opcode(0x70 /* StoreOp */);
 496    aml_append(var, val);
 497    aml_append(var, target);
 498    return var;
 499}
 500
 501/**
 502 * build_opcode_2arg_dst:
 503 * @op: 1-byte opcode
 504 * @arg1: 1st operand
 505 * @arg2: 2nd operand
 506 * @dst: optional target to store to, set to NULL if it's not required
 507 *
 508 * An internal helper to compose AML terms that have
 509 *   "Op Operand Operand Target"
 510 * pattern.
 511 *
 512 * Returns: The newly allocated and composed according to patter Aml object.
 513 */
 514static Aml *
 515build_opcode_2arg_dst(uint8_t op, Aml *arg1, Aml *arg2, Aml *dst)
 516{
 517    Aml *var = aml_opcode(op);
 518    aml_append(var, arg1);
 519    aml_append(var, arg2);
 520    if (dst) {
 521        aml_append(var, dst);
 522    } else {
 523        build_append_byte(var->buf, 0x00 /* NullNameOp */);
 524    }
 525    return var;
 526}
 527
 528/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefAnd */
 529Aml *aml_and(Aml *arg1, Aml *arg2, Aml *dst)
 530{
 531    return build_opcode_2arg_dst(0x7B /* AndOp */, arg1, arg2, dst);
 532}
 533
 534/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefOr */
 535Aml *aml_or(Aml *arg1, Aml *arg2, Aml *dst)
 536{
 537    return build_opcode_2arg_dst(0x7D /* OrOp */, arg1, arg2, dst);
 538}
 539
 540/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefLOr */
 541Aml *aml_lor(Aml *arg1, Aml *arg2)
 542{
 543    Aml *var = aml_opcode(0x91 /* LOrOp */);
 544    aml_append(var, arg1);
 545    aml_append(var, arg2);
 546    return var;
 547}
 548
 549/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefShiftLeft */
 550Aml *aml_shiftleft(Aml *arg1, Aml *count)
 551{
 552    return build_opcode_2arg_dst(0x79 /* ShiftLeftOp */, arg1, count, NULL);
 553}
 554
 555/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefShiftRight */
 556Aml *aml_shiftright(Aml *arg1, Aml *count, Aml *dst)
 557{
 558    return build_opcode_2arg_dst(0x7A /* ShiftRightOp */, arg1, count, dst);
 559}
 560
 561/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefLLess */
 562Aml *aml_lless(Aml *arg1, Aml *arg2)
 563{
 564    Aml *var = aml_opcode(0x95 /* LLessOp */);
 565    aml_append(var, arg1);
 566    aml_append(var, arg2);
 567    return var;
 568}
 569
 570/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefAdd */
 571Aml *aml_add(Aml *arg1, Aml *arg2, Aml *dst)
 572{
 573    return build_opcode_2arg_dst(0x72 /* AddOp */, arg1, arg2, dst);
 574}
 575
 576/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefSubtract */
 577Aml *aml_subtract(Aml *arg1, Aml *arg2, Aml *dst)
 578{
 579    return build_opcode_2arg_dst(0x74 /* SubtractOp */, arg1, arg2, dst);
 580}
 581
 582/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefIncrement */
 583Aml *aml_increment(Aml *arg)
 584{
 585    Aml *var = aml_opcode(0x75 /* IncrementOp */);
 586    aml_append(var, arg);
 587    return var;
 588}
 589
 590/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefDecrement */
 591Aml *aml_decrement(Aml *arg)
 592{
 593    Aml *var = aml_opcode(0x76 /* DecrementOp */);
 594    aml_append(var, arg);
 595    return var;
 596}
 597
 598/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefIndex */
 599Aml *aml_index(Aml *arg1, Aml *idx)
 600{
 601    return build_opcode_2arg_dst(0x88 /* IndexOp */, arg1, idx, NULL);
 602}
 603
 604/* ACPI 1.0b: 16.2.5.3 Type 1 Opcodes Encoding: DefNotify */
 605Aml *aml_notify(Aml *arg1, Aml *arg2)
 606{
 607    Aml *var = aml_opcode(0x86 /* NotifyOp */);
 608    aml_append(var, arg1);
 609    aml_append(var, arg2);
 610    return var;
 611}
 612
 613/* helper to call method with 1 argument */
 614Aml *aml_call0(const char *method)
 615{
 616    Aml *var = aml_alloc();
 617    build_append_namestring(var->buf, "%s", method);
 618    return var;
 619}
 620
 621/* helper to call method with 1 argument */
 622Aml *aml_call1(const char *method, Aml *arg1)
 623{
 624    Aml *var = aml_alloc();
 625    build_append_namestring(var->buf, "%s", method);
 626    aml_append(var, arg1);
 627    return var;
 628}
 629
 630/* helper to call method with 2 arguments */
 631Aml *aml_call2(const char *method, Aml *arg1, Aml *arg2)
 632{
 633    Aml *var = aml_alloc();
 634    build_append_namestring(var->buf, "%s", method);
 635    aml_append(var, arg1);
 636    aml_append(var, arg2);
 637    return var;
 638}
 639
 640/* helper to call method with 3 arguments */
 641Aml *aml_call3(const char *method, Aml *arg1, Aml *arg2, Aml *arg3)
 642{
 643    Aml *var = aml_alloc();
 644    build_append_namestring(var->buf, "%s", method);
 645    aml_append(var, arg1);
 646    aml_append(var, arg2);
 647    aml_append(var, arg3);
 648    return var;
 649}
 650
 651/* helper to call method with 4 arguments */
 652Aml *aml_call4(const char *method, Aml *arg1, Aml *arg2, Aml *arg3, Aml *arg4)
 653{
 654    Aml *var = aml_alloc();
 655    build_append_namestring(var->buf, "%s", method);
 656    aml_append(var, arg1);
 657    aml_append(var, arg2);
 658    aml_append(var, arg3);
 659    aml_append(var, arg4);
 660    return var;
 661}
 662
 663/* helper to call method with 5 arguments */
 664Aml *aml_call5(const char *method, Aml *arg1, Aml *arg2, Aml *arg3, Aml *arg4,
 665               Aml *arg5)
 666{
 667    Aml *var = aml_alloc();
 668    build_append_namestring(var->buf, "%s", method);
 669    aml_append(var, arg1);
 670    aml_append(var, arg2);
 671    aml_append(var, arg3);
 672    aml_append(var, arg4);
 673    aml_append(var, arg5);
 674    return var;
 675}
 676
 677/*
 678 * ACPI 5.0: 6.4.3.8.1 GPIO Connection Descriptor
 679 * Type 1, Large Item Name 0xC
 680 */
 681
 682static Aml *aml_gpio_connection(AmlGpioConnectionType type,
 683                                AmlConsumerAndProducer con_and_pro,
 684                                uint8_t flags, AmlPinConfig pin_config,
 685                                uint16_t output_drive,
 686                                uint16_t debounce_timeout,
 687                                const uint32_t pin_list[], uint32_t pin_count,
 688                                const char *resource_source_name,
 689                                const uint8_t *vendor_data,
 690                                uint16_t vendor_data_len)
 691{
 692    Aml *var = aml_alloc();
 693    const uint16_t min_desc_len = 0x16;
 694    uint16_t resource_source_name_len, length;
 695    uint16_t pin_table_offset, resource_source_name_offset, vendor_data_offset;
 696    uint32_t i;
 697
 698    assert(resource_source_name);
 699    resource_source_name_len = strlen(resource_source_name) + 1;
 700    length = min_desc_len + resource_source_name_len + vendor_data_len;
 701    pin_table_offset = min_desc_len + 1;
 702    resource_source_name_offset = pin_table_offset + pin_count * 2;
 703    vendor_data_offset = resource_source_name_offset + resource_source_name_len;
 704
 705    build_append_byte(var->buf, 0x8C);  /* GPIO Connection Descriptor */
 706    build_append_int_noprefix(var->buf, length, 2); /* Length */
 707    build_append_byte(var->buf, 1);     /* Revision ID */
 708    build_append_byte(var->buf, type);  /* GPIO Connection Type */
 709    /* General Flags (2 bytes) */
 710    build_append_int_noprefix(var->buf, con_and_pro, 2);
 711    /* Interrupt and IO Flags (2 bytes) */
 712    build_append_int_noprefix(var->buf, flags, 2);
 713    /* Pin Configuration 0 = Default 1 = Pull-up 2 = Pull-down 3 = No Pull */
 714    build_append_byte(var->buf, pin_config);
 715    /* Output Drive Strength (2 bytes) */
 716    build_append_int_noprefix(var->buf, output_drive, 2);
 717    /* Debounce Timeout (2 bytes) */
 718    build_append_int_noprefix(var->buf, debounce_timeout, 2);
 719    /* Pin Table Offset (2 bytes) */
 720    build_append_int_noprefix(var->buf, pin_table_offset, 2);
 721    build_append_byte(var->buf, 0);     /* Resource Source Index */
 722    /* Resource Source Name Offset (2 bytes) */
 723    build_append_int_noprefix(var->buf, resource_source_name_offset, 2);
 724    /* Vendor Data Offset (2 bytes) */
 725    build_append_int_noprefix(var->buf, vendor_data_offset, 2);
 726    /* Vendor Data Length (2 bytes) */
 727    build_append_int_noprefix(var->buf, vendor_data_len, 2);
 728    /* Pin Number (2n bytes)*/
 729    for (i = 0; i < pin_count; i++) {
 730        build_append_int_noprefix(var->buf, pin_list[i], 2);
 731    }
 732
 733    /* Resource Source Name */
 734    build_append_namestring(var->buf, "%s", resource_source_name);
 735    build_append_byte(var->buf, '\0');
 736
 737    /* Vendor-defined Data */
 738    if (vendor_data != NULL) {
 739        g_array_append_vals(var->buf, vendor_data, vendor_data_len);
 740    }
 741
 742    return var;
 743}
 744
 745/*
 746 * ACPI 5.0: 19.5.53
 747 * GpioInt(GPIO Interrupt Connection Resource Descriptor Macro)
 748 */
 749Aml *aml_gpio_int(AmlConsumerAndProducer con_and_pro,
 750                  AmlLevelAndEdge edge_level,
 751                  AmlActiveHighAndLow active_level, AmlShared shared,
 752                  AmlPinConfig pin_config, uint16_t debounce_timeout,
 753                  const uint32_t pin_list[], uint32_t pin_count,
 754                  const char *resource_source_name,
 755                  const uint8_t *vendor_data, uint16_t vendor_data_len)
 756{
 757    uint8_t flags = edge_level | (active_level << 1) | (shared << 3);
 758
 759    return aml_gpio_connection(AML_INTERRUPT_CONNECTION, con_and_pro, flags,
 760                               pin_config, 0, debounce_timeout, pin_list,
 761                               pin_count, resource_source_name, vendor_data,
 762                               vendor_data_len);
 763}
 764
 765/*
 766 * ACPI 1.0b: 6.4.3.4 32-Bit Fixed Location Memory Range Descriptor
 767 * (Type 1, Large Item Name 0x6)
 768 */
 769Aml *aml_memory32_fixed(uint32_t addr, uint32_t size,
 770                        AmlReadAndWrite read_and_write)
 771{
 772    Aml *var = aml_alloc();
 773    build_append_byte(var->buf, 0x86); /* Memory32Fixed Resource Descriptor */
 774    build_append_byte(var->buf, 9);    /* Length, bits[7:0] value = 9 */
 775    build_append_byte(var->buf, 0);    /* Length, bits[15:8] value = 0 */
 776    build_append_byte(var->buf, read_and_write); /* Write status, 1 rw 0 ro */
 777
 778    /* Range base address */
 779    build_append_byte(var->buf, extract32(addr, 0, 8));  /* bits[7:0] */
 780    build_append_byte(var->buf, extract32(addr, 8, 8));  /* bits[15:8] */
 781    build_append_byte(var->buf, extract32(addr, 16, 8)); /* bits[23:16] */
 782    build_append_byte(var->buf, extract32(addr, 24, 8)); /* bits[31:24] */
 783
 784    /* Range length */
 785    build_append_byte(var->buf, extract32(size, 0, 8));  /* bits[7:0] */
 786    build_append_byte(var->buf, extract32(size, 8, 8));  /* bits[15:8] */
 787    build_append_byte(var->buf, extract32(size, 16, 8)); /* bits[23:16] */
 788    build_append_byte(var->buf, extract32(size, 24, 8)); /* bits[31:24] */
 789    return var;
 790}
 791
 792/*
 793 * ACPI 5.0: 6.4.3.6 Extended Interrupt Descriptor
 794 * Type 1, Large Item Name 0x9
 795 */
 796Aml *aml_interrupt(AmlConsumerAndProducer con_and_pro,
 797                   AmlLevelAndEdge level_and_edge,
 798                   AmlActiveHighAndLow high_and_low, AmlShared shared,
 799                   uint32_t *irq_list, uint8_t irq_count)
 800{
 801    int i;
 802    Aml *var = aml_alloc();
 803    uint8_t irq_flags = con_and_pro | (level_and_edge << 1)
 804                        | (high_and_low << 2) | (shared << 3);
 805    const int header_bytes_in_len = 2;
 806    uint16_t len = header_bytes_in_len + irq_count * sizeof(uint32_t);
 807
 808    assert(irq_count > 0);
 809
 810    build_append_byte(var->buf, 0x89); /* Extended irq descriptor */
 811    build_append_byte(var->buf, len & 0xFF); /* Length, bits[7:0] */
 812    build_append_byte(var->buf, len >> 8); /* Length, bits[15:8] */
 813    build_append_byte(var->buf, irq_flags); /* Interrupt Vector Information. */
 814    build_append_byte(var->buf, irq_count);   /* Interrupt table length */
 815
 816    /* Interrupt Number List */
 817    for (i = 0; i < irq_count; i++) {
 818        build_append_int_noprefix(var->buf, irq_list[i], 4);
 819    }
 820    return var;
 821}
 822
 823/* ACPI 1.0b: 6.4.2.5 I/O Port Descriptor */
 824Aml *aml_io(AmlIODecode dec, uint16_t min_base, uint16_t max_base,
 825            uint8_t aln, uint8_t len)
 826{
 827    Aml *var = aml_alloc();
 828    build_append_byte(var->buf, 0x47); /* IO port descriptor */
 829    build_append_byte(var->buf, dec);
 830    build_append_byte(var->buf, min_base & 0xff);
 831    build_append_byte(var->buf, (min_base >> 8) & 0xff);
 832    build_append_byte(var->buf, max_base & 0xff);
 833    build_append_byte(var->buf, (max_base >> 8) & 0xff);
 834    build_append_byte(var->buf, aln);
 835    build_append_byte(var->buf, len);
 836    return var;
 837}
 838
 839/*
 840 * ACPI 1.0b: 6.4.2.1.1 ASL Macro for IRQ Descriptor
 841 *
 842 * More verbose description at:
 843 * ACPI 5.0: 19.5.64 IRQNoFlags (Interrupt Resource Descriptor Macro)
 844 *           6.4.2.1 IRQ Descriptor
 845 */
 846Aml *aml_irq_no_flags(uint8_t irq)
 847{
 848    uint16_t irq_mask;
 849    Aml *var = aml_alloc();
 850
 851    assert(irq < 16);
 852    build_append_byte(var->buf, 0x22); /* IRQ descriptor 2 byte form */
 853
 854    irq_mask = 1U << irq;
 855    build_append_byte(var->buf, irq_mask & 0xFF); /* IRQ mask bits[7:0] */
 856    build_append_byte(var->buf, irq_mask >> 8); /* IRQ mask bits[15:8] */
 857    return var;
 858}
 859
 860/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefLNot */
 861Aml *aml_lnot(Aml *arg)
 862{
 863    Aml *var = aml_opcode(0x92 /* LNotOp */);
 864    aml_append(var, arg);
 865    return var;
 866}
 867
 868/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefLEqual */
 869Aml *aml_equal(Aml *arg1, Aml *arg2)
 870{
 871    Aml *var = aml_opcode(0x93 /* LequalOp */);
 872    aml_append(var, arg1);
 873    aml_append(var, arg2);
 874    return var;
 875}
 876
 877/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefLGreater */
 878Aml *aml_lgreater(Aml *arg1, Aml *arg2)
 879{
 880    Aml *var = aml_opcode(0x94 /* LGreaterOp */);
 881    aml_append(var, arg1);
 882    aml_append(var, arg2);
 883    return var;
 884}
 885
 886/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefLGreaterEqual */
 887Aml *aml_lgreater_equal(Aml *arg1, Aml *arg2)
 888{
 889    /* LGreaterEqualOp := LNotOp LLessOp */
 890    Aml *var = aml_opcode(0x92 /* LNotOp */);
 891    build_append_byte(var->buf, 0x95 /* LLessOp */);
 892    aml_append(var, arg1);
 893    aml_append(var, arg2);
 894    return var;
 895}
 896
 897/* ACPI 1.0b: 16.2.5.3 Type 1 Opcodes Encoding: DefIfElse */
 898Aml *aml_if(Aml *predicate)
 899{
 900    Aml *var = aml_bundle(0xA0 /* IfOp */, AML_PACKAGE);
 901    aml_append(var, predicate);
 902    return var;
 903}
 904
 905/* ACPI 1.0b: 16.2.5.3 Type 1 Opcodes Encoding: DefElse */
 906Aml *aml_else(void)
 907{
 908    Aml *var = aml_bundle(0xA1 /* ElseOp */, AML_PACKAGE);
 909    return var;
 910}
 911
 912/* ACPI 1.0b: 16.2.5.3 Type 1 Opcodes Encoding: DefWhile */
 913Aml *aml_while(Aml *predicate)
 914{
 915    Aml *var = aml_bundle(0xA2 /* WhileOp */, AML_PACKAGE);
 916    aml_append(var, predicate);
 917    return var;
 918}
 919
 920/* ACPI 1.0b: 16.2.5.2 Named Objects Encoding: DefMethod */
 921Aml *aml_method(const char *name, int arg_count, AmlSerializeFlag sflag)
 922{
 923    Aml *var = aml_bundle(0x14 /* MethodOp */, AML_PACKAGE);
 924    int methodflags;
 925
 926    /*
 927     * MethodFlags:
 928     *   bit 0-2: ArgCount (0-7)
 929     *   bit 3: SerializeFlag
 930     *     0: NotSerialized
 931     *     1: Serialized
 932     *   bit 4-7: reserved (must be 0)
 933     */
 934    assert(arg_count < 8);
 935    methodflags = arg_count | (sflag << 3);
 936
 937    build_append_namestring(var->buf, "%s", name);
 938    build_append_byte(var->buf, methodflags); /* MethodFlags: ArgCount */
 939    return var;
 940}
 941
 942/* ACPI 1.0b: 16.2.5.2 Named Objects Encoding: DefDevice */
 943Aml *aml_device(const char *name_format, ...)
 944{
 945    va_list ap;
 946    Aml *var = aml_bundle(0x82 /* DeviceOp */, AML_EXT_PACKAGE);
 947    va_start(ap, name_format);
 948    build_append_namestringv(var->buf, name_format, ap);
 949    va_end(ap);
 950    return var;
 951}
 952
 953/* ACPI 1.0b: 6.4.1 ASL Macros for Resource Descriptors */
 954Aml *aml_resource_template(void)
 955{
 956    /* ResourceTemplate is a buffer of Resources with EndTag at the end */
 957    Aml *var = aml_bundle(0x11 /* BufferOp */, AML_RES_TEMPLATE);
 958    return var;
 959}
 960
 961/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefBuffer
 962 * Pass byte_list as NULL to request uninitialized buffer to reserve space.
 963 */
 964Aml *aml_buffer(int buffer_size, uint8_t *byte_list)
 965{
 966    int i;
 967    Aml *var = aml_bundle(0x11 /* BufferOp */, AML_BUFFER);
 968
 969    for (i = 0; i < buffer_size; i++) {
 970        if (byte_list == NULL) {
 971            build_append_byte(var->buf, 0x0);
 972        } else {
 973            build_append_byte(var->buf, byte_list[i]);
 974        }
 975    }
 976
 977    return var;
 978}
 979
 980/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefPackage */
 981Aml *aml_package(uint8_t num_elements)
 982{
 983    Aml *var = aml_bundle(0x12 /* PackageOp */, AML_PACKAGE);
 984    build_append_byte(var->buf, num_elements);
 985    return var;
 986}
 987
 988/* ACPI 1.0b: 16.2.5.2 Named Objects Encoding: DefOpRegion */
 989Aml *aml_operation_region(const char *name, AmlRegionSpace rs,
 990                          Aml *offset, uint32_t len)
 991{
 992    Aml *var = aml_alloc();
 993    build_append_byte(var->buf, 0x5B); /* ExtOpPrefix */
 994    build_append_byte(var->buf, 0x80); /* OpRegionOp */
 995    build_append_namestring(var->buf, "%s", name);
 996    build_append_byte(var->buf, rs);
 997    aml_append(var, offset);
 998    build_append_int(var->buf, len);
 999    return var;
1000}
1001
1002/* ACPI 1.0b: 16.2.5.2 Named Objects Encoding: NamedField */
1003Aml *aml_named_field(const char *name, unsigned length)
1004{
1005    Aml *var = aml_alloc();
1006    build_append_nameseg(var->buf, name);
1007    build_append_pkg_length(var->buf, length, false);
1008    return var;
1009}
1010
1011/* ACPI 1.0b: 16.2.5.2 Named Objects Encoding: ReservedField */
1012Aml *aml_reserved_field(unsigned length)
1013{
1014    Aml *var = aml_alloc();
1015    /* ReservedField  := 0x00 PkgLength */
1016    build_append_byte(var->buf, 0x00);
1017    build_append_pkg_length(var->buf, length, false);
1018    return var;
1019}
1020
1021/* ACPI 1.0b: 16.2.5.2 Named Objects Encoding: DefField */
1022Aml *aml_field(const char *name, AmlAccessType type, AmlLockRule lock,
1023               AmlUpdateRule rule)
1024{
1025    Aml *var = aml_bundle(0x81 /* FieldOp */, AML_EXT_PACKAGE);
1026    uint8_t flags = rule << 5 | type;
1027
1028    flags |= lock << 4; /* LockRule at 4 bit offset */
1029
1030    build_append_namestring(var->buf, "%s", name);
1031    build_append_byte(var->buf, flags);
1032    return var;
1033}
1034
1035static
1036Aml *create_field_common(int opcode, Aml *srcbuf, Aml *index, const char *name)
1037{
1038    Aml *var = aml_opcode(opcode);
1039    aml_append(var, srcbuf);
1040    aml_append(var, index);
1041    build_append_namestring(var->buf, "%s", name);
1042    return var;
1043}
1044
1045/* ACPI 1.0b: 16.2.5.2 Named Objects Encoding: DefCreateField */
1046Aml *aml_create_field(Aml *srcbuf, Aml *bit_index, Aml *num_bits,
1047                      const char *name)
1048{
1049    Aml *var = aml_alloc();
1050    build_append_byte(var->buf, 0x5B); /* ExtOpPrefix */
1051    build_append_byte(var->buf, 0x13); /* CreateFieldOp */
1052    aml_append(var, srcbuf);
1053    aml_append(var, bit_index);
1054    aml_append(var, num_bits);
1055    build_append_namestring(var->buf, "%s", name);
1056    return var;
1057}
1058
1059/* ACPI 1.0b: 16.2.5.2 Named Objects Encoding: DefCreateDWordField */
1060Aml *aml_create_dword_field(Aml *srcbuf, Aml *index, const char *name)
1061{
1062    return create_field_common(0x8A /* CreateDWordFieldOp */,
1063                               srcbuf, index, name);
1064}
1065
1066/* ACPI 2.0a: 17.2.4.2 Named Objects Encoding: DefCreateQWordField */
1067Aml *aml_create_qword_field(Aml *srcbuf, Aml *index, const char *name)
1068{
1069    return create_field_common(0x8F /* CreateQWordFieldOp */,
1070                               srcbuf, index, name);
1071}
1072
1073/* ACPI 1.0b: 16.2.3 Data Objects Encoding: String */
1074Aml *aml_string(const char *name_format, ...)
1075{
1076    Aml *var = aml_opcode(0x0D /* StringPrefix */);
1077    va_list ap;
1078    char *s;
1079    int len;
1080
1081    va_start(ap, name_format);
1082    len = g_vasprintf(&s, name_format, ap);
1083    va_end(ap);
1084
1085    g_array_append_vals(var->buf, s, len + 1);
1086    g_free(s);
1087
1088    return var;
1089}
1090
1091/* ACPI 1.0b: 16.2.6.2 Local Objects Encoding */
1092Aml *aml_local(int num)
1093{
1094    uint8_t op = 0x60 /* Local0Op */ + num;
1095
1096    assert(num <= 7);
1097    return aml_opcode(op);
1098}
1099
1100/* ACPI 2.0a: 17.2.2 Data Objects Encoding: DefVarPackage */
1101Aml *aml_varpackage(uint32_t num_elements)
1102{
1103    Aml *var = aml_bundle(0x13 /* VarPackageOp */, AML_PACKAGE);
1104    build_append_int(var->buf, num_elements);
1105    return var;
1106}
1107
1108/* ACPI 1.0b: 16.2.5.2 Named Objects Encoding: DefProcessor */
1109Aml *aml_processor(uint8_t proc_id, uint32_t pblk_addr, uint8_t pblk_len,
1110                   const char *name_format, ...)
1111{
1112    va_list ap;
1113    Aml *var = aml_bundle(0x83 /* ProcessorOp */, AML_EXT_PACKAGE);
1114    va_start(ap, name_format);
1115    build_append_namestringv(var->buf, name_format, ap);
1116    va_end(ap);
1117    build_append_byte(var->buf, proc_id); /* ProcID */
1118    build_append_int_noprefix(var->buf, pblk_addr, sizeof(pblk_addr));
1119    build_append_byte(var->buf, pblk_len); /* PblkLen */
1120    return var;
1121}
1122
1123static uint8_t Hex2Digit(char c)
1124{
1125    if (c >= 'A') {
1126        return c - 'A' + 10;
1127    }
1128
1129    return c - '0';
1130}
1131
1132/* ACPI 1.0b: 15.2.3.6.4.1 EISAID Macro - Convert EISA ID String To Integer */
1133Aml *aml_eisaid(const char *str)
1134{
1135    Aml *var = aml_alloc();
1136    uint32_t id;
1137
1138    g_assert(strlen(str) == 7);
1139    id = (str[0] - 0x40) << 26 |
1140    (str[1] - 0x40) << 21 |
1141    (str[2] - 0x40) << 16 |
1142    Hex2Digit(str[3]) << 12 |
1143    Hex2Digit(str[4]) << 8 |
1144    Hex2Digit(str[5]) << 4 |
1145    Hex2Digit(str[6]);
1146
1147    build_append_byte(var->buf, 0x0C); /* DWordPrefix */
1148    build_append_int_noprefix(var->buf, bswap32(id), sizeof(id));
1149    return var;
1150}
1151
1152/* ACPI 1.0b: 6.4.3.5.5 Word Address Space Descriptor: bytes 3-5 */
1153static Aml *aml_as_desc_header(AmlResourceType type, AmlMinFixed min_fixed,
1154                               AmlMaxFixed max_fixed, AmlDecode dec,
1155                               uint8_t type_flags)
1156{
1157    uint8_t flags = max_fixed | min_fixed | dec;
1158    Aml *var = aml_alloc();
1159
1160    build_append_byte(var->buf, type);
1161    build_append_byte(var->buf, flags);
1162    build_append_byte(var->buf, type_flags); /* Type Specific Flags */
1163    return var;
1164}
1165
1166/* ACPI 1.0b: 6.4.3.5.5 Word Address Space Descriptor */
1167static Aml *aml_word_as_desc(AmlResourceType type, AmlMinFixed min_fixed,
1168                             AmlMaxFixed max_fixed, AmlDecode dec,
1169                             uint16_t addr_gran, uint16_t addr_min,
1170                             uint16_t addr_max, uint16_t addr_trans,
1171                             uint16_t len, uint8_t type_flags)
1172{
1173    Aml *var = aml_alloc();
1174
1175    build_append_byte(var->buf, 0x88); /* Word Address Space Descriptor */
1176    /* minimum length since we do not encode optional fields */
1177    build_append_byte(var->buf, 0x0D);
1178    build_append_byte(var->buf, 0x0);
1179
1180    aml_append(var,
1181        aml_as_desc_header(type, min_fixed, max_fixed, dec, type_flags));
1182    build_append_int_noprefix(var->buf, addr_gran, sizeof(addr_gran));
1183    build_append_int_noprefix(var->buf, addr_min, sizeof(addr_min));
1184    build_append_int_noprefix(var->buf, addr_max, sizeof(addr_max));
1185    build_append_int_noprefix(var->buf, addr_trans, sizeof(addr_trans));
1186    build_append_int_noprefix(var->buf, len, sizeof(len));
1187    return var;
1188}
1189
1190/* ACPI 1.0b: 6.4.3.5.3 DWord Address Space Descriptor */
1191static Aml *aml_dword_as_desc(AmlResourceType type, AmlMinFixed min_fixed,
1192                              AmlMaxFixed max_fixed, AmlDecode dec,
1193                              uint32_t addr_gran, uint32_t addr_min,
1194                              uint32_t addr_max, uint32_t addr_trans,
1195                              uint32_t len, uint8_t type_flags)
1196{
1197    Aml *var = aml_alloc();
1198
1199    build_append_byte(var->buf, 0x87); /* DWord Address Space Descriptor */
1200    /* minimum length since we do not encode optional fields */
1201    build_append_byte(var->buf, 23);
1202    build_append_byte(var->buf, 0x0);
1203
1204
1205    aml_append(var,
1206        aml_as_desc_header(type, min_fixed, max_fixed, dec, type_flags));
1207    build_append_int_noprefix(var->buf, addr_gran, sizeof(addr_gran));
1208    build_append_int_noprefix(var->buf, addr_min, sizeof(addr_min));
1209    build_append_int_noprefix(var->buf, addr_max, sizeof(addr_max));
1210    build_append_int_noprefix(var->buf, addr_trans, sizeof(addr_trans));
1211    build_append_int_noprefix(var->buf, len, sizeof(len));
1212    return var;
1213}
1214
1215/* ACPI 1.0b: 6.4.3.5.1 QWord Address Space Descriptor */
1216static Aml *aml_qword_as_desc(AmlResourceType type, AmlMinFixed min_fixed,
1217                              AmlMaxFixed max_fixed, AmlDecode dec,
1218                              uint64_t addr_gran, uint64_t addr_min,
1219                              uint64_t addr_max, uint64_t addr_trans,
1220                              uint64_t len, uint8_t type_flags)
1221{
1222    Aml *var = aml_alloc();
1223
1224    build_append_byte(var->buf, 0x8A); /* QWord Address Space Descriptor */
1225    /* minimum length since we do not encode optional fields */
1226    build_append_byte(var->buf, 0x2B);
1227    build_append_byte(var->buf, 0x0);
1228
1229    aml_append(var,
1230        aml_as_desc_header(type, min_fixed, max_fixed, dec, type_flags));
1231    build_append_int_noprefix(var->buf, addr_gran, sizeof(addr_gran));
1232    build_append_int_noprefix(var->buf, addr_min, sizeof(addr_min));
1233    build_append_int_noprefix(var->buf, addr_max, sizeof(addr_max));
1234    build_append_int_noprefix(var->buf, addr_trans, sizeof(addr_trans));
1235    build_append_int_noprefix(var->buf, len, sizeof(len));
1236    return var;
1237}
1238
1239/*
1240 * ACPI 1.0b: 6.4.3.5.6 ASL Macros for WORD Address Descriptor
1241 *
1242 * More verbose description at:
1243 * ACPI 5.0: 19.5.141 WordBusNumber (Word Bus Number Resource Descriptor Macro)
1244 */
1245Aml *aml_word_bus_number(AmlMinFixed min_fixed, AmlMaxFixed max_fixed,
1246                         AmlDecode dec, uint16_t addr_gran,
1247                         uint16_t addr_min, uint16_t addr_max,
1248                         uint16_t addr_trans, uint16_t len)
1249
1250{
1251    return aml_word_as_desc(AML_BUS_NUMBER_RANGE, min_fixed, max_fixed, dec,
1252                            addr_gran, addr_min, addr_max, addr_trans, len, 0);
1253}
1254
1255/*
1256 * ACPI 1.0b: 6.4.3.5.6 ASL Macros for WORD Address Descriptor
1257 *
1258 * More verbose description at:
1259 * ACPI 5.0: 19.5.142 WordIO (Word IO Resource Descriptor Macro)
1260 */
1261Aml *aml_word_io(AmlMinFixed min_fixed, AmlMaxFixed max_fixed,
1262                 AmlDecode dec, AmlISARanges isa_ranges,
1263                 uint16_t addr_gran, uint16_t addr_min,
1264                 uint16_t addr_max, uint16_t addr_trans,
1265                 uint16_t len)
1266
1267{
1268    return aml_word_as_desc(AML_IO_RANGE, min_fixed, max_fixed, dec,
1269                            addr_gran, addr_min, addr_max, addr_trans, len,
1270                            isa_ranges);
1271}
1272
1273/*
1274 * ACPI 1.0b: 6.4.3.5.4 ASL Macros for DWORD Address Descriptor
1275 *
1276 * More verbose description at:
1277 * ACPI 5.0: 19.5.33 DWordIO (DWord IO Resource Descriptor Macro)
1278 */
1279Aml *aml_dword_io(AmlMinFixed min_fixed, AmlMaxFixed max_fixed,
1280                 AmlDecode dec, AmlISARanges isa_ranges,
1281                 uint32_t addr_gran, uint32_t addr_min,
1282                 uint32_t addr_max, uint32_t addr_trans,
1283                 uint32_t len)
1284
1285{
1286    return aml_dword_as_desc(AML_IO_RANGE, min_fixed, max_fixed, dec,
1287                            addr_gran, addr_min, addr_max, addr_trans, len,
1288                            isa_ranges);
1289}
1290
1291/*
1292 * ACPI 1.0b: 6.4.3.5.4 ASL Macros for DWORD Address Space Descriptor
1293 *
1294 * More verbose description at:
1295 * ACPI 5.0: 19.5.34 DWordMemory (DWord Memory Resource Descriptor Macro)
1296 */
1297Aml *aml_dword_memory(AmlDecode dec, AmlMinFixed min_fixed,
1298                      AmlMaxFixed max_fixed, AmlCacheable cacheable,
1299                      AmlReadAndWrite read_and_write,
1300                      uint32_t addr_gran, uint32_t addr_min,
1301                      uint32_t addr_max, uint32_t addr_trans,
1302                      uint32_t len)
1303{
1304    uint8_t flags = read_and_write | (cacheable << 1);
1305
1306    return aml_dword_as_desc(AML_MEMORY_RANGE, min_fixed, max_fixed,
1307                             dec, addr_gran, addr_min, addr_max,
1308                             addr_trans, len, flags);
1309}
1310
1311/*
1312 * ACPI 1.0b: 6.4.3.5.2 ASL Macros for QWORD Address Space Descriptor
1313 *
1314 * More verbose description at:
1315 * ACPI 5.0: 19.5.102 QWordMemory (QWord Memory Resource Descriptor Macro)
1316 */
1317Aml *aml_qword_memory(AmlDecode dec, AmlMinFixed min_fixed,
1318                      AmlMaxFixed max_fixed, AmlCacheable cacheable,
1319                      AmlReadAndWrite read_and_write,
1320                      uint64_t addr_gran, uint64_t addr_min,
1321                      uint64_t addr_max, uint64_t addr_trans,
1322                      uint64_t len)
1323{
1324    uint8_t flags = read_and_write | (cacheable << 1);
1325
1326    return aml_qword_as_desc(AML_MEMORY_RANGE, min_fixed, max_fixed,
1327                             dec, addr_gran, addr_min, addr_max,
1328                             addr_trans, len, flags);
1329}
1330
1331/* ACPI 1.0b: 6.4.2.2 DMA Format/6.4.2.2.1 ASL Macro for DMA Descriptor */
1332Aml *aml_dma(AmlDmaType typ, AmlDmaBusMaster bm, AmlTransferSize sz,
1333             uint8_t channel)
1334{
1335    Aml *var = aml_alloc();
1336    uint8_t flags = sz | bm << 2 | typ << 5;
1337
1338    assert(channel < 8);
1339    build_append_byte(var->buf, 0x2A);    /* Byte 0: DMA Descriptor */
1340    build_append_byte(var->buf, 1U << channel); /* Byte 1: _DMA - DmaChannel */
1341    build_append_byte(var->buf, flags);   /* Byte 2 */
1342    return var;
1343}
1344
1345/* ACPI 1.0b: 16.2.5.3 Type 1 Opcodes Encoding: DefSleep */
1346Aml *aml_sleep(uint64_t msec)
1347{
1348    Aml *var = aml_alloc();
1349    build_append_byte(var->buf, 0x5B); /* ExtOpPrefix */
1350    build_append_byte(var->buf, 0x22); /* SleepOp */
1351    aml_append(var, aml_int(msec));
1352    return var;
1353}
1354
1355static uint8_t Hex2Byte(const char *src)
1356{
1357    int hi, lo;
1358
1359    hi = Hex2Digit(src[0]);
1360    assert(hi >= 0);
1361    assert(hi <= 15);
1362
1363    lo = Hex2Digit(src[1]);
1364    assert(lo >= 0);
1365    assert(lo <= 15);
1366    return (hi << 4) | lo;
1367}
1368
1369/*
1370 * ACPI 3.0: 17.5.124 ToUUID (Convert String to UUID Macro)
1371 * e.g. UUID: aabbccdd-eeff-gghh-iijj-kkllmmnnoopp
1372 * call aml_touuid("aabbccdd-eeff-gghh-iijj-kkllmmnnoopp");
1373 */
1374Aml *aml_touuid(const char *uuid)
1375{
1376    Aml *var = aml_bundle(0x11 /* BufferOp */, AML_BUFFER);
1377
1378    assert(strlen(uuid) == 36);
1379    assert(uuid[8] == '-');
1380    assert(uuid[13] == '-');
1381    assert(uuid[18] == '-');
1382    assert(uuid[23] == '-');
1383
1384    build_append_byte(var->buf, Hex2Byte(uuid + 6));  /* dd - at offset 00 */
1385    build_append_byte(var->buf, Hex2Byte(uuid + 4));  /* cc - at offset 01 */
1386    build_append_byte(var->buf, Hex2Byte(uuid + 2));  /* bb - at offset 02 */
1387    build_append_byte(var->buf, Hex2Byte(uuid + 0));  /* aa - at offset 03 */
1388
1389    build_append_byte(var->buf, Hex2Byte(uuid + 11)); /* ff - at offset 04 */
1390    build_append_byte(var->buf, Hex2Byte(uuid + 9));  /* ee - at offset 05 */
1391
1392    build_append_byte(var->buf, Hex2Byte(uuid + 16)); /* hh - at offset 06 */
1393    build_append_byte(var->buf, Hex2Byte(uuid + 14)); /* gg - at offset 07 */
1394
1395    build_append_byte(var->buf, Hex2Byte(uuid + 19)); /* ii - at offset 08 */
1396    build_append_byte(var->buf, Hex2Byte(uuid + 21)); /* jj - at offset 09 */
1397
1398    build_append_byte(var->buf, Hex2Byte(uuid + 24)); /* kk - at offset 10 */
1399    build_append_byte(var->buf, Hex2Byte(uuid + 26)); /* ll - at offset 11 */
1400    build_append_byte(var->buf, Hex2Byte(uuid + 28)); /* mm - at offset 12 */
1401    build_append_byte(var->buf, Hex2Byte(uuid + 30)); /* nn - at offset 13 */
1402    build_append_byte(var->buf, Hex2Byte(uuid + 32)); /* oo - at offset 14 */
1403    build_append_byte(var->buf, Hex2Byte(uuid + 34)); /* pp - at offset 15 */
1404
1405    return var;
1406}
1407
1408/*
1409 * ACPI 2.0b: 16.2.3.6.4.3  Unicode Macro (Convert Ascii String To Unicode)
1410 */
1411Aml *aml_unicode(const char *str)
1412{
1413    int i = 0;
1414    Aml *var = aml_bundle(0x11 /* BufferOp */, AML_BUFFER);
1415
1416    do {
1417        build_append_byte(var->buf, str[i]);
1418        build_append_byte(var->buf, 0);
1419        i++;
1420    } while (i <= strlen(str));
1421
1422    return var;
1423}
1424
1425/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefRefOf */
1426Aml *aml_refof(Aml *arg)
1427{
1428    Aml *var = aml_opcode(0x71 /* RefOfOp */);
1429    aml_append(var, arg);
1430    return var;
1431}
1432
1433/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefDerefOf */
1434Aml *aml_derefof(Aml *arg)
1435{
1436    Aml *var = aml_opcode(0x83 /* DerefOfOp */);
1437    aml_append(var, arg);
1438    return var;
1439}
1440
1441/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefSizeOf */
1442Aml *aml_sizeof(Aml *arg)
1443{
1444    Aml *var = aml_opcode(0x87 /* SizeOfOp */);
1445    aml_append(var, arg);
1446    return var;
1447}
1448
1449/* ACPI 1.0b: 16.2.5.2 Named Objects Encoding: DefMutex */
1450Aml *aml_mutex(const char *name, uint8_t sync_level)
1451{
1452    Aml *var = aml_alloc();
1453    build_append_byte(var->buf, 0x5B); /* ExtOpPrefix */
1454    build_append_byte(var->buf, 0x01); /* MutexOp */
1455    build_append_namestring(var->buf, "%s", name);
1456    assert(!(sync_level & 0xF0));
1457    build_append_byte(var->buf, sync_level);
1458    return var;
1459}
1460
1461/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefAcquire */
1462Aml *aml_acquire(Aml *mutex, uint16_t timeout)
1463{
1464    Aml *var = aml_alloc();
1465    build_append_byte(var->buf, 0x5B); /* ExtOpPrefix */
1466    build_append_byte(var->buf, 0x23); /* AcquireOp */
1467    aml_append(var, mutex);
1468    build_append_int_noprefix(var->buf, timeout, sizeof(timeout));
1469    return var;
1470}
1471
1472/* ACPI 1.0b: 16.2.5.3 Type 1 Opcodes Encoding: DefRelease */
1473Aml *aml_release(Aml *mutex)
1474{
1475    Aml *var = aml_alloc();
1476    build_append_byte(var->buf, 0x5B); /* ExtOpPrefix */
1477    build_append_byte(var->buf, 0x27); /* ReleaseOp */
1478    aml_append(var, mutex);
1479    return var;
1480}
1481
1482/* ACPI 1.0b: 16.2.5.1 Name Space Modifier Objects Encoding: DefAlias */
1483Aml *aml_alias(const char *source_object, const char *alias_object)
1484{
1485    Aml *var = aml_opcode(0x06 /* AliasOp */);
1486    aml_append(var, aml_name("%s", source_object));
1487    aml_append(var, aml_name("%s", alias_object));
1488    return var;
1489}
1490
1491/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefConcat */
1492Aml *aml_concatenate(Aml *source1, Aml *source2, Aml *target)
1493{
1494    return build_opcode_2arg_dst(0x73 /* ConcatOp */, source1, source2,
1495                                 target);
1496}
1497
1498/* ACPI 1.0b: 16.2.5.4 Type 2 Opcodes Encoding: DefObjectType */
1499Aml *aml_object_type(Aml *object)
1500{
1501    Aml *var = aml_opcode(0x8E /* ObjectTypeOp */);
1502    aml_append(var, object);
1503    return var;
1504}
1505
1506void
1507build_header(BIOSLinker *linker, GArray *table_data,
1508             AcpiTableHeader *h, const char *sig, int len, uint8_t rev,
1509             const char *oem_id, const char *oem_table_id)
1510{
1511    unsigned tbl_offset = (char *)h - table_data->data;
1512    unsigned checksum_offset = (char *)&h->checksum - table_data->data;
1513    memcpy(&h->signature, sig, 4);
1514    h->length = cpu_to_le32(len);
1515    h->revision = rev;
1516
1517    if (oem_id) {
1518        strncpy((char *)h->oem_id, oem_id, sizeof h->oem_id);
1519    } else {
1520        memcpy(h->oem_id, ACPI_BUILD_APPNAME6, 6);
1521    }
1522
1523    if (oem_table_id) {
1524        strncpy((char *)h->oem_table_id, oem_table_id, sizeof(h->oem_table_id));
1525    } else {
1526        memcpy(h->oem_table_id, ACPI_BUILD_APPNAME4, 4);
1527        memcpy(h->oem_table_id + 4, sig, 4);
1528    }
1529
1530    h->oem_revision = cpu_to_le32(1);
1531    memcpy(h->asl_compiler_id, ACPI_BUILD_APPNAME4, 4);
1532    h->asl_compiler_revision = cpu_to_le32(1);
1533    /* Checksum to be filled in by Guest linker */
1534    bios_linker_loader_add_checksum(linker, ACPI_BUILD_TABLE_FILE,
1535        tbl_offset, len, checksum_offset);
1536}
1537
1538void *acpi_data_push(GArray *table_data, unsigned size)
1539{
1540    unsigned off = table_data->len;
1541    g_array_set_size(table_data, off + size);
1542    return table_data->data + off;
1543}
1544
1545unsigned acpi_data_len(GArray *table)
1546{
1547    assert(g_array_get_element_size(table) == 1);
1548    return table->len;
1549}
1550
1551void acpi_add_table(GArray *table_offsets, GArray *table_data)
1552{
1553    uint32_t offset = table_data->len;
1554    g_array_append_val(table_offsets, offset);
1555}
1556
1557void acpi_build_tables_init(AcpiBuildTables *tables)
1558{
1559    tables->rsdp = g_array_new(false, true /* clear */, 1);
1560    tables->table_data = g_array_new(false, true /* clear */, 1);
1561    tables->tcpalog = g_array_new(false, true /* clear */, 1);
1562    tables->linker = bios_linker_loader_init();
1563}
1564
1565void acpi_build_tables_cleanup(AcpiBuildTables *tables, bool mfre)
1566{
1567    bios_linker_loader_cleanup(tables->linker);
1568    g_array_free(tables->rsdp, true);
1569    g_array_free(tables->table_data, true);
1570    g_array_free(tables->tcpalog, mfre);
1571}
1572
1573/* Build rsdt table */
1574void
1575build_rsdt(GArray *table_data, BIOSLinker *linker, GArray *table_offsets,
1576           const char *oem_id, const char *oem_table_id)
1577{
1578    int i;
1579    unsigned rsdt_entries_offset;
1580    AcpiRsdtDescriptorRev1 *rsdt;
1581    const unsigned table_data_len = (sizeof(uint32_t) * table_offsets->len);
1582    const unsigned rsdt_entry_size = sizeof(rsdt->table_offset_entry[0]);
1583    const size_t rsdt_len = sizeof(*rsdt) + table_data_len;
1584
1585    rsdt = acpi_data_push(table_data, rsdt_len);
1586    rsdt_entries_offset = (char *)rsdt->table_offset_entry - table_data->data;
1587    for (i = 0; i < table_offsets->len; ++i) {
1588        uint32_t ref_tbl_offset = g_array_index(table_offsets, uint32_t, i);
1589        uint32_t rsdt_entry_offset = rsdt_entries_offset + rsdt_entry_size * i;
1590
1591        /* rsdt->table_offset_entry to be filled by Guest linker */
1592        bios_linker_loader_add_pointer(linker,
1593            ACPI_BUILD_TABLE_FILE, rsdt_entry_offset, rsdt_entry_size,
1594            ACPI_BUILD_TABLE_FILE, ref_tbl_offset);
1595    }
1596    build_header(linker, table_data,
1597                 (void *)rsdt, "RSDT", rsdt_len, 1, oem_id, oem_table_id);
1598}
1599
1600void build_srat_memory(AcpiSratMemoryAffinity *numamem, uint64_t base,
1601                       uint64_t len, int node, MemoryAffinityFlags flags)
1602{
1603    numamem->type = ACPI_SRAT_MEMORY;
1604    numamem->length = sizeof(*numamem);
1605    numamem->proximity = cpu_to_le32(node);
1606    numamem->flags = cpu_to_le32(flags);
1607    numamem->base_addr = cpu_to_le64(base);
1608    numamem->range_length = cpu_to_le64(len);
1609}
1610