1 /* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  */
5 
6 /* APIs provided by firmware to vboot_reference.
7  *
8  * General notes:
9  *
10  * All verified boot functions now start with "Vb" for namespace clarity.  This
11  * fixes the problem where uboot and vboot both defined assert().
12  *
13  * Verified boot APIs to be implemented by the calling firmware and exported to
14  * vboot_reference start with "VbEx".
15  *
16  * TODO: split this file into a vboot_entry_points.h file which contains the
17  * entry points for the firmware to call vboot_reference, and a
18  * vboot_firmware_exports.h which contains the APIs to be implemented by the
19  * calling firmware and exported to vboot_reference.
20  */
21 
22 #ifndef VBOOT_REFERENCE_VBOOT_API_H_
23 #define VBOOT_REFERENCE_VBOOT_API_H_
24 #include <stdint.h>
25 #include <stdlib.h>
26 
27 /*****************************************************************************/
28 /* Error codes */
29 
30 /*
31  * Functions which return an error all return this type.  This is a 32-bit
32  * value rather than an int so it's consistent across UEFI, which is 32-bit
33  * during PEI and 64-bit during DXE/BDS.
34  */
35 typedef uint32_t VbError_t;
36 
37 /*
38  * Predefined error numbers.  Success is 0.  Errors are non-zero, but differ
39  * between functions.  For example, the TPM functions may pass through TPM
40  * error codes, some of which may be recoverable.
41  */
42 enum VbErrorPredefined_t {
43 	/* No error; function completed successfully. */
44 	VBERROR_SUCCESS                       = 0,
45 
46 	/*
47 	 * The verified boot entry points VbInit(), VbSelectFirmware(),
48 	 * VbSelectAndLoadKernel() may return the following errors.
49 	 */
50 	/* Unknown error */
51 	VBERROR_UNKNOWN                       = 0x10000,
52 	/* Unable to initialize shared data */
53 	VBERROR_INIT_SHARED_DATA              = 0x10001,
54 	/* Error resuming TPM during a S3 resume */
55 	VBERROR_TPM_S3_RESUME                 = 0x10002,
56 	/* VbSelectFirmware() failed to find a valid firmware */
57 	VBERROR_LOAD_FIRMWARE                 = 0x10003,
58 	/* Unable to write firmware versions to TPM */
59 	VBERROR_TPM_WRITE_FIRMWARE            = 0x10004,
60 	/* Unable to lock firmware versions in TPM */
61 	VBERROR_TPM_LOCK_FIRMWARE             = 0x10005,
62 	/* Unable to set boot mode state in TPM */
63 	VBERROR_TPM_SET_BOOT_MODE_STATE       = 0x10006,
64 	/* TPM requires reboot */
65 	VBERROR_TPM_REBOOT_REQUIRED           = 0x10007,
66 	/* Unable to set up TPM */
67 	VBERROR_TPM_FIRMWARE_SETUP            = 0x10008,
68 	/* Unable to read kernel versions from TPM */
69 	VBERROR_TPM_READ_KERNEL               = 0x10009,
70 	/* Attempt to load developer-only firmware with developer switch off */
71 	VBERROR_DEV_FIRMWARE_SWITCH_MISMATCH  = 0x1000A,
72 	/* Unable to write kernel versions to TPM */
73 	VBERROR_TPM_WRITE_KERNEL              = 0x1000B,
74 	/* Unable to lock kernel versions in TPM */
75 	VBERROR_TPM_LOCK_KERNEL               = 0x1000C,
76 	/* Calling firmware requested shutdown via VbExIsShutdownRequested() */
77 	VBERROR_SHUTDOWN_REQUESTED            = 0x1000D,
78 	/* Unable to find a boot device on which to look for a kernel */
79 	VBERROR_NO_DISK_FOUND                 = 0x1000E,
80 	/* No OS kernel found on any boot device */
81 	VBERROR_NO_KERNEL_FOUND               = 0x1000F,
82 	/* All OS kernels found were invalid (corrupt, improperly signed...) */
83 	VBERROR_INVALID_KERNEL_FOUND          = 0x10010,
84 	/* VbSelectAndLoadKernel() requested recovery mode */
85 	VBERROR_LOAD_KERNEL_RECOVERY          = 0x10011,
86 	/* Other error inside VbSelectAndLoadKernel() */
87 	VBERROR_LOAD_KERNEL                   = 0x10012,
88 	/* Invalid Google binary block */
89 	VBERROR_INVALID_GBB                   = 0x10013,
90 	/* Invalid bitmap volume */
91 	VBERROR_INVALID_BMPFV                 = 0x10014,
92 	/* Invalid screen index */
93 	VBERROR_INVALID_SCREEN_INDEX          = 0x10015,
94 	/* Simulated (test) error */
95 	VBERROR_SIMULATED                     = 0x10016,
96 	/* Invalid parameter */
97 	VBERROR_INVALID_PARAMETER             = 0x10017,
98 	/* VbExBeep() can't make sounds at all */
99 	VBERROR_NO_SOUND                      = 0x10018,
100 	/* VbExBeep() can't make sound in the background */
101 	VBERROR_NO_BACKGROUND_SOUND           = 0x10019,
102 	/* Developer has requested a BIOS shell */
103 	VBERROR_BIOS_SHELL_REQUESTED          = 0x10020,
104 	/* Need VGA and don't have it, or vice-versa */
105 	VBERROR_VGA_OPROM_MISMATCH            = 0x10021,
106 	/* Need EC to reboot to read-only code */
107 	VBERROR_EC_REBOOT_TO_RO_REQUIRED      = 0x10022,
108 	/* Invalid region read parameters */
109 	VBERROR_REGION_READ_INVALID           = 0x10023,
110 	/* Cannot read from region */
111 	VBERROR_REGION_READ_FAILED            = 0x10024,
112 	/* Unsupported region type */
113 	VBERROR_UNSUPPORTED_REGION            = 0x10025,
114 	/* No image present (returned from VbGbbReadImage() for missing image) */
115 	VBERROR_NO_IMAGE_PRESENT              = 0x10026,
116 
117 	/* VbExEcGetExpectedRWHash() may return the following codes */
118 	/* Compute expected RW hash from the EC image; BIOS doesn't have it */
119 	VBERROR_EC_GET_EXPECTED_HASH_FROM_IMAGE = 0x20000,
120 };
121 
122 
123 /*****************************************************************************/
124 /* Main entry points from firmware into vboot_reference */
125 
126 /*
127  * Minimum and recommended size of shared_data_blob in bytes.  Shared data blob
128  * is used to communicate data between calls to VbInit(), VbSelectFirmware(),
129  * the OS.  Minimum size is enough to hold all required data for verified boot
130  * but may not be able to hold debug output.
131  */
132 #define VB_SHARED_DATA_MIN_SIZE 3072
133 #define VB_SHARED_DATA_REC_SIZE 16384
134 
135 /*
136  * Data passed by firmware to VbInit(), VbSelectFirmware() and
137  * VbSelectAndLoadKernel().
138  *
139  * Note that in UEFI, these are called by different phases in different
140  * processor modes (VbInit() and VbSelectFirmware() = 32-bit PEI,
141  * VbSelectAndLoadKernel() = 64-bit BDS), so the data may be at a different
142  * location between calls.
143  */
144 typedef struct VbCommonParams {
145 	/* Pointer to GBB data */
146 	void *gbb_data;
147 	/* Size of GBB data in bytes */
148 	uint32_t gbb_size;
149 
150 	/*
151 	 * Shared data blob for data shared between verified boot entry points.
152 	 * This should be at least VB_SHARED_DATA_MIN_SIZE bytes long, and
153 	 * ideally is VB_SHARED_DATA_REC_SIZE bytes long.
154 	 */
155 	/* Pointer to shared data blob buffer */
156 	void *shared_data_blob;
157 	/*
158 	 * On input, set to size of shared data blob buffer, in bytes.  On
159 	 * output, this will contain the actual data size placed into the
160 	 * buffer.
161 	 */
162 	uint32_t shared_data_size;
163 
164 	/*
165 	 * Internal context/data for verified boot, to maintain state during
166 	 * calls to other API functions such as VbExHashFirmwareBody().
167 	 * Allocated and freed inside the entry point; firmware should not look
168 	 * at this.
169 	 */
170 	void *vboot_context;
171 
172 	/*
173 	 * Internal context/data for firmware / VbExHashFirmwareBody().  Needed
174 	 * because the PEI phase of UEFI boot runs out of ROM and thus can't
175 	 * modify global variables; everything needs to get passed around on
176 	 * the stack.
177 	 */
178 	void *caller_context;
179 
180 	/* For internal use of Vboot - do not examine or modify! */
181 	struct GoogleBinaryBlockHeader *gbb;
182 	struct BmpBlockHeader *bmp;
183 } VbCommonParams;
184 
185 /* Flags for VbInitParams.flags */
186 /* Developer switch was on at boot time. */
187 #define VB_INIT_FLAG_DEV_SWITCH_ON       0x00000001
188 /* Recovery button was pressed at boot time. */
189 #define VB_INIT_FLAG_REC_BUTTON_PRESSED  0x00000002
190 /* Hardware write protect was enabled at boot time. */
191 #define VB_INIT_FLAG_WP_ENABLED          0x00000004
192 /* This is a S3 resume, not a normal boot. */
193 #define VB_INIT_FLAG_S3_RESUME           0x00000008
194 /*
195  * Previous boot attempt failed for reasons external to verified boot (RAM
196  * init failure, SSD missing, etc.).
197  *
198  * TODO: add a field to VbInitParams which holds a reason code, and report
199  * that via VbSharedData.
200  */
201 #define VB_INIT_FLAG_PREVIOUS_BOOT_FAIL  0x00000010
202 /*
203  * Calling firmware supports read only firmware for normal/developer boot path.
204  */
205 #define VB_INIT_FLAG_RO_NORMAL_SUPPORT   0x00000020
206 /*
207  * This platform does not have a physical dev-switch, so we must rely on a
208  * virtual switch (kept in the TPM) instead. When this flag is set,
209  * VB_INIT_FLAG_DEV_SWITCH_ON is ignored.
210  */
211 #define VB_INIT_FLAG_VIRTUAL_DEV_SWITCH  0x00000040
212 /* Set when the VGA Option ROM has been loaded already. */
213 #define VB_INIT_FLAG_OPROM_LOADED        0x00000080
214 /* Set if we care about the VGA Option ROM - some platforms don't. */
215 #define VB_INIT_FLAG_OPROM_MATTERS       0x00000100
216 /* EC on this platform supports EC software sync. */
217 #define VB_INIT_FLAG_EC_SOFTWARE_SYNC    0x00000200
218 /* EC on this platform is slow to update. */
219 #define VB_INIT_FLAG_EC_SLOW_UPDATE      0x00000400
220 /*
221  * Software write protect was enabled at boot time. This is separate from the
222  * HW write protect. Both must be set for flash write protection to work.
223  */
224 #define VB_INIT_FLAG_SW_WP_ENABLED       0x00000800
225 /*
226  * This platform does not have a physical recovery switch which, when present,
227  * can (and should) be used for additional physical presence checks.
228  */
229 #define VB_INIT_FLAG_VIRTUAL_REC_SWITCH  0x00001000
230 /* Set when we are calling VbInit() before loading Option ROMs */
231 #define VB_INIT_FLAG_BEFORE_OPROM_LOAD   0x00002000
232 
233 /*
234  * Output flags for VbInitParams.out_flags.  Used to indicate potential boot
235  * paths and configuration to the calling firmware early in the boot process,
236  * so that it can properly configure itself for the capabilities subsequently
237  * required by VbSelectFirmware() and VbSelectAndLoadKernel().
238  */
239 /*
240  * Enable recovery path.  Do not rely on any rewritable data (cached RAM
241  * timings, etc.).  Reliable operation is more important than boot speed.
242  */
243 #define VB_INIT_OUT_ENABLE_RECOVERY      0x00000001
244 /* RAM must be cleared before calling VbSelectFirmware(). */
245 #define VB_INIT_OUT_CLEAR_RAM            0x00000002
246 /*
247  * Load display drivers; VbExDisplay*() functions may be called.  If this flag
248  * is not present, VbExDisplay*() functions will not be called this boot.
249  */
250 #define VB_INIT_OUT_ENABLE_DISPLAY       0x00000004
251 /*
252  * Load USB storage drivers; VbExDisk*() functions may be called with the
253  * VB_DISK_FLAG_REMOVABLE flag.  If this flag is not present, VbExDisk*()
254  * functions will only be called for fixed disks.
255  */
256 #define VB_INIT_OUT_ENABLE_USB_STORAGE   0x00000008
257 /* If this is a S3 resume, do a debug reset boot instead */
258 #define VB_INIT_OUT_S3_DEBUG_BOOT        0x00000010
259 /* BIOS should load any PCI option ROMs it finds, not just internal video */
260 #define VB_INIT_OUT_ENABLE_OPROM         0x00000020
261 /* BIOS may be asked to boot something other than ChromeOS */
262 #define VB_INIT_OUT_ENABLE_ALTERNATE_OS  0x00000040
263 /* Enable developer path. */
264 #define VB_INIT_OUT_ENABLE_DEVELOPER     0x00000080
265 
266 /* Data only used by VbInit() */
267 typedef struct VbInitParams {
268 	/* Inputs to VbInit() */
269 	/* Flags (see VB_INIT_FLAG_*) */
270 	uint32_t flags;
271 
272 	/* Outputs from VbInit(); valid only if it returns success. */
273 	/* Output flags for firmware; see VB_INIT_OUT_*) */
274 	uint32_t out_flags;
275 } VbInitParams;
276 
277 /*
278  * Firmware types for VbHashFirmwareBody() and
279  * VbSelectFirmwareParams.selected_firmware.  Note that we store these in a
280  * uint32_t because enum maps to int, which isn't fixed-size.
281  */
282 enum VbSelectFirmware_t {
283 	/* Recovery mode */
284 	VB_SELECT_FIRMWARE_RECOVERY = 0,
285 	/* Rewritable firmware A/B for normal or developer path */
286 	VB_SELECT_FIRMWARE_A = 1,
287 	VB_SELECT_FIRMWARE_B = 2,
288 	/* Read only firmware for normal or developer path. */
289 	VB_SELECT_FIRMWARE_READONLY = 3,
290         VB_SELECT_FIRMWARE_COUNT,
291 };
292 
293 /* Data only used by VbSelectFirmware() */
294 typedef struct VbSelectFirmwareParams {
295 	/* Inputs to VbSelectFirmware() */
296 	/* Key block + preamble for firmware A */
297 	void *verification_block_A;
298 	/* Key block + preamble for firmware B */
299 	void *verification_block_B;
300 	/* Verification block A size in bytes */
301 	uint32_t verification_size_A;
302 	/* Verification block B size in bytes */
303 	uint32_t verification_size_B;
304 
305 	/* Outputs from VbSelectFirmware(); valid only if it returns success. */
306 	/* Main firmware to run; see VB_SELECT_FIRMWARE_*. */
307 	uint32_t selected_firmware;
308 } VbSelectFirmwareParams;
309 
310 /*
311  * We use disk handles rather than indices.  Using indices causes problems if
312  * a disk is removed/inserted in the middle of processing.
313  */
314 typedef void *VbExDiskHandle_t;
315 
316 /* Data used only by VbSelectAndLoadKernel() */
317 typedef struct VbSelectAndLoadKernelParams {
318 	/* Inputs to VbSelectAndLoadKernel() */
319 	/* Destination buffer for kernel (normally at 0x100000 on x86) */
320 	void *kernel_buffer;
321 	/* Size of kernel buffer in bytes */
322 	uint32_t kernel_buffer_size;
323 
324 	/*
325 	 * Outputs from VbSelectAndLoadKernel(); valid only if it returns
326 	 * success.
327 	 */
328 	/* Handle of disk containing loaded kernel */
329 	VbExDiskHandle_t disk_handle;
330 	/* Partition number on disk to boot (1...M) */
331 	uint32_t partition_number;
332 	/* Address of bootloader image in RAM */
333 	uint64_t bootloader_address;
334 	/* Size of bootloader image in bytes */
335 	uint32_t bootloader_size;
336 	/* UniquePartitionGuid for boot partition */
337 	uint8_t partition_guid[16];
338 	/* Flags passed in by signer */
339 	uint32_t flags;
340 	/*
341 	 * TODO: in H2C, all that pretty much just gets passed to the
342 	 * bootloader as KernelBootloaderOptions, though the disk handle is
343 	 * passed as an index instead of a handle.  Is that used anymore now
344 	 * that we're passing partition_guid?
345 	 */
346 } VbSelectAndLoadKernelParams;
347 
348 /**
349  * Initialize the verified boot library.
350  *
351  * Returns VBERROR_SUCCESS if success, non-zero if error; on error,
352  * caller should reboot.
353  */
354 VbError_t VbInit(VbCommonParams *cparams, VbInitParams *iparams);
355 
356 /**
357  * Select the main firmware.
358  *
359  * Returns VBERROR_SUCCESS if success, non-zero if error; on error,
360  * caller should reboot.
361  *
362  * NOTE: This is now called in all modes, including recovery.  Previously,
363  * LoadFirmware() was not called in recovery mode, which meant that
364  * LoadKernel() needed to duplicate the TPM and VbSharedData initialization
365  * code.
366  */
367 VbError_t VbSelectFirmware(VbCommonParams *cparams,
368                            VbSelectFirmwareParams *fparams);
369 
370 /**
371  * Update the data hash for the current firmware image, extending it by [size]
372  * bytes stored in [*data].  This function must only be called inside
373  * VbExHashFirmwareBody(), which is in turn called by VbSelectFirmware().
374  */
375 void VbUpdateFirmwareBodyHash(VbCommonParams *cparams,
376                               uint8_t *data, uint32_t size);
377 
378 /**
379  * Select and loads the kernel.
380  *
381  * Returns VBERROR_SUCCESS if success, non-zero if error; on error, caller
382  * should reboot. */
383 VbError_t VbSelectAndLoadKernel(VbCommonParams *cparams,
384                                 VbSelectAndLoadKernelParams *kparams);
385 
386 /*****************************************************************************/
387 /* Debug output (from utility.h) */
388 
389 /**
390  * Output an error message and quit.  Does not return.  Supports
391  * printf()-style formatting.
392  */
393 void VbExError(const char *format, ...);
394 
395 /**
396  * Output a debug message.  Supports printf()-style formatting.
397  */
398 void VbExDebug(const char *format, ...)
399 	__attribute__ ((format (__printf__, 1, 2)));
400 
401 /*****************************************************************************/
402 /* Memory (from utility.h) */
403 
404 /**
405  * Allocate [size] bytes and return a pointer to the allocated memory. Abort
406  * on error; this always either returns a good pointer or never returns.
407  *
408  * If any of the firmware API implementations require aligned data (for
409  * example, disk access on ARM), all pointers returned by VbExMalloc() must
410  * also be aligned.
411  */
412 void *VbExMalloc(size_t size);
413 
414 /**
415  * Free memory pointed to by [ptr] previously allocated by VbExMalloc().
416  */
417 void VbExFree(void *ptr);
418 
419 /*****************************************************************************/
420 /* Timer and delay (first two from utility.h) */
421 
422 /**
423  * Read a high-resolution timer.  Returns the current timer value in arbitrary
424  * units.
425  *
426  * This is intended for benchmarking, so this call MUST be fast.  The timer
427  * frequency must be >1 KHz (preferably >1 MHz), and the timer must not wrap
428  * around for at least 10 minutes.  It is preferable (but not required) that
429  * the timer be initialized to 0 at boot.
430  *
431  * It is assumed that the firmware has some other way of communicating the
432  * timer frequency to the OS.  For example, on x86 we use TSC, and the OS
433  * kernel reports the initial TSC value at kernel-start and calculates the
434  * frequency. */
435 uint64_t VbExGetTimer(void);
436 
437 /**
438  * Delay for at least the specified number of milliseconds.  Should be accurate
439  * to within 10% (a requested delay of 1000 ms should result in an actual delay
440  * of between 1000 - 1100 ms).
441  */
442 void VbExSleepMs(uint32_t msec);
443 
444 /**
445  * Play a beep tone of the specified frequency in Hz and duration in msec.
446  * This is effectively a VbSleep() variant that makes noise.
447  *
448  * If the audio codec can run in the background, then:
449  *   zero frequency means OFF, non-zero frequency means ON
450  *   zero msec means return immediately, non-zero msec means delay (and
451  *     then OFF if needed)
452  * otherwise,
453  *   non-zero msec and non-zero frequency means ON, delay, OFF, return
454  *   zero msec or zero frequency means do nothing and return immediately
455  *
456  * The return value is used by the caller to determine the capabilities. The
457  * implementation should always do the best it can if it cannot fully support
458  * all features - for example, beeping at a fixed frequency if frequency
459  * support is not available.  At a minimum, it must delay for the specified
460  * non-zero duration.
461  */
462 VbError_t VbExBeep(uint32_t msec, uint32_t frequency);
463 
464 /*****************************************************************************/
465 /* TPM (from tlcl_stub.h) */
466 
467 /**
468  * Initialize the stub library. */
469 VbError_t VbExTpmInit(void);
470 
471 /**
472  * Close and open the device.  This is needed for running more complex commands
473  * at user level, such as TPM_TakeOwnership, since the TPM device can be opened
474  * only by one process at a time.
475  */
476 VbError_t VbExTpmClose(void);
477 VbError_t VbExTpmOpen(void);
478 
479 /**
480  * Send a request_length-byte request to the TPM and receive a response.  On
481  * input, response_length is the size of the response buffer in bytes.  On
482  * exit, response_length is set to the actual received response length in
483  * bytes. */
484 VbError_t VbExTpmSendReceive(const uint8_t *request, uint32_t request_length,
485                              uint8_t *response, uint32_t *response_length);
486 
487 /*****************************************************************************/
488 /* Non-volatile storage */
489 
490 #define VBNV_BLOCK_SIZE 16  /* Size of NV storage block in bytes */
491 
492 /**
493  * Read the VBNV_BLOCK_SIZE-byte non-volatile storage into buf.
494  */
495 VbError_t VbExNvStorageRead(uint8_t *buf);
496 
497 /**
498  * Write the VBNV_BLOCK_SIZE-byte non-volatile storage from buf.
499  */
500 VbError_t VbExNvStorageWrite(const uint8_t *buf);
501 
502 /*****************************************************************************/
503 /* Firmware / EEPROM access (previously in load_firmware_fw.h) */
504 
505 /**
506  * Calculate the hash of the firmware body data for [firmware_index], which is
507  * either VB_SELECT_FIRMWARE_A or VB_SELECT_FIRMWARE B.
508  *
509  * This function must call VbUpdateFirmwareBodyHash() before returning, to
510  * update the secure hash for the firmware image.  For best performance, the
511  * implementation should call VbUpdateFirmwareBodyHash() periodically during
512  * the read, so that updating the hash can be pipelined with the read.  If the
513  * reader cannot update the hash during the read process, it should call
514  * VbUpdateFirmwareBodyHash() on the entire firmware data after the read,
515  * before returning.
516  *
517  * It is recommended that the firmware use this call to copy the requested
518  * firmware body from EEPROM into RAM, so that it doesn't need to do a second
519  * slow copy from EEPROM to RAM if this firmware body is selected.
520  *
521  * Note this function doesn't actually pass the firmware body data to verified
522  * boot, because verified boot doesn't actually need the firmware body, just
523  * its hash.  This is important on x86, where the firmware is stored
524  * compressed.  We hash the compressed data, but the BIOS decompresses it
525  * during read.  Simply updating a hash is compatible with the x86
526  * read-and-decompress pipeline.
527  */
528 VbError_t VbExHashFirmwareBody(VbCommonParams *cparams,
529                                uint32_t firmware_index);
530 
531 /*****************************************************************************/
532 /* Disk access (previously in boot_device.h) */
533 
534 /* Flags for VbDisk APIs */
535 /* Disk is removable.  Example removable disks: SD cards, USB keys.  */
536 #define VB_DISK_FLAG_REMOVABLE 0x00000001
537 /*
538  * Disk is fixed.  If this flag is present, disk is internal to the system and
539  * not removable.  Example fixed disks: internal SATA SSD, eMMC.
540  */
541 #define VB_DISK_FLAG_FIXED     0x00000002
542 /*
543  * Note that VB_DISK_FLAG_REMOVABLE and VB_DISK_FLAG_FIXED are
544  * mutually-exclusive for a single disk.  VbExDiskGetInfo() may specify both
545  * flags to request disks of both types in a single call.
546  *
547  * At some point we could specify additional flags, but we don't currently
548  * have a way to make use of these:
549  *
550  * USB              Device is known to be attached to USB.  Note that the SD
551  *                  card reader inside x86 systems is attached to USB so this
552  *                  isn't super useful.
553  * SD               Device is known to be a SD card.  Note that external card
554  *                  readers might not return this information, so also of
555  *                  questionable use.
556  * READ_ONLY        Device is known to be read-only.  Could be used by recovery
557  *                  when processing read-only recovery image.
558  */
559 
560 /*
561  * Disks are used in two ways:
562  * - As a random-access device to read and write the GPT
563  * - As a streaming device to read the kernel
564  * These are implemented differently on raw NAND vs eMMC/SATA/USB
565  * - On eMMC/SATA/USB, both of these refer to the same underlying
566  *   storage, so they have the same size and LBA size. In this case,
567  *   the GPT should not point to the same address as itself.
568  * - On raw NAND, the GPT is held on a portion of the SPI flash.
569  *   Random access GPT operations refer to the SPI and streaming
570  *   operations refer to NAND. The GPT may therefore point into
571  *   the same offsets as itself.
572  * These types are distinguished by the following flag and VbDiskInfo
573  * has separate fields to describe the random-access ("GPT") and
574  * streaming aspects of the disk. If a disk is random-access (i.e.
575  * not raw NAND) then these fields are equal.
576  */
577 #define VB_DISK_FLAG_EXTERNAL_GPT	0x00000004
578 
579 /* Information on a single disk */
580 typedef struct VbDiskInfo {
581 	/* Disk handle */
582 	VbExDiskHandle_t handle;
583 	/* Size of a random-access LBA sector in bytes */
584 	uint64_t bytes_per_lba;
585 	/* Number of random-access LBA sectors on the device.
586 	 * If streaming_lba_count is 0, this stands in for the size of the
587 	 * randomly accessed portion as well as the streaming portion.
588 	 * Otherwise, this is only the randomly-accessed portion. */
589 	uint64_t lba_count;
590 	/* Number of streaming sectors on the device */
591 	uint64_t streaming_lba_count;
592 	/* Flags (see VB_DISK_FLAG_* constants) */
593 	uint32_t flags;
594 	/*
595 	 * Optional name string, for use in debugging.  May be empty or null if
596 	 * not available.
597 	 */
598 	const char *name;
599 } VbDiskInfo;
600 
601 /**
602  * Store information into [info] for all disks (storage devices) attached to
603  * the system which match all of the disk_flags.
604  *
605  * On output, count indicates how many disks are present, and [infos_ptr]
606  * points to a [count]-sized array of VbDiskInfo structs with the information
607  * on those disks; this pointer must be freed by calling VbExDiskFreeInfo().
608  * If count=0, infos_ptr may point to NULL.  If [infos_ptr] points to NULL
609  * because count=0 or error, it is not necessary to call VbExDiskFreeInfo().
610  *
611  * A multi-function device (such as a 4-in-1 card reader) should provide
612  * multiple disk handles.
613  *
614  * The firmware must not alter or free the list pointed to by [infos_ptr] until
615  * VbExDiskFreeInfo() is called.
616  */
617 VbError_t VbExDiskGetInfo(VbDiskInfo **infos_ptr, uint32_t *count,
618                           uint32_t disk_flags);
619 
620 /**
621  * Free a disk information list [infos] previously returned by
622  * VbExDiskGetInfo().  If [preserve_handle] != NULL, the firmware must ensure
623  * that handle remains valid after this call; all other handles from the info
624  * list need not remain valid after this call.
625  */
626 VbError_t VbExDiskFreeInfo(VbDiskInfo *infos,
627                            VbExDiskHandle_t preserve_handle);
628 
629 /**
630  * Read lba_count LBA sectors, starting at sector lba_start, from the disk,
631  * into the buffer.
632  *
633  * This is used for random access to the GPT. It is not for the partition
634  * contents. The upper limit is lba_count.
635  *
636  * If the disk handle is invalid (for example, the handle refers to a disk
637  * which as been removed), the function must return error but must not
638  * crash.
639  */
640 VbError_t VbExDiskRead(VbExDiskHandle_t handle, uint64_t lba_start,
641                        uint64_t lba_count, void *buffer);
642 
643 /**
644  * Write lba_count LBA sectors, starting at sector lba_start, to the disk, from
645  * the buffer.
646  *
647  * This is used for random access to the GPT. It does not (necessarily) access
648  * the streaming portion of the device.
649  *
650  * If the disk handle is invalid (for example, the handle refers to a disk
651  * which as been removed), the function must return error but must not
652  * crash.
653  */
654 VbError_t VbExDiskWrite(VbExDiskHandle_t handle, uint64_t lba_start,
655                         uint64_t lba_count, const void *buffer);
656 
657 /* Streaming read interface */
658 typedef void *VbExStream_t;
659 
660 /**
661  * Open a stream on a disk
662  *
663  * @param handle	Disk to open the stream against
664  * @param lba_start	Starting sector offset within the disk to stream from
665  * @param lba_count	Maximum extent of the stream in sectors
666  * @param stream	out-paramter for the generated stream
667  *
668  * @return Error code, or VBERROR_SUCCESS.
669  *
670  * This is used for access to the contents of the actual partitions on the
671  * device. It is not used to access the GPT. The size of the content addressed
672  * is within streaming_lba_count.
673  */
674 VbError_t VbExStreamOpen(VbExDiskHandle_t handle, uint64_t lba_start,
675 			 uint64_t lba_count, VbExStream_t *stream_ptr);
676 
677 /**
678  * Read from a stream on a disk
679  *
680  * @param stream	Stream to read from
681  * @param bytes		Number of bytes to read
682  * @param buffer	Destination to read into
683  *
684  * @return Error code, or VBERROR_SUCCESS. Failure to read as much data as
685  * requested is an error.
686  *
687  * This is used for access to the contents of the actual partitions on the
688  * device. It is not used to access the GPT.
689  */
690 VbError_t VbExStreamRead(VbExStream_t stream, uint32_t bytes, void *buffer);
691 
692 /**
693  * Close a stream
694  *
695  * @param stream	Stream to close
696  */
697 void VbExStreamClose(VbExStream_t stream);
698 
699 
700 /*****************************************************************************/
701 /* Display */
702 
703 /* Predefined (default) screens for VbExDisplayScreen(). */
704 enum VbScreenType_t {
705 	/* Blank (clear) screen */
706 	VB_SCREEN_BLANK = 0,
707 	/* Developer - warning */
708 	VB_SCREEN_DEVELOPER_WARNING = 0x101,
709 	/* Developer - easter egg */
710 	VB_SCREEN_DEVELOPER_EGG     = 0x102,
711 	/* Recovery - remove inserted devices */
712 	VB_SCREEN_RECOVERY_REMOVE   = 0x201,
713 	/* Recovery - insert recovery image */
714 	VB_SCREEN_RECOVERY_INSERT   = 0x202,
715 	/* Recovery - inserted image invalid */
716 	VB_SCREEN_RECOVERY_NO_GOOD  = 0x203,
717 	/* Recovery - confirm dev mode */
718 	VB_SCREEN_RECOVERY_TO_DEV   = 0x204,
719 	/* Developer - confirm normal mode */
720 	VB_SCREEN_DEVELOPER_TO_NORM = 0x205,
721 	/* Please wait - programming EC */
722 	VB_SCREEN_WAIT              = 0x206,
723 	/* Confirm after DEVELOPER_TO_NORM */
724 	VB_SCREEN_TO_NORM_CONFIRMED = 0x207,
725 };
726 
727 /**
728  * Initialize and clear the display.  Set width and height to the screen
729  * dimensions in pixels.
730  */
731 VbError_t VbExDisplayInit(uint32_t *width, uint32_t *height);
732 
733 /**
734  * Enable (enable!=0) or disable (enable=0) the display backlight.
735  */
736 VbError_t VbExDisplayBacklight(uint8_t enable);
737 
738 /**
739  * Sets the logical dimension to display.
740  *
741  * If the physical display is larger or smaller than given dimension, display
742  * provider may decide to scale or shift images (from VbExDisplayImage)to proper
743  * location.
744  */
745 VbError_t VbExDisplaySetDimension(uint32_t width, uint32_t height);
746 
747 /**
748  * Display a predefined screen; see VB_SCREEN_* for valid screens.
749  *
750  * This is a backup method of screen display, intended for use if the GBB does
751  * not contain a full set of bitmaps.  It is acceptable for the backup screen
752  * to be simple ASCII text such as "NO GOOD" or "INSERT"; these screens should
753  * only be seen during development.
754  */
755 VbError_t VbExDisplayScreen(uint32_t screen_type);
756 
757 /**
758  * Write an image to the display, with the upper left corner at the specified
759  * pixel coordinates.  The bitmap buffer is a pointer to the platform-dependent
760  * uncompressed binary blob with dimensions and format specified internally
761  * (for example, a raw BMP, GIF, PNG, whatever). We pass the size just for
762  * convenience.
763  */
764 VbError_t VbExDisplayImage(uint32_t x, uint32_t y,
765                            void *buffer, uint32_t buffersize);
766 
767 /**
768  * Display a string containing debug information on the screen, rendered in a
769  * platform-dependent font.  Should be able to handle newlines '\n' in the
770  * string.  Firmware must support displaying at least 20 lines of text, where
771  * each line may be at least 80 characters long.  If the firmware has its own
772  * debug state, it may display it to the screen below this information.
773  *
774  * NOTE: This is what we currently display when TAB is pressed.  Some
775  * information (HWID, recovery reason) is ours; some (CMOS breadcrumbs) is
776  * platform-specific.  If we decide to soft-render the HWID string
777  * (chrome-os-partner:3693), we'll need to maintain our own fonts, so we'll
778  * likely display it via VbExDisplayImage() above.
779  */
780 VbError_t VbExDisplayDebugInfo(const char *info_str);
781 
782 /*****************************************************************************/
783 /* Keyboard and switches */
784 
785 /* Key codes for required non-printable-ASCII characters. */
786 enum VbKeyCode_t {
787 	VB_KEY_UP = 0x100,
788 	VB_KEY_DOWN = 0x101,
789 	VB_KEY_LEFT = 0x102,
790 	VB_KEY_RIGHT = 0x103,
791 	VB_KEY_CTRL_ENTER = 0x104,
792 };
793 
794 /* Flags for additional information.
795  * TODO(semenzato): consider adding flags for modifiers instead of
796  * making up some of the key codes above.
797  */
798 enum VbKeyFlags_t {
799 	VB_KEY_FLAG_TRUSTED_KEYBOARD = 1 << 0,
800 };
801 
802 /**
803  * Read the next keypress from the keyboard buffer.
804  *
805  * Returns the keypress, or zero if no keypress is pending or error.
806  *
807  * The following keys must be returned as ASCII character codes:
808  *    0x08          Backspace
809  *    0x09          Tab
810  *    0x0D          Enter (carriage return)
811  *    0x01 - 0x1A   Ctrl+A - Ctrl+Z (yes, those alias with backspace/tab/enter)
812  *    0x1B          Esc
813  *    0x20          Space
814  *    0x30 - 0x39   '0' - '9'
815  *    0x60 - 0x7A   'a' - 'z'
816  *
817  * Some extended keys must also be supported; see the VB_KEY_* defines above.
818  *
819  * Keys ('/') or key-chords (Fn+Q) not defined above may be handled in any of
820  * the following ways:
821  *    1. Filter (don't report anything if one of these keys is pressed).
822  *    2. Report as ASCII (if a well-defined ASCII value exists for the key).
823  *    3. Report as any other value in the range 0x200 - 0x2FF.
824  * It is not permitted to report a key as a multi-byte code (for example,
825  * sending an arrow key as the sequence of keys '\x1b', '[', '1', 'A'). */
826 uint32_t VbExKeyboardRead(void);
827 
828 /**
829  * Same as VbExKeyboardRead(), but return extra information.
830  */
831 uint32_t VbExKeyboardReadWithFlags(uint32_t *flags_ptr);
832 
833 /**
834  * Return the current state of the switches specified in request_mask
835  */
836 uint32_t VbExGetSwitches(uint32_t request_mask);
837 
838 /*****************************************************************************/
839 /* Embedded controller (EC) */
840 
841 /*
842  * All these functions take a devidx parameter, which indicates which embedded
843  * processor the call applies to.  At present, only devidx=0 is valid, but
844  * upcoming CLs will add support for multiple devices.
845  */
846 
847 /**
848  * This is called only if the system implements a keyboard-based (virtual)
849  * developer switch. It must return true only if the system has an embedded
850  * controller which is provably running in its RO firmware at the time the
851  * function is called.
852  */
853 int VbExTrustEC(int devidx);
854 
855 /**
856  * Check if the EC is currently running rewritable code.
857  *
858  * If the EC is in RO code, sets *in_rw=0.
859  * If the EC is in RW code, sets *in_rw non-zero.
860  * If the current EC image is unknown, returns error. */
861 VbError_t VbExEcRunningRW(int devidx, int *in_rw);
862 
863 /**
864  * Request the EC jump to its rewritable code.  If successful, returns when the
865  * EC has booting its RW code far enough to respond to subsequent commands.
866  * Does nothing if the EC is already in its rewritable code.
867  */
868 VbError_t VbExEcJumpToRW(int devidx);
869 
870 /**
871  * Tell the EC to refuse another jump until it reboots. Subsequent calls to
872  * VbExEcJumpToRW() in this boot will fail.
873  */
874 VbError_t VbExEcDisableJump(int devidx);
875 
876 /**
877  * Read the SHA-256 hash of the rewriteable EC image.
878  */
879 VbError_t VbExEcHashRW(int devidx, const uint8_t **hash, int *hash_size);
880 
881 /**
882  * Get the expected contents of the EC image associated with the main firmware
883  * specified by the "select" argument.
884  */
885 VbError_t VbExEcGetExpectedRW(int devidx, enum VbSelectFirmware_t select,
886                               const uint8_t **image, int *image_size);
887 
888 /**
889  * Read the SHA-256 hash of the expected contents of the EC image associated
890  * with the main firmware specified by the "select" argument.
891  */
892 VbError_t VbExEcGetExpectedRWHash(int devidx, enum VbSelectFirmware_t select,
893 		       const uint8_t **hash, int *hash_size);
894 
895 /**
896  * Update the EC rewritable image.
897  */
898 VbError_t VbExEcUpdateRW(int devidx, const uint8_t *image, int image_size);
899 
900 /**
901  * Lock the EC code to prevent updates until the EC is rebooted.
902  * Subsequent calls to VbExEcUpdateRW() this boot will fail.
903  */
904 VbError_t VbExEcProtectRW(int devidx);
905 
906 /**
907  * Info the EC of the boot mode selected by the AP.
908  * mode: Normal, Developer, or Recovery
909  */
910 enum VbEcBootMode_t {VB_EC_NORMAL, VB_EC_DEVELOPER, VB_EC_RECOVERY };
911 VbError_t VbExEcEnteringMode(int devidx, enum VbEcBootMode_t mode);
912 
913 /*****************************************************************************/
914 /* Misc */
915 
916 /* Args to VbExProtectFlash() */
917 enum VbProtectFlash_t { VBPROTECT_RW_A, VBPROTECT_RW_B, VBPROTECT_RW_DEVKEY };
918 
919 /**
920  * Lock a section of the BIOS flash address space to prevent updates until the
921  * host is rebooted. Subsequent attempts to erase or modify the specified BIOS
922  * image will fail. If this function is called more than once each call should
923  * be cumulative.
924  */
925 VbError_t VbExProtectFlash(enum VbProtectFlash_t region);
926 
927 /**
928  * Check if the firmware needs to shut down the system.
929  *
930  * Returns a non-zero VB_SHUTDOWN_REQUEST mask indicating the reason(s) for
931  * shutdown if a shutdown is being requested (see VB_SHUTDOWN_REQUEST_*), or 0
932  * if a shutdown is not being requested.
933  *
934  * NOTE: When we're displaying a screen, pressing the power button should shut
935  * down the computer.  We need a way to break out of our control loop so this
936  * can occur cleanly.
937  */
938 uint32_t VbExIsShutdownRequested(void);
939 
940 /*
941  * Shutdown requested for a reason which is not defined among other
942  * VB_SHUTDOWN_REQUEST_* values. This must be defined as 1 for backward
943  * compatibility with old versions of the API.
944  */
945 #define VB_SHUTDOWN_REQUEST_OTHER		0x00000001
946 /* Shutdown requested due to a lid switch being closed. */
947 #define VB_SHUTDOWN_REQUEST_LID_CLOSED		0x00000002
948 /* Shutdown requested due to a power button being pressed. */
949 #define VB_SHUTDOWN_REQUEST_POWER_BUTTON	0x00000004
950 
951 /**
952  * Expose the BIOS' built-in decompression routine to the vboot wrapper. The
953  * caller must know how large the uncompressed data will be and must manage
954  * that memory. The decompression routine just puts the uncompressed data into
955  * the specified buffer. We pass in the size of the outbuf, and get back the
956  * actual size used.
957  */
958 VbError_t VbExDecompress(void *inbuf, uint32_t in_size,
959                          uint32_t compression_type,
960                          void *outbuf, uint32_t *out_size);
961 
962 /* Constants for compression_type */
963 enum {
964 	COMPRESS_NONE = 0,
965 	COMPRESS_EFIv1,           /* The x86 BIOS only supports this */
966 	COMPRESS_LZMA1,           /* The ARM BIOS supports LZMA1 */
967 	MAX_COMPRESS,
968 };
969 
970 /**
971  * Execute legacy boot option.
972  */
973 int VbExLegacy(void);
974 
975 /* Regions for VbExRegionRead() */
976 enum vb_firmware_region {
977 	VB_REGION_GBB,	/* Google Binary Block - see gbbheader.h */
978 
979 	VB_REGION_COUNT,
980 };
981 
982 /**
983  * Read data from a region of the firmware image
984  *
985  * Vboot wants access to a region, to read data from it. This function
986  * reads it (typically from the firmware image such as SPI flash) and
987  * returns the data.
988  *
989  * cparams is passed so that the boot loader has some context for the
990  * operation.
991  *
992  * @param cparams	Common parameters, e.g. use member caller_context
993  *			to point to useful context data
994  * @param region	Firmware region to read
995  * @param offset	Start offset within region
996  * @param size		Number of bytes to read
997  * @param buf		Place to put data
998  * @return VBERROR_... error, VBERROR_SUCCESS on success,
999  */
1000 VbError_t VbExRegionRead(VbCommonParams *cparams,
1001 			 enum vb_firmware_region region, uint32_t offset,
1002 			 uint32_t size, void *buf);
1003 
1004 #endif  /* VBOOT_REFERENCE_VBOOT_API_H_ */
1005