xref: /openbmc/qemu/hw/acpi/nvdimm.c (revision 75f27498220e6ff6f78bf08fbe2cc662ec76ba89)
1 /*
2  * NVDIMM ACPI Implementation
3  *
4  * Copyright(C) 2015 Intel Corporation.
5  *
6  * Author:
7  *  Xiao Guangrong <guangrong.xiao@linux.intel.com>
8  *
9  * NFIT is defined in ACPI 6.0: 5.2.25 NVDIMM Firmware Interface Table (NFIT)
10  * and the DSM specification can be found at:
11  *       http://pmem.io/documents/NVDIMM_DSM_Interface_Example.pdf
12  *
13  * Currently, it only supports PMEM Virtualization.
14  *
15  * This library is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU Lesser General Public
17  * License as published by the Free Software Foundation; either
18  * version 2 of the License, or (at your option) any later version.
19  *
20  * This library is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23  * Lesser General Public License for more details.
24  *
25  * You should have received a copy of the GNU Lesser General Public
26  * License along with this library; if not, see <http://www.gnu.org/licenses/>
27  */
28 
29 #include "qemu/osdep.h"
30 #include "hw/acpi/acpi.h"
31 #include "hw/acpi/aml-build.h"
32 #include "hw/acpi/bios-linker-loader.h"
33 #include "hw/nvram/fw_cfg.h"
34 #include "hw/mem/nvdimm.h"
35 
36 static int nvdimm_plugged_device_list(Object *obj, void *opaque)
37 {
38     GSList **list = opaque;
39 
40     if (object_dynamic_cast(obj, TYPE_NVDIMM)) {
41         *list = g_slist_append(*list, DEVICE(obj));
42     }
43 
44     object_child_foreach(obj, nvdimm_plugged_device_list, opaque);
45     return 0;
46 }
47 
48 /*
49  * inquire plugged NVDIMM devices and link them into the list which is
50  * returned to the caller.
51  *
52  * Note: it is the caller's responsibility to free the list to avoid
53  * memory leak.
54  */
55 static GSList *nvdimm_get_plugged_device_list(void)
56 {
57     GSList *list = NULL;
58 
59     object_child_foreach(qdev_get_machine(), nvdimm_plugged_device_list,
60                          &list);
61     return list;
62 }
63 
64 #define NVDIMM_UUID_LE(a, b, c, d0, d1, d2, d3, d4, d5, d6, d7)             \
65    { (a) & 0xff, ((a) >> 8) & 0xff, ((a) >> 16) & 0xff, ((a) >> 24) & 0xff, \
66      (b) & 0xff, ((b) >> 8) & 0xff, (c) & 0xff, ((c) >> 8) & 0xff,          \
67      (d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7) }
68 
69 /*
70  * define Byte Addressable Persistent Memory (PM) Region according to
71  * ACPI 6.0: 5.2.25.1 System Physical Address Range Structure.
72  */
73 static const uint8_t nvdimm_nfit_spa_uuid[] =
74       NVDIMM_UUID_LE(0x66f0d379, 0xb4f3, 0x4074, 0xac, 0x43, 0x0d, 0x33,
75                      0x18, 0xb7, 0x8c, 0xdb);
76 
77 /*
78  * NVDIMM Firmware Interface Table
79  * @signature: "NFIT"
80  *
81  * It provides information that allows OSPM to enumerate NVDIMM present in
82  * the platform and associate system physical address ranges created by the
83  * NVDIMMs.
84  *
85  * It is defined in ACPI 6.0: 5.2.25 NVDIMM Firmware Interface Table (NFIT)
86  */
87 struct NvdimmNfitHeader {
88     ACPI_TABLE_HEADER_DEF
89     uint32_t reserved;
90 } QEMU_PACKED;
91 typedef struct NvdimmNfitHeader NvdimmNfitHeader;
92 
93 /*
94  * define NFIT structures according to ACPI 6.0: 5.2.25 NVDIMM Firmware
95  * Interface Table (NFIT).
96  */
97 
98 /*
99  * System Physical Address Range Structure
100  *
101  * It describes the system physical address ranges occupied by NVDIMMs and
102  * the types of the regions.
103  */
104 struct NvdimmNfitSpa {
105     uint16_t type;
106     uint16_t length;
107     uint16_t spa_index;
108     uint16_t flags;
109     uint32_t reserved;
110     uint32_t proximity_domain;
111     uint8_t type_guid[16];
112     uint64_t spa_base;
113     uint64_t spa_length;
114     uint64_t mem_attr;
115 } QEMU_PACKED;
116 typedef struct NvdimmNfitSpa NvdimmNfitSpa;
117 
118 /*
119  * Memory Device to System Physical Address Range Mapping Structure
120  *
121  * It enables identifying each NVDIMM region and the corresponding SPA
122  * describing the memory interleave
123  */
124 struct NvdimmNfitMemDev {
125     uint16_t type;
126     uint16_t length;
127     uint32_t nfit_handle;
128     uint16_t phys_id;
129     uint16_t region_id;
130     uint16_t spa_index;
131     uint16_t dcr_index;
132     uint64_t region_len;
133     uint64_t region_offset;
134     uint64_t region_dpa;
135     uint16_t interleave_index;
136     uint16_t interleave_ways;
137     uint16_t flags;
138     uint16_t reserved;
139 } QEMU_PACKED;
140 typedef struct NvdimmNfitMemDev NvdimmNfitMemDev;
141 
142 /*
143  * NVDIMM Control Region Structure
144  *
145  * It describes the NVDIMM and if applicable, Block Control Window.
146  */
147 struct NvdimmNfitControlRegion {
148     uint16_t type;
149     uint16_t length;
150     uint16_t dcr_index;
151     uint16_t vendor_id;
152     uint16_t device_id;
153     uint16_t revision_id;
154     uint16_t sub_vendor_id;
155     uint16_t sub_device_id;
156     uint16_t sub_revision_id;
157     uint8_t reserved[6];
158     uint32_t serial_number;
159     uint16_t fic;
160     uint16_t num_bcw;
161     uint64_t bcw_size;
162     uint64_t cmd_offset;
163     uint64_t cmd_size;
164     uint64_t status_offset;
165     uint64_t status_size;
166     uint16_t flags;
167     uint8_t reserved2[6];
168 } QEMU_PACKED;
169 typedef struct NvdimmNfitControlRegion NvdimmNfitControlRegion;
170 
171 /*
172  * Module serial number is a unique number for each device. We use the
173  * slot id of NVDIMM device to generate this number so that each device
174  * associates with a different number.
175  *
176  * 0x123456 is a magic number we arbitrarily chose.
177  */
178 static uint32_t nvdimm_slot_to_sn(int slot)
179 {
180     return 0x123456 + slot;
181 }
182 
183 /*
184  * handle is used to uniquely associate nfit_memdev structure with NVDIMM
185  * ACPI device - nfit_memdev.nfit_handle matches with the value returned
186  * by ACPI device _ADR method.
187  *
188  * We generate the handle with the slot id of NVDIMM device and reserve
189  * 0 for NVDIMM root device.
190  */
191 static uint32_t nvdimm_slot_to_handle(int slot)
192 {
193     return slot + 1;
194 }
195 
196 /*
197  * index uniquely identifies the structure, 0 is reserved which indicates
198  * that the structure is not valid or the associated structure is not
199  * present.
200  *
201  * Each NVDIMM device needs two indexes, one for nfit_spa and another for
202  * nfit_dc which are generated by the slot id of NVDIMM device.
203  */
204 static uint16_t nvdimm_slot_to_spa_index(int slot)
205 {
206     return (slot + 1) << 1;
207 }
208 
209 /* See the comments of nvdimm_slot_to_spa_index(). */
210 static uint32_t nvdimm_slot_to_dcr_index(int slot)
211 {
212     return nvdimm_slot_to_spa_index(slot) + 1;
213 }
214 
215 static NVDIMMDevice *nvdimm_get_device_by_handle(uint32_t handle)
216 {
217     NVDIMMDevice *nvdimm = NULL;
218     GSList *list, *device_list = nvdimm_get_plugged_device_list();
219 
220     for (list = device_list; list; list = list->next) {
221         NVDIMMDevice *nvd = list->data;
222         int slot = object_property_get_int(OBJECT(nvd), PC_DIMM_SLOT_PROP,
223                                            NULL);
224 
225         if (nvdimm_slot_to_handle(slot) == handle) {
226             nvdimm = nvd;
227             break;
228         }
229     }
230 
231     g_slist_free(device_list);
232     return nvdimm;
233 }
234 
235 /* ACPI 6.0: 5.2.25.1 System Physical Address Range Structure */
236 static void
237 nvdimm_build_structure_spa(GArray *structures, DeviceState *dev)
238 {
239     NvdimmNfitSpa *nfit_spa;
240     uint64_t addr = object_property_get_int(OBJECT(dev), PC_DIMM_ADDR_PROP,
241                                             NULL);
242     uint64_t size = object_property_get_int(OBJECT(dev), PC_DIMM_SIZE_PROP,
243                                             NULL);
244     uint32_t node = object_property_get_int(OBJECT(dev), PC_DIMM_NODE_PROP,
245                                             NULL);
246     int slot = object_property_get_int(OBJECT(dev), PC_DIMM_SLOT_PROP,
247                                             NULL);
248 
249     nfit_spa = acpi_data_push(structures, sizeof(*nfit_spa));
250 
251     nfit_spa->type = cpu_to_le16(0 /* System Physical Address Range
252                                       Structure */);
253     nfit_spa->length = cpu_to_le16(sizeof(*nfit_spa));
254     nfit_spa->spa_index = cpu_to_le16(nvdimm_slot_to_spa_index(slot));
255 
256     /*
257      * Control region is strict as all the device info, such as SN, index,
258      * is associated with slot id.
259      */
260     nfit_spa->flags = cpu_to_le16(1 /* Control region is strictly for
261                                        management during hot add/online
262                                        operation */ |
263                                   2 /* Data in Proximity Domain field is
264                                        valid*/);
265 
266     /* NUMA node. */
267     nfit_spa->proximity_domain = cpu_to_le32(node);
268     /* the region reported as PMEM. */
269     memcpy(nfit_spa->type_guid, nvdimm_nfit_spa_uuid,
270            sizeof(nvdimm_nfit_spa_uuid));
271 
272     nfit_spa->spa_base = cpu_to_le64(addr);
273     nfit_spa->spa_length = cpu_to_le64(size);
274 
275     /* It is the PMEM and can be cached as writeback. */
276     nfit_spa->mem_attr = cpu_to_le64(0x8ULL /* EFI_MEMORY_WB */ |
277                                      0x8000ULL /* EFI_MEMORY_NV */);
278 }
279 
280 /*
281  * ACPI 6.0: 5.2.25.2 Memory Device to System Physical Address Range Mapping
282  * Structure
283  */
284 static void
285 nvdimm_build_structure_memdev(GArray *structures, DeviceState *dev)
286 {
287     NvdimmNfitMemDev *nfit_memdev;
288     uint64_t size = object_property_get_int(OBJECT(dev), PC_DIMM_SIZE_PROP,
289                                             NULL);
290     int slot = object_property_get_int(OBJECT(dev), PC_DIMM_SLOT_PROP,
291                                             NULL);
292     uint32_t handle = nvdimm_slot_to_handle(slot);
293 
294     nfit_memdev = acpi_data_push(structures, sizeof(*nfit_memdev));
295 
296     nfit_memdev->type = cpu_to_le16(1 /* Memory Device to System Address
297                                          Range Map Structure*/);
298     nfit_memdev->length = cpu_to_le16(sizeof(*nfit_memdev));
299     nfit_memdev->nfit_handle = cpu_to_le32(handle);
300 
301     /*
302      * associate memory device with System Physical Address Range
303      * Structure.
304      */
305     nfit_memdev->spa_index = cpu_to_le16(nvdimm_slot_to_spa_index(slot));
306     /* associate memory device with Control Region Structure. */
307     nfit_memdev->dcr_index = cpu_to_le16(nvdimm_slot_to_dcr_index(slot));
308 
309     /* The memory region on the device. */
310     nfit_memdev->region_len = cpu_to_le64(size);
311     /* The device address starts from 0. */
312     nfit_memdev->region_dpa = cpu_to_le64(0);
313 
314     /* Only one interleave for PMEM. */
315     nfit_memdev->interleave_ways = cpu_to_le16(1);
316 }
317 
318 /*
319  * ACPI 6.0: 5.2.25.5 NVDIMM Control Region Structure.
320  */
321 static void nvdimm_build_structure_dcr(GArray *structures, DeviceState *dev)
322 {
323     NvdimmNfitControlRegion *nfit_dcr;
324     int slot = object_property_get_int(OBJECT(dev), PC_DIMM_SLOT_PROP,
325                                        NULL);
326     uint32_t sn = nvdimm_slot_to_sn(slot);
327 
328     nfit_dcr = acpi_data_push(structures, sizeof(*nfit_dcr));
329 
330     nfit_dcr->type = cpu_to_le16(4 /* NVDIMM Control Region Structure */);
331     nfit_dcr->length = cpu_to_le16(sizeof(*nfit_dcr));
332     nfit_dcr->dcr_index = cpu_to_le16(nvdimm_slot_to_dcr_index(slot));
333 
334     /* vendor: Intel. */
335     nfit_dcr->vendor_id = cpu_to_le16(0x8086);
336     nfit_dcr->device_id = cpu_to_le16(1);
337 
338     /* The _DSM method is following Intel's DSM specification. */
339     nfit_dcr->revision_id = cpu_to_le16(1 /* Current Revision supported
340                                              in ACPI 6.0 is 1. */);
341     nfit_dcr->serial_number = cpu_to_le32(sn);
342     nfit_dcr->fic = cpu_to_le16(0x201 /* Format Interface Code. See Chapter
343                                          2: NVDIMM Device Specific Method
344                                          (DSM) in DSM Spec Rev1.*/);
345 }
346 
347 static GArray *nvdimm_build_device_structure(void)
348 {
349     GSList *device_list = nvdimm_get_plugged_device_list();
350     GArray *structures = g_array_new(false, true /* clear */, 1);
351 
352     for (; device_list; device_list = device_list->next) {
353         DeviceState *dev = device_list->data;
354 
355         /* build System Physical Address Range Structure. */
356         nvdimm_build_structure_spa(structures, dev);
357 
358         /*
359          * build Memory Device to System Physical Address Range Mapping
360          * Structure.
361          */
362         nvdimm_build_structure_memdev(structures, dev);
363 
364         /* build NVDIMM Control Region Structure. */
365         nvdimm_build_structure_dcr(structures, dev);
366     }
367     g_slist_free(device_list);
368 
369     return structures;
370 }
371 
372 static void nvdimm_init_fit_buffer(NvdimmFitBuffer *fit_buf)
373 {
374     fit_buf->fit = g_array_new(false, true /* clear */, 1);
375 }
376 
377 static void nvdimm_build_fit_buffer(NvdimmFitBuffer *fit_buf)
378 {
379     g_array_free(fit_buf->fit, true);
380     fit_buf->fit = nvdimm_build_device_structure();
381     fit_buf->dirty = true;
382 }
383 
384 void nvdimm_acpi_hotplug(AcpiNVDIMMState *state)
385 {
386     nvdimm_build_fit_buffer(&state->fit_buf);
387 }
388 
389 static void nvdimm_build_nfit(AcpiNVDIMMState *state, GArray *table_offsets,
390                               GArray *table_data, BIOSLinker *linker)
391 {
392     NvdimmFitBuffer *fit_buf = &state->fit_buf;
393     unsigned int header;
394 
395 
396     /* NVDIMM device is not plugged? */
397     if (!fit_buf->fit->len) {
398         return;
399     }
400 
401     acpi_add_table(table_offsets, table_data);
402 
403     /* NFIT header. */
404     header = table_data->len;
405     acpi_data_push(table_data, sizeof(NvdimmNfitHeader));
406     /* NVDIMM device structures. */
407     g_array_append_vals(table_data, fit_buf->fit->data, fit_buf->fit->len);
408 
409     build_header(linker, table_data,
410                  (void *)(table_data->data + header), "NFIT",
411                  sizeof(NvdimmNfitHeader) + fit_buf->fit->len, 1, NULL, NULL);
412 }
413 
414 struct NvdimmDsmIn {
415     uint32_t handle;
416     uint32_t revision;
417     uint32_t function;
418     /* the remaining size in the page is used by arg3. */
419     union {
420         uint8_t arg3[4084];
421     };
422 } QEMU_PACKED;
423 typedef struct NvdimmDsmIn NvdimmDsmIn;
424 QEMU_BUILD_BUG_ON(sizeof(NvdimmDsmIn) != 4096);
425 
426 struct NvdimmDsmOut {
427     /* the size of buffer filled by QEMU. */
428     uint32_t len;
429     uint8_t data[4092];
430 } QEMU_PACKED;
431 typedef struct NvdimmDsmOut NvdimmDsmOut;
432 QEMU_BUILD_BUG_ON(sizeof(NvdimmDsmOut) != 4096);
433 
434 struct NvdimmDsmFunc0Out {
435     /* the size of buffer filled by QEMU. */
436      uint32_t len;
437      uint32_t supported_func;
438 } QEMU_PACKED;
439 typedef struct NvdimmDsmFunc0Out NvdimmDsmFunc0Out;
440 
441 struct NvdimmDsmFuncNoPayloadOut {
442     /* the size of buffer filled by QEMU. */
443      uint32_t len;
444      uint32_t func_ret_status;
445 } QEMU_PACKED;
446 typedef struct NvdimmDsmFuncNoPayloadOut NvdimmDsmFuncNoPayloadOut;
447 
448 struct NvdimmFuncGetLabelSizeOut {
449     /* the size of buffer filled by QEMU. */
450     uint32_t len;
451     uint32_t func_ret_status; /* return status code. */
452     uint32_t label_size; /* the size of label data area. */
453     /*
454      * Maximum size of the namespace label data length supported by
455      * the platform in Get/Set Namespace Label Data functions.
456      */
457     uint32_t max_xfer;
458 } QEMU_PACKED;
459 typedef struct NvdimmFuncGetLabelSizeOut NvdimmFuncGetLabelSizeOut;
460 QEMU_BUILD_BUG_ON(sizeof(NvdimmFuncGetLabelSizeOut) > 4096);
461 
462 struct NvdimmFuncGetLabelDataIn {
463     uint32_t offset; /* the offset in the namespace label data area. */
464     uint32_t length; /* the size of data is to be read via the function. */
465 } QEMU_PACKED;
466 typedef struct NvdimmFuncGetLabelDataIn NvdimmFuncGetLabelDataIn;
467 QEMU_BUILD_BUG_ON(sizeof(NvdimmFuncGetLabelDataIn) +
468                   offsetof(NvdimmDsmIn, arg3) > 4096);
469 
470 struct NvdimmFuncGetLabelDataOut {
471     /* the size of buffer filled by QEMU. */
472     uint32_t len;
473     uint32_t func_ret_status; /* return status code. */
474     uint8_t out_buf[0]; /* the data got via Get Namesapce Label function. */
475 } QEMU_PACKED;
476 typedef struct NvdimmFuncGetLabelDataOut NvdimmFuncGetLabelDataOut;
477 QEMU_BUILD_BUG_ON(sizeof(NvdimmFuncGetLabelDataOut) > 4096);
478 
479 struct NvdimmFuncSetLabelDataIn {
480     uint32_t offset; /* the offset in the namespace label data area. */
481     uint32_t length; /* the size of data is to be written via the function. */
482     uint8_t in_buf[0]; /* the data written to label data area. */
483 } QEMU_PACKED;
484 typedef struct NvdimmFuncSetLabelDataIn NvdimmFuncSetLabelDataIn;
485 QEMU_BUILD_BUG_ON(sizeof(NvdimmFuncSetLabelDataIn) +
486                   offsetof(NvdimmDsmIn, arg3) > 4096);
487 
488 struct NvdimmFuncReadFITIn {
489     uint32_t offset; /* the offset of FIT buffer. */
490 } QEMU_PACKED;
491 typedef struct NvdimmFuncReadFITIn NvdimmFuncReadFITIn;
492 QEMU_BUILD_BUG_ON(sizeof(NvdimmFuncReadFITIn) +
493                   offsetof(NvdimmDsmIn, arg3) > 4096);
494 
495 struct NvdimmFuncReadFITOut {
496     /* the size of buffer filled by QEMU. */
497     uint32_t len;
498     uint32_t func_ret_status; /* return status code. */
499     uint8_t fit[0]; /* the FIT data. */
500 } QEMU_PACKED;
501 typedef struct NvdimmFuncReadFITOut NvdimmFuncReadFITOut;
502 QEMU_BUILD_BUG_ON(sizeof(NvdimmFuncReadFITOut) > 4096);
503 
504 static void
505 nvdimm_dsm_function0(uint32_t supported_func, hwaddr dsm_mem_addr)
506 {
507     NvdimmDsmFunc0Out func0 = {
508         .len = cpu_to_le32(sizeof(func0)),
509         .supported_func = cpu_to_le32(supported_func),
510     };
511     cpu_physical_memory_write(dsm_mem_addr, &func0, sizeof(func0));
512 }
513 
514 static void
515 nvdimm_dsm_no_payload(uint32_t func_ret_status, hwaddr dsm_mem_addr)
516 {
517     NvdimmDsmFuncNoPayloadOut out = {
518         .len = cpu_to_le32(sizeof(out)),
519         .func_ret_status = cpu_to_le32(func_ret_status),
520     };
521     cpu_physical_memory_write(dsm_mem_addr, &out, sizeof(out));
522 }
523 
524 #define NVDIMM_QEMU_RSVD_HANDLE_ROOT 0x10000
525 
526 /* Read FIT data, defined in docs/specs/acpi_nvdimm.txt. */
527 static void nvdimm_dsm_func_read_fit(AcpiNVDIMMState *state, NvdimmDsmIn *in,
528                                      hwaddr dsm_mem_addr)
529 {
530     NvdimmFitBuffer *fit_buf = &state->fit_buf;
531     NvdimmFuncReadFITIn *read_fit;
532     NvdimmFuncReadFITOut *read_fit_out;
533     GArray *fit;
534     uint32_t read_len = 0, func_ret_status;
535     int size;
536 
537     read_fit = (NvdimmFuncReadFITIn *)in->arg3;
538     le32_to_cpus(&read_fit->offset);
539 
540     fit = fit_buf->fit;
541 
542     nvdimm_debug("Read FIT: offset %#x FIT size %#x Dirty %s.\n",
543                  read_fit->offset, fit->len, fit_buf->dirty ? "Yes" : "No");
544 
545     if (read_fit->offset > fit->len) {
546         func_ret_status = 3 /* Invalid Input Parameters */;
547         goto exit;
548     }
549 
550     /* It is the first time to read FIT. */
551     if (!read_fit->offset) {
552         fit_buf->dirty = false;
553     } else if (fit_buf->dirty) { /* FIT has been changed during RFIT. */
554         func_ret_status = 0x100 /* fit changed */;
555         goto exit;
556     }
557 
558     func_ret_status = 0 /* Success */;
559     read_len = MIN(fit->len - read_fit->offset,
560                    4096 - sizeof(NvdimmFuncReadFITOut));
561 
562 exit:
563     size = sizeof(NvdimmFuncReadFITOut) + read_len;
564     read_fit_out = g_malloc(size);
565 
566     read_fit_out->len = cpu_to_le32(size);
567     read_fit_out->func_ret_status = cpu_to_le32(func_ret_status);
568     memcpy(read_fit_out->fit, fit->data + read_fit->offset, read_len);
569 
570     cpu_physical_memory_write(dsm_mem_addr, read_fit_out, size);
571 
572     g_free(read_fit_out);
573 }
574 
575 static void nvdimm_dsm_reserved_root(AcpiNVDIMMState *state, NvdimmDsmIn *in,
576                                      hwaddr dsm_mem_addr)
577 {
578     switch (in->function) {
579     case 0x0:
580         nvdimm_dsm_function0(0x1 | 1 << 1 /* Read FIT */, dsm_mem_addr);
581         return;
582     case 0x1 /*Read FIT */:
583         nvdimm_dsm_func_read_fit(state, in, dsm_mem_addr);
584         return;
585     }
586 
587     nvdimm_dsm_no_payload(1 /* Not Supported */, dsm_mem_addr);
588 }
589 
590 static void nvdimm_dsm_root(NvdimmDsmIn *in, hwaddr dsm_mem_addr)
591 {
592     /*
593      * function 0 is called to inquire which functions are supported by
594      * OSPM
595      */
596     if (!in->function) {
597         nvdimm_dsm_function0(0 /* No function supported other than
598                                   function 0 */, dsm_mem_addr);
599         return;
600     }
601 
602     /* No function except function 0 is supported yet. */
603     nvdimm_dsm_no_payload(1 /* Not Supported */, dsm_mem_addr);
604 }
605 
606 /*
607  * the max transfer size is the max size transferred by both a
608  * 'Get Namespace Label Data' function and a 'Set Namespace Label Data'
609  * function.
610  */
611 static uint32_t nvdimm_get_max_xfer_label_size(void)
612 {
613     uint32_t max_get_size, max_set_size, dsm_memory_size = 4096;
614 
615     /*
616      * the max data ACPI can read one time which is transferred by
617      * the response of 'Get Namespace Label Data' function.
618      */
619     max_get_size = dsm_memory_size - sizeof(NvdimmFuncGetLabelDataOut);
620 
621     /*
622      * the max data ACPI can write one time which is transferred by
623      * 'Set Namespace Label Data' function.
624      */
625     max_set_size = dsm_memory_size - offsetof(NvdimmDsmIn, arg3) -
626                    sizeof(NvdimmFuncSetLabelDataIn);
627 
628     return MIN(max_get_size, max_set_size);
629 }
630 
631 /*
632  * DSM Spec Rev1 4.4 Get Namespace Label Size (Function Index 4).
633  *
634  * It gets the size of Namespace Label data area and the max data size
635  * that Get/Set Namespace Label Data functions can transfer.
636  */
637 static void nvdimm_dsm_label_size(NVDIMMDevice *nvdimm, hwaddr dsm_mem_addr)
638 {
639     NvdimmFuncGetLabelSizeOut label_size_out = {
640         .len = cpu_to_le32(sizeof(label_size_out)),
641     };
642     uint32_t label_size, mxfer;
643 
644     label_size = nvdimm->label_size;
645     mxfer = nvdimm_get_max_xfer_label_size();
646 
647     nvdimm_debug("label_size %#x, max_xfer %#x.\n", label_size, mxfer);
648 
649     label_size_out.func_ret_status = cpu_to_le32(0 /* Success */);
650     label_size_out.label_size = cpu_to_le32(label_size);
651     label_size_out.max_xfer = cpu_to_le32(mxfer);
652 
653     cpu_physical_memory_write(dsm_mem_addr, &label_size_out,
654                               sizeof(label_size_out));
655 }
656 
657 static uint32_t nvdimm_rw_label_data_check(NVDIMMDevice *nvdimm,
658                                            uint32_t offset, uint32_t length)
659 {
660     uint32_t ret = 3 /* Invalid Input Parameters */;
661 
662     if (offset + length < offset) {
663         nvdimm_debug("offset %#x + length %#x is overflow.\n", offset,
664                      length);
665         return ret;
666     }
667 
668     if (nvdimm->label_size < offset + length) {
669         nvdimm_debug("position %#x is beyond label data (len = %" PRIx64 ").\n",
670                      offset + length, nvdimm->label_size);
671         return ret;
672     }
673 
674     if (length > nvdimm_get_max_xfer_label_size()) {
675         nvdimm_debug("length (%#x) is larger than max_xfer (%#x).\n",
676                      length, nvdimm_get_max_xfer_label_size());
677         return ret;
678     }
679 
680     return 0 /* Success */;
681 }
682 
683 /*
684  * DSM Spec Rev1 4.5 Get Namespace Label Data (Function Index 5).
685  */
686 static void nvdimm_dsm_get_label_data(NVDIMMDevice *nvdimm, NvdimmDsmIn *in,
687                                       hwaddr dsm_mem_addr)
688 {
689     NVDIMMClass *nvc = NVDIMM_GET_CLASS(nvdimm);
690     NvdimmFuncGetLabelDataIn *get_label_data;
691     NvdimmFuncGetLabelDataOut *get_label_data_out;
692     uint32_t status;
693     int size;
694 
695     get_label_data = (NvdimmFuncGetLabelDataIn *)in->arg3;
696     le32_to_cpus(&get_label_data->offset);
697     le32_to_cpus(&get_label_data->length);
698 
699     nvdimm_debug("Read Label Data: offset %#x length %#x.\n",
700                  get_label_data->offset, get_label_data->length);
701 
702     status = nvdimm_rw_label_data_check(nvdimm, get_label_data->offset,
703                                         get_label_data->length);
704     if (status != 0 /* Success */) {
705         nvdimm_dsm_no_payload(status, dsm_mem_addr);
706         return;
707     }
708 
709     size = sizeof(*get_label_data_out) + get_label_data->length;
710     assert(size <= 4096);
711     get_label_data_out = g_malloc(size);
712 
713     get_label_data_out->len = cpu_to_le32(size);
714     get_label_data_out->func_ret_status = cpu_to_le32(0 /* Success */);
715     nvc->read_label_data(nvdimm, get_label_data_out->out_buf,
716                          get_label_data->length, get_label_data->offset);
717 
718     cpu_physical_memory_write(dsm_mem_addr, get_label_data_out, size);
719     g_free(get_label_data_out);
720 }
721 
722 /*
723  * DSM Spec Rev1 4.6 Set Namespace Label Data (Function Index 6).
724  */
725 static void nvdimm_dsm_set_label_data(NVDIMMDevice *nvdimm, NvdimmDsmIn *in,
726                                       hwaddr dsm_mem_addr)
727 {
728     NVDIMMClass *nvc = NVDIMM_GET_CLASS(nvdimm);
729     NvdimmFuncSetLabelDataIn *set_label_data;
730     uint32_t status;
731 
732     set_label_data = (NvdimmFuncSetLabelDataIn *)in->arg3;
733 
734     le32_to_cpus(&set_label_data->offset);
735     le32_to_cpus(&set_label_data->length);
736 
737     nvdimm_debug("Write Label Data: offset %#x length %#x.\n",
738                  set_label_data->offset, set_label_data->length);
739 
740     status = nvdimm_rw_label_data_check(nvdimm, set_label_data->offset,
741                                         set_label_data->length);
742     if (status != 0 /* Success */) {
743         nvdimm_dsm_no_payload(status, dsm_mem_addr);
744         return;
745     }
746 
747     assert(offsetof(NvdimmDsmIn, arg3) +
748            sizeof(*set_label_data) + set_label_data->length <= 4096);
749 
750     nvc->write_label_data(nvdimm, set_label_data->in_buf,
751                           set_label_data->length, set_label_data->offset);
752     nvdimm_dsm_no_payload(0 /* Success */, dsm_mem_addr);
753 }
754 
755 static void nvdimm_dsm_device(NvdimmDsmIn *in, hwaddr dsm_mem_addr)
756 {
757     NVDIMMDevice *nvdimm = nvdimm_get_device_by_handle(in->handle);
758 
759     /* See the comments in nvdimm_dsm_root(). */
760     if (!in->function) {
761         uint32_t supported_func = 0;
762 
763         if (nvdimm && nvdimm->label_size) {
764             supported_func |= 0x1 /* Bit 0 indicates whether there is
765                                      support for any functions other
766                                      than function 0. */ |
767                               1 << 4 /* Get Namespace Label Size */ |
768                               1 << 5 /* Get Namespace Label Data */ |
769                               1 << 6 /* Set Namespace Label Data */;
770         }
771         nvdimm_dsm_function0(supported_func, dsm_mem_addr);
772         return;
773     }
774 
775     if (!nvdimm) {
776         nvdimm_dsm_no_payload(2 /* Non-Existing Memory Device */,
777                               dsm_mem_addr);
778         return;
779     }
780 
781     /* Encode DSM function according to DSM Spec Rev1. */
782     switch (in->function) {
783     case 4 /* Get Namespace Label Size */:
784         if (nvdimm->label_size) {
785             nvdimm_dsm_label_size(nvdimm, dsm_mem_addr);
786             return;
787         }
788         break;
789     case 5 /* Get Namespace Label Data */:
790         if (nvdimm->label_size) {
791             nvdimm_dsm_get_label_data(nvdimm, in, dsm_mem_addr);
792             return;
793         }
794         break;
795     case 0x6 /* Set Namespace Label Data */:
796         if (nvdimm->label_size) {
797             nvdimm_dsm_set_label_data(nvdimm, in, dsm_mem_addr);
798             return;
799         }
800         break;
801     }
802 
803     nvdimm_dsm_no_payload(1 /* Not Supported */, dsm_mem_addr);
804 }
805 
806 static uint64_t
807 nvdimm_dsm_read(void *opaque, hwaddr addr, unsigned size)
808 {
809     nvdimm_debug("BUG: we never read _DSM IO Port.\n");
810     return 0;
811 }
812 
813 static void
814 nvdimm_dsm_write(void *opaque, hwaddr addr, uint64_t val, unsigned size)
815 {
816     AcpiNVDIMMState *state = opaque;
817     NvdimmDsmIn *in;
818     hwaddr dsm_mem_addr = val;
819 
820     nvdimm_debug("dsm memory address %#" HWADDR_PRIx ".\n", dsm_mem_addr);
821 
822     /*
823      * The DSM memory is mapped to guest address space so an evil guest
824      * can change its content while we are doing DSM emulation. Avoid
825      * this by copying DSM memory to QEMU local memory.
826      */
827     in = g_new(NvdimmDsmIn, 1);
828     cpu_physical_memory_read(dsm_mem_addr, in, sizeof(*in));
829 
830     le32_to_cpus(&in->revision);
831     le32_to_cpus(&in->function);
832     le32_to_cpus(&in->handle);
833 
834     nvdimm_debug("Revision %#x Handler %#x Function %#x.\n", in->revision,
835                  in->handle, in->function);
836 
837     if (in->revision != 0x1 /* Currently we only support DSM Spec Rev1. */) {
838         nvdimm_debug("Revision %#x is not supported, expect %#x.\n",
839                      in->revision, 0x1);
840         nvdimm_dsm_no_payload(1 /* Not Supported */, dsm_mem_addr);
841         goto exit;
842     }
843 
844     if (in->handle == NVDIMM_QEMU_RSVD_HANDLE_ROOT) {
845         nvdimm_dsm_reserved_root(state, in, dsm_mem_addr);
846         goto exit;
847     }
848 
849      /* Handle 0 is reserved for NVDIMM Root Device. */
850     if (!in->handle) {
851         nvdimm_dsm_root(in, dsm_mem_addr);
852         goto exit;
853     }
854 
855     nvdimm_dsm_device(in, dsm_mem_addr);
856 
857 exit:
858     g_free(in);
859 }
860 
861 static const MemoryRegionOps nvdimm_dsm_ops = {
862     .read = nvdimm_dsm_read,
863     .write = nvdimm_dsm_write,
864     .endianness = DEVICE_LITTLE_ENDIAN,
865     .valid = {
866         .min_access_size = 4,
867         .max_access_size = 4,
868     },
869 };
870 
871 void nvdimm_acpi_plug_cb(HotplugHandler *hotplug_dev, DeviceState *dev)
872 {
873     if (dev->hotplugged) {
874         acpi_send_event(DEVICE(hotplug_dev), ACPI_NVDIMM_HOTPLUG_STATUS);
875     }
876 }
877 
878 void nvdimm_init_acpi_state(AcpiNVDIMMState *state, MemoryRegion *io,
879                             FWCfgState *fw_cfg, Object *owner)
880 {
881     memory_region_init_io(&state->io_mr, owner, &nvdimm_dsm_ops, state,
882                           "nvdimm-acpi-io", NVDIMM_ACPI_IO_LEN);
883     memory_region_add_subregion(io, NVDIMM_ACPI_IO_BASE, &state->io_mr);
884 
885     state->dsm_mem = g_array_new(false, true /* clear */, 1);
886     acpi_data_push(state->dsm_mem, sizeof(NvdimmDsmIn));
887     fw_cfg_add_file(fw_cfg, NVDIMM_DSM_MEM_FILE, state->dsm_mem->data,
888                     state->dsm_mem->len);
889 
890     nvdimm_init_fit_buffer(&state->fit_buf);
891 }
892 
893 #define NVDIMM_COMMON_DSM       "NCAL"
894 #define NVDIMM_ACPI_MEM_ADDR    "MEMA"
895 
896 #define NVDIMM_DSM_MEMORY       "NRAM"
897 #define NVDIMM_DSM_IOPORT       "NPIO"
898 
899 #define NVDIMM_DSM_NOTIFY       "NTFI"
900 #define NVDIMM_DSM_HANDLE       "HDLE"
901 #define NVDIMM_DSM_REVISION     "REVS"
902 #define NVDIMM_DSM_FUNCTION     "FUNC"
903 #define NVDIMM_DSM_ARG3         "FARG"
904 
905 #define NVDIMM_DSM_OUT_BUF_SIZE "RLEN"
906 #define NVDIMM_DSM_OUT_BUF      "ODAT"
907 
908 #define NVDIMM_DSM_RFIT_STATUS  "RSTA"
909 
910 #define NVDIMM_QEMU_RSVD_UUID   "648B9CF2-CDA1-4312-8AD9-49C4AF32BD62"
911 
912 static void nvdimm_build_common_dsm(Aml *dev)
913 {
914     Aml *method, *ifctx, *function, *handle, *uuid, *dsm_mem, *elsectx2;
915     Aml *elsectx, *unsupport, *unpatched, *expected_uuid, *uuid_invalid;
916     Aml *pckg, *pckg_index, *pckg_buf, *field, *dsm_out_buf, *dsm_out_buf_size;
917     uint8_t byte_list[1];
918 
919     method = aml_method(NVDIMM_COMMON_DSM, 5, AML_SERIALIZED);
920     uuid = aml_arg(0);
921     function = aml_arg(2);
922     handle = aml_arg(4);
923     dsm_mem = aml_local(6);
924     dsm_out_buf = aml_local(7);
925 
926     aml_append(method, aml_store(aml_name(NVDIMM_ACPI_MEM_ADDR), dsm_mem));
927 
928     /* map DSM memory and IO into ACPI namespace. */
929     aml_append(method, aml_operation_region(NVDIMM_DSM_IOPORT, AML_SYSTEM_IO,
930                aml_int(NVDIMM_ACPI_IO_BASE), NVDIMM_ACPI_IO_LEN));
931     aml_append(method, aml_operation_region(NVDIMM_DSM_MEMORY,
932                AML_SYSTEM_MEMORY, dsm_mem, sizeof(NvdimmDsmIn)));
933 
934     /*
935      * DSM notifier:
936      * NVDIMM_DSM_NOTIFY: write the address of DSM memory and notify QEMU to
937      *                    emulate the access.
938      *
939      * It is the IO port so that accessing them will cause VM-exit, the
940      * control will be transferred to QEMU.
941      */
942     field = aml_field(NVDIMM_DSM_IOPORT, AML_DWORD_ACC, AML_NOLOCK,
943                       AML_PRESERVE);
944     aml_append(field, aml_named_field(NVDIMM_DSM_NOTIFY,
945                sizeof(uint32_t) * BITS_PER_BYTE));
946     aml_append(method, field);
947 
948     /*
949      * DSM input:
950      * NVDIMM_DSM_HANDLE: store device's handle, it's zero if the _DSM call
951      *                    happens on NVDIMM Root Device.
952      * NVDIMM_DSM_REVISION: store the Arg1 of _DSM call.
953      * NVDIMM_DSM_FUNCTION: store the Arg2 of _DSM call.
954      * NVDIMM_DSM_ARG3: store the Arg3 of _DSM call which is a Package
955      *                  containing function-specific arguments.
956      *
957      * They are RAM mapping on host so that these accesses never cause
958      * VM-EXIT.
959      */
960     field = aml_field(NVDIMM_DSM_MEMORY, AML_DWORD_ACC, AML_NOLOCK,
961                       AML_PRESERVE);
962     aml_append(field, aml_named_field(NVDIMM_DSM_HANDLE,
963                sizeof(typeof_field(NvdimmDsmIn, handle)) * BITS_PER_BYTE));
964     aml_append(field, aml_named_field(NVDIMM_DSM_REVISION,
965                sizeof(typeof_field(NvdimmDsmIn, revision)) * BITS_PER_BYTE));
966     aml_append(field, aml_named_field(NVDIMM_DSM_FUNCTION,
967                sizeof(typeof_field(NvdimmDsmIn, function)) * BITS_PER_BYTE));
968     aml_append(field, aml_named_field(NVDIMM_DSM_ARG3,
969          (sizeof(NvdimmDsmIn) - offsetof(NvdimmDsmIn, arg3)) * BITS_PER_BYTE));
970     aml_append(method, field);
971 
972     /*
973      * DSM output:
974      * NVDIMM_DSM_OUT_BUF_SIZE: the size of the buffer filled by QEMU.
975      * NVDIMM_DSM_OUT_BUF: the buffer QEMU uses to store the result.
976      *
977      * Since the page is reused by both input and out, the input data
978      * will be lost after storing new result into ODAT so we should fetch
979      * all the input data before writing the result.
980      */
981     field = aml_field(NVDIMM_DSM_MEMORY, AML_DWORD_ACC, AML_NOLOCK,
982                       AML_PRESERVE);
983     aml_append(field, aml_named_field(NVDIMM_DSM_OUT_BUF_SIZE,
984                sizeof(typeof_field(NvdimmDsmOut, len)) * BITS_PER_BYTE));
985     aml_append(field, aml_named_field(NVDIMM_DSM_OUT_BUF,
986        (sizeof(NvdimmDsmOut) - offsetof(NvdimmDsmOut, data)) * BITS_PER_BYTE));
987     aml_append(method, field);
988 
989     /*
990      * do not support any method if DSM memory address has not been
991      * patched.
992      */
993     unpatched = aml_equal(dsm_mem, aml_int(0x0));
994 
995     expected_uuid = aml_local(0);
996 
997     ifctx = aml_if(aml_equal(handle, aml_int(0x0)));
998     aml_append(ifctx, aml_store(
999                aml_touuid("2F10E7A4-9E91-11E4-89D3-123B93F75CBA")
1000                /* UUID for NVDIMM Root Device */, expected_uuid));
1001     aml_append(method, ifctx);
1002     elsectx = aml_else();
1003     ifctx = aml_if(aml_equal(handle, aml_int(NVDIMM_QEMU_RSVD_HANDLE_ROOT)));
1004     aml_append(ifctx, aml_store(aml_touuid(NVDIMM_QEMU_RSVD_UUID
1005                /* UUID for QEMU internal use */), expected_uuid));
1006     aml_append(elsectx, ifctx);
1007     elsectx2 = aml_else();
1008     aml_append(elsectx2, aml_store(
1009                aml_touuid("4309AC30-0D11-11E4-9191-0800200C9A66")
1010                /* UUID for NVDIMM Devices */, expected_uuid));
1011     aml_append(elsectx, elsectx2);
1012     aml_append(method, elsectx);
1013 
1014     uuid_invalid = aml_lnot(aml_equal(uuid, expected_uuid));
1015 
1016     unsupport = aml_if(aml_or(unpatched, uuid_invalid, NULL));
1017 
1018     /*
1019      * function 0 is called to inquire what functions are supported by
1020      * OSPM
1021      */
1022     ifctx = aml_if(aml_equal(function, aml_int(0)));
1023     byte_list[0] = 0 /* No function Supported */;
1024     aml_append(ifctx, aml_return(aml_buffer(1, byte_list)));
1025     aml_append(unsupport, ifctx);
1026 
1027     /* No function is supported yet. */
1028     byte_list[0] = 1 /* Not Supported */;
1029     aml_append(unsupport, aml_return(aml_buffer(1, byte_list)));
1030     aml_append(method, unsupport);
1031 
1032     /*
1033      * The HDLE indicates the DSM function is issued from which device,
1034      * it reserves 0 for root device and is the handle for NVDIMM devices.
1035      * See the comments in nvdimm_slot_to_handle().
1036      */
1037     aml_append(method, aml_store(handle, aml_name(NVDIMM_DSM_HANDLE)));
1038     aml_append(method, aml_store(aml_arg(1), aml_name(NVDIMM_DSM_REVISION)));
1039     aml_append(method, aml_store(aml_arg(2), aml_name(NVDIMM_DSM_FUNCTION)));
1040 
1041     /*
1042      * The fourth parameter (Arg3) of _DSM is a package which contains
1043      * a buffer, the layout of the buffer is specified by UUID (Arg0),
1044      * Revision ID (Arg1) and Function Index (Arg2) which are documented
1045      * in the DSM Spec.
1046      */
1047     pckg = aml_arg(3);
1048     ifctx = aml_if(aml_and(aml_equal(aml_object_type(pckg),
1049                    aml_int(4 /* Package */)) /* It is a Package? */,
1050                    aml_equal(aml_sizeof(pckg), aml_int(1)) /* 1 element? */,
1051                    NULL));
1052 
1053     pckg_index = aml_local(2);
1054     pckg_buf = aml_local(3);
1055     aml_append(ifctx, aml_store(aml_index(pckg, aml_int(0)), pckg_index));
1056     aml_append(ifctx, aml_store(aml_derefof(pckg_index), pckg_buf));
1057     aml_append(ifctx, aml_store(pckg_buf, aml_name(NVDIMM_DSM_ARG3)));
1058     aml_append(method, ifctx);
1059 
1060     /*
1061      * tell QEMU about the real address of DSM memory, then QEMU
1062      * gets the control and fills the result in DSM memory.
1063      */
1064     aml_append(method, aml_store(dsm_mem, aml_name(NVDIMM_DSM_NOTIFY)));
1065 
1066     dsm_out_buf_size = aml_local(1);
1067     /* RLEN is not included in the payload returned to guest. */
1068     aml_append(method, aml_subtract(aml_name(NVDIMM_DSM_OUT_BUF_SIZE),
1069                aml_int(4), dsm_out_buf_size));
1070     aml_append(method, aml_store(aml_shiftleft(dsm_out_buf_size, aml_int(3)),
1071                                  dsm_out_buf_size));
1072     aml_append(method, aml_create_field(aml_name(NVDIMM_DSM_OUT_BUF),
1073                aml_int(0), dsm_out_buf_size, "OBUF"));
1074     aml_append(method, aml_concatenate(aml_buffer(0, NULL), aml_name("OBUF"),
1075                                        dsm_out_buf));
1076     aml_append(method, aml_return(dsm_out_buf));
1077     aml_append(dev, method);
1078 }
1079 
1080 static void nvdimm_build_device_dsm(Aml *dev, uint32_t handle)
1081 {
1082     Aml *method;
1083 
1084     method = aml_method("_DSM", 4, AML_NOTSERIALIZED);
1085     aml_append(method, aml_return(aml_call5(NVDIMM_COMMON_DSM, aml_arg(0),
1086                                   aml_arg(1), aml_arg(2), aml_arg(3),
1087                                   aml_int(handle))));
1088     aml_append(dev, method);
1089 }
1090 
1091 static void nvdimm_build_fit(Aml *dev)
1092 {
1093     Aml *method, *pkg, *buf, *buf_size, *offset, *call_result;
1094     Aml *whilectx, *ifcond, *ifctx, *elsectx, *fit;
1095 
1096     buf = aml_local(0);
1097     buf_size = aml_local(1);
1098     fit = aml_local(2);
1099 
1100     aml_append(dev, aml_create_dword_field(aml_buffer(4, NULL),
1101                aml_int(0), NVDIMM_DSM_RFIT_STATUS));
1102 
1103     /* build helper function, RFIT. */
1104     method = aml_method("RFIT", 1, AML_SERIALIZED);
1105     aml_append(method, aml_create_dword_field(aml_buffer(4, NULL),
1106                                               aml_int(0), "OFST"));
1107 
1108     /* prepare input package. */
1109     pkg = aml_package(1);
1110     aml_append(method, aml_store(aml_arg(0), aml_name("OFST")));
1111     aml_append(pkg, aml_name("OFST"));
1112 
1113     /* call Read_FIT function. */
1114     call_result = aml_call5(NVDIMM_COMMON_DSM,
1115                             aml_touuid(NVDIMM_QEMU_RSVD_UUID),
1116                             aml_int(1) /* Revision 1 */,
1117                             aml_int(0x1) /* Read FIT */,
1118                             pkg, aml_int(NVDIMM_QEMU_RSVD_HANDLE_ROOT));
1119     aml_append(method, aml_store(call_result, buf));
1120 
1121     /* handle _DSM result. */
1122     aml_append(method, aml_create_dword_field(buf,
1123                aml_int(0) /* offset at byte 0 */, "STAU"));
1124 
1125     aml_append(method, aml_store(aml_name("STAU"),
1126                                  aml_name(NVDIMM_DSM_RFIT_STATUS)));
1127 
1128      /* if something is wrong during _DSM. */
1129     ifcond = aml_equal(aml_int(0 /* Success */), aml_name("STAU"));
1130     ifctx = aml_if(aml_lnot(ifcond));
1131     aml_append(ifctx, aml_return(aml_buffer(0, NULL)));
1132     aml_append(method, ifctx);
1133 
1134     aml_append(method, aml_store(aml_sizeof(buf), buf_size));
1135     aml_append(method, aml_subtract(buf_size,
1136                                     aml_int(4) /* the size of "STAU" */,
1137                                     buf_size));
1138 
1139     /* if we read the end of fit. */
1140     ifctx = aml_if(aml_equal(buf_size, aml_int(0)));
1141     aml_append(ifctx, aml_return(aml_buffer(0, NULL)));
1142     aml_append(method, ifctx);
1143 
1144     aml_append(method, aml_store(aml_shiftleft(buf_size, aml_int(3)),
1145                                  buf_size));
1146     aml_append(method, aml_create_field(buf,
1147                             aml_int(4 * BITS_PER_BYTE), /* offset at byte 4.*/
1148                             buf_size, "BUFF"));
1149     aml_append(method, aml_return(aml_name("BUFF")));
1150     aml_append(dev, method);
1151 
1152     /* build _FIT. */
1153     method = aml_method("_FIT", 0, AML_SERIALIZED);
1154     offset = aml_local(3);
1155 
1156     aml_append(method, aml_store(aml_buffer(0, NULL), fit));
1157     aml_append(method, aml_store(aml_int(0), offset));
1158 
1159     whilectx = aml_while(aml_int(1));
1160     aml_append(whilectx, aml_store(aml_call1("RFIT", offset), buf));
1161     aml_append(whilectx, aml_store(aml_sizeof(buf), buf_size));
1162 
1163     /*
1164      * if fit buffer was changed during RFIT, read from the beginning
1165      * again.
1166      */
1167     ifctx = aml_if(aml_equal(aml_name(NVDIMM_DSM_RFIT_STATUS),
1168                              aml_int(0x100 /* fit changed */)));
1169     aml_append(ifctx, aml_store(aml_buffer(0, NULL), fit));
1170     aml_append(ifctx, aml_store(aml_int(0), offset));
1171     aml_append(whilectx, ifctx);
1172 
1173     elsectx = aml_else();
1174 
1175     /* finish fit read if no data is read out. */
1176     ifctx = aml_if(aml_equal(buf_size, aml_int(0)));
1177     aml_append(ifctx, aml_return(fit));
1178     aml_append(elsectx, ifctx);
1179 
1180     /* update the offset. */
1181     aml_append(elsectx, aml_add(offset, buf_size, offset));
1182     /* append the data we read out to the fit buffer. */
1183     aml_append(elsectx, aml_concatenate(fit, buf, fit));
1184     aml_append(whilectx, elsectx);
1185     aml_append(method, whilectx);
1186 
1187     aml_append(dev, method);
1188 }
1189 
1190 static void nvdimm_build_nvdimm_devices(Aml *root_dev, uint32_t ram_slots)
1191 {
1192     uint32_t slot;
1193 
1194     for (slot = 0; slot < ram_slots; slot++) {
1195         uint32_t handle = nvdimm_slot_to_handle(slot);
1196         Aml *nvdimm_dev;
1197 
1198         nvdimm_dev = aml_device("NV%02X", slot);
1199 
1200         /*
1201          * ACPI 6.0: 9.20 NVDIMM Devices:
1202          *
1203          * _ADR object that is used to supply OSPM with unique address
1204          * of the NVDIMM device. This is done by returning the NFIT Device
1205          * handle that is used to identify the associated entries in ACPI
1206          * table NFIT or _FIT.
1207          */
1208         aml_append(nvdimm_dev, aml_name_decl("_ADR", aml_int(handle)));
1209 
1210         nvdimm_build_device_dsm(nvdimm_dev, handle);
1211         aml_append(root_dev, nvdimm_dev);
1212     }
1213 }
1214 
1215 static void nvdimm_build_ssdt(GArray *table_offsets, GArray *table_data,
1216                               BIOSLinker *linker, GArray *dsm_dma_arrea,
1217                               uint32_t ram_slots)
1218 {
1219     Aml *ssdt, *sb_scope, *dev;
1220     int mem_addr_offset, nvdimm_ssdt;
1221 
1222     acpi_add_table(table_offsets, table_data);
1223 
1224     ssdt = init_aml_allocator();
1225     acpi_data_push(ssdt->buf, sizeof(AcpiTableHeader));
1226 
1227     sb_scope = aml_scope("\\_SB");
1228 
1229     dev = aml_device("NVDR");
1230 
1231     /*
1232      * ACPI 6.0: 9.20 NVDIMM Devices:
1233      *
1234      * The ACPI Name Space device uses _HID of ACPI0012 to identify the root
1235      * NVDIMM interface device. Platform firmware is required to contain one
1236      * such device in _SB scope if NVDIMMs support is exposed by platform to
1237      * OSPM.
1238      * For each NVDIMM present or intended to be supported by platform,
1239      * platform firmware also exposes an ACPI Namespace Device under the
1240      * root device.
1241      */
1242     aml_append(dev, aml_name_decl("_HID", aml_string("ACPI0012")));
1243 
1244     nvdimm_build_common_dsm(dev);
1245 
1246     /* 0 is reserved for root device. */
1247     nvdimm_build_device_dsm(dev, 0);
1248     nvdimm_build_fit(dev);
1249 
1250     nvdimm_build_nvdimm_devices(dev, ram_slots);
1251 
1252     aml_append(sb_scope, dev);
1253     aml_append(ssdt, sb_scope);
1254 
1255     nvdimm_ssdt = table_data->len;
1256 
1257     /* copy AML table into ACPI tables blob and patch header there */
1258     g_array_append_vals(table_data, ssdt->buf->data, ssdt->buf->len);
1259     mem_addr_offset = build_append_named_dword(table_data,
1260                                                NVDIMM_ACPI_MEM_ADDR);
1261 
1262     bios_linker_loader_alloc(linker,
1263                              NVDIMM_DSM_MEM_FILE, dsm_dma_arrea,
1264                              sizeof(NvdimmDsmIn), false /* high memory */);
1265     bios_linker_loader_add_pointer(linker,
1266         ACPI_BUILD_TABLE_FILE, mem_addr_offset, sizeof(uint32_t),
1267         NVDIMM_DSM_MEM_FILE, 0);
1268     build_header(linker, table_data,
1269         (void *)(table_data->data + nvdimm_ssdt),
1270         "SSDT", table_data->len - nvdimm_ssdt, 1, NULL, "NVDIMM");
1271     free_aml_allocator();
1272 }
1273 
1274 void nvdimm_build_acpi(GArray *table_offsets, GArray *table_data,
1275                        BIOSLinker *linker, AcpiNVDIMMState *state,
1276                        uint32_t ram_slots)
1277 {
1278     nvdimm_build_nfit(state, table_offsets, table_data, linker);
1279 
1280     /*
1281      * NVDIMM device is allowed to be plugged only if there is available
1282      * slot.
1283      */
1284     if (ram_slots) {
1285         nvdimm_build_ssdt(table_offsets, table_data, linker, state->dsm_mem,
1286                           ram_slots);
1287     }
1288 }
1289