xref: /aosp_15_r20/external/vboot_reference/firmware/2lib/include/2api.h (revision 8617a60d3594060b7ecbd21bc622a7c14f3cf2bc)
1 /* Copyright 2013 The ChromiumOS Authors
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  *
5  * APIs between calling firmware and vboot_reference
6  *
7  * General notes:
8  *
9  * TODO: split this file into a vboot_entry_points.h file which contains the
10  * entry points for the firmware to call vboot_reference, and a
11  * vboot_firmware_exports.h which contains the APIs to be implemented by the
12  * calling firmware and exported to vboot_reference.
13  *
14  * Notes:
15  *    * Assumes this code is never called in the S3 resume path.  TPM resume
16  *      must be done elsewhere, and VB2_NV_DEBUG_RESET_MODE is ignored.
17  */
18 
19 #ifndef VBOOT_REFERENCE_2API_H_
20 #define VBOOT_REFERENCE_2API_H_
21 
22 #include "2constants.h"
23 #include "2context.h"
24 #include "2crypto.h"
25 #include "2fw_hash_tags.h"
26 #include "2gbb_flags.h"
27 #include "2hmac.h"
28 #include "2id.h"
29 #include "2info.h"
30 #include "2recovery_reasons.h"
31 #include "2return_codes.h"
32 #include "2rsa.h"
33 #include "2secdata_struct.h"
34 
35 #define _VB2_TRY_IMPL(expr, ctx, recovery_reason, ...) do { \
36 	vb2_error_t _vb2_try_rv = (expr); \
37 	struct vb2_context *_vb2_try_ctx = (ctx); \
38 	uint8_t _vb2_try_reason = (recovery_reason); \
39 	if (_vb2_try_rv != VB2_SUCCESS) { \
40 		vb2ex_printf(__func__, \
41 			     "%s returned %#x\n", #expr, _vb2_try_rv); \
42 		if (_vb2_try_rv >= VB2_REQUEST_END && \
43 		    (_vb2_try_ctx) && \
44 		    (_vb2_try_reason) != VB2_RECOVERY_NOT_REQUESTED) \
45 			vb2api_fail(_vb2_try_ctx, _vb2_try_reason, \
46 				    _vb2_try_rv); \
47 		return _vb2_try_rv; \
48 	} \
49 } while (0)
50 
51 /*
52  * Evaluate an expression and return *from the caller* on failure or if an
53  * action (such as reboot) is requested.
54  *
55  * This macro supports two forms of usage:
56  * 1. VB2_TRY(expr)
57  * 2. VB2_TRY(expr, ctx, recovery_reason)
58  *
59  * When the second form is used, vb2api_fail() will be called on failure before
60  * return. Note that nvdata only holds one byte for recovery subcode, so any
61  * other more significant bytes will be truncated.
62  *
63  * @param expr			An expression (such as a function call) of type
64  *				vb2_error_t.
65  * @param ctx			Vboot context.
66  * @param recovery_reason	Recovery reason passed to vb2api_fail().
67  */
68 #define VB2_TRY(expr, ...) _VB2_TRY_IMPL(expr, ##__VA_ARGS__, NULL, 0)
69 
70 /**
71  * Check if the return value is an error.
72  *
73  * @param rv	The return value.
74  * @return True if the value is an error.
75  */
vb2_is_error(vb2_error_t rv)76 static inline int vb2_is_error(vb2_error_t rv)
77 {
78 	return rv >= VB2_ERROR_BASE && rv <= VB2_ERROR_MAX;
79 }
80 
81 /* Resource index for vb2ex_read_resource() */
82 enum vb2_resource_index {
83 
84 	/* Google binary block */
85 	VB2_RES_GBB,
86 
87 	/*
88 	 * Firmware verified boot block (keyblock+preamble).  Use
89 	 * VB2_CONTEXT_FW_SLOT_B to determine whether this refers to slot A or
90 	 * slot B; vboot will set that flag to the proper state before reading
91 	 * the vblock.
92 	 */
93 	VB2_RES_FW_VBLOCK,
94 
95 	/*
96 	 * Kernel verified boot block (keyblock+preamble) for the current
97 	 * kernel partition.  Used only by vb2api_kernel_load_vblock().
98 	 * Contents are allowed to change between calls to that function (to
99 	 * allow multiple kernels to be examined).
100 	 */
101 	VB2_RES_KERNEL_VBLOCK,
102 };
103 
104 /* Digest ID for vbapi_get_pcr_digest() */
105 enum vb2_pcr_digest {
106 	/* Digest based on current developer and recovery mode flags */
107 	BOOT_MODE_PCR,
108 
109 	/* SHA-256 hash digest of HWID, from GBB */
110 	HWID_DIGEST_PCR,
111 
112 	/* The firmware version values. */
113 	FIRMWARE_VERSION_PCR,
114 
115 	/* The kernel version values. */
116 	KERNEL_VERSION_PCR,
117 };
118 
119 /******************************************************************************
120  * APIs provided by verified boot.
121  *
122  * At a high level, call functions in the order described below.  After each
123  * call, examine vb2_context.flags to determine whether nvdata or secdata
124  * needs to be written.
125  *
126  * If you need to cause the boot process to fail at any point, call
127  * vb2api_fail().  Then check vb2_context.flags to see what data needs to be
128  * written.  Then reboot.
129  *
130  *	Load nvdata from wherever you keep it.
131  *
132  *	Load secdata_firmware from wherever you keep it.
133  *
134  *      	If it wasn't there at all (for example, this is the first boot
135  *		of a new system in the factory), call
136  *		vb2api_secdata_firmware_create() to initialize the data.
137  *
138  *		If access to your storage is unreliable (reads/writes may
139  *		contain corrupt data), you may call
140  *		vb2api_secdata_firmware_check() to determine if the data was
141  *		valid, and retry reading if it wasn't.  (In that case, you
142  *		should also read back and check the data after any time you
143  *		write it, to make sure it was written correctly.)
144  *
145  *	Call vb2api_fw_phase1().  At present, this nominally decides whether
146  *	recovery mode is needed this boot.
147  *
148  *	Call vb2api_fw_phase2().  At present, this nominally decides which
149  *	firmware slot will be attempted (A or B).
150  *
151  *	Call vb2api_fw_phase3().  At present, this nominally verifies the
152  *	firmware keyblock and preamble.
153  *
154  *	Lock down wherever you keep secdata_firmware.  It should no longer be
155  *	writable this boot.
156  *
157  *	Verify the hash of each section of code/data you need to boot the RW
158  *	firmware.  For each section:
159  *
160  *	1) Normal verification:
161  *
162  *		Call vb2api_init_hash() to see if the hash exists.
163  *
164  *		Load the data for the section.  Call vb2api_extend_hash() on the
165  *		data as you load it.  You can load it all at once and make one
166  *		call, or load and hash-extend a block at a time.
167  *
168  *		Call vb2api_check_hash() to see if the hash is valid.
169  *
170  *			If it is valid, you may use the data and/or execute
171  *			code from that section.
172  *
173  *			If the hash was invalid, you must reboot.
174  *
175  *	2) Verification with CBFS integration:
176  *
177  *		Call vb2api_get_metadata_hash() to get hash of CBFS metadata.
178  *
179  *		Initialize CBFS using stored hash as correct metadata hash.
180  *
181  *			If CBFS initialization fails because of metadata hash
182  *			mismatch, you must reboot.
183  *
184  *			If CBFS initialization succeeds, you may use the data
185  *			and/or execute code from that section.
186  *			IMPORTANT: Be aware, that to have full section
187  *			verification, the CBFS_VERIFICATION has to be enabled.
188  *			Initialization of CBFS volume only checks hash of files
189  *			metadata, not their contents!
190  *
191  * At this point, firmware verification is done, and vb2_context contains the
192  * kernel key needed to verify the kernel.  That context should be preserved
193  * and passed on to kernel selection.  The kernel selection process may be
194  * done by the same firmware image, or may be done by the RW firmware.  The
195  * recommended order is:
196  *
197  *	Load secdata_kernel from wherever you keep it.
198  *
199  *      	If it wasn't there at all (for example, this is the first boot
200  *		of a new system in the factory), call
201  *		vb2api_secdata_kernel_create() to initialize the data.
202  *
203  *		If access to your storage is unreliable (reads/writes may
204  *		contain corrupt data), you may call
205  *		vb2api_secdata_kernel_check() to determine if the data was
206  *		valid, and retry reading if it wasn't.  (In that case, you
207  *		should also read back and check the data after any time you
208 *		write it, to make sure it was written correctly.)
209  *
210  *	Call vb2api_kernel_phase1().  At present, this decides which key to
211  *	use to verify kernel data - the recovery key from the GBB, or the
212  *	kernel subkey from the firmware verification stage.
213  *
214  *	Call vb2api_kernel_phase2().  Do EC and auxfw software sync, clear
215  *	recovery and commit nvdata if needed.
216  *
217  *	Find a boot device (you're on your own here).
218  *
219  *	Call vb2api_load_kernel_vblock() for each kernel partition on the
220  *	boot device, until one succeeds.
221  *
222  *	When that succeeds, call vb2api_get_kernel_size() to determine where
223  *	the kernel is located in the stream and how big it is.  Load or map
224  *	the kernel.  (Again, you're on your own.  This is the responsibility of
225  *	the caller so that the caller can choose whether to allocate a buffer,
226  *	load the kernel data into a predefined area of RAM, or directly map a
227  *	kernel file into the address space.  Note that technically it doesn't
228  *	matter whether the kernel data is even in the same file or stream as
229  *	the vblock, as long as the caller loads the right data.
230  *
231  *	Call vb2api_verify_kernel_data() on the kernel data.
232  *
233  *	If you ran out of kernels before finding a good one, call vb2api_fail()
234  *	with an appropriate recovery reason.
235  *
236  *	Set the VB2_CONTEXT_ALLOW_KERNEL_ROLL_FORWARD flag if the current
237  *	kernel partition has the successful flag (that is, it's already known
238  *	or assumed to be a functional kernel partition).
239  *
240  *	Call vb2api_kernel_phase3().  This cleans up from kernel verification
241  *	and updates the secure data if needed.
242  *
243  *	Lock down wherever you keep secdata_kernel.  It should no longer be
244  *	writable this boot.
245  */
246 
247 /**
248  * Initialize verified boot data structures.
249  *
250  * Needs to be called once per boot, before using any API functions that
251  * accept a vb2_context object.  Sets up the vboot work buffer, as well as
252  * vb2_shared_data and vb2_context.  A pointer to the context object is
253  * written to ctxptr.  After transitioning between different firmware
254  * applications, or any time the context pointer is lost, vb2api_reinit()
255  * should be used to restore access to the context and data on the workbuf.
256  *
257  * If the workbuf needs to be relocated, call vb2api_relocate() instead
258  * of copying memory manually.
259  *
260  * @param workbuf	Workbuf memory location to initialize
261  * @param size		Size of workbuf being initialized
262  * @param ctxptr	Pointer to a context pointer to be filled in
263  * @return VB2_SUCCESS, or non-zero error code.
264  */
265 vb2_error_t vb2api_init(void *workbuf, uint32_t size,
266 			struct vb2_context **ctxptr);
267 
268 /**
269  * Reinitialize vboot data structures.
270  *
271  * After transitioning between different firmware applications, or any time the
272  * context pointer is lost, this function should be called to restore access to
273  * the workbuf.  A pointer to the context object is written to ctxptr.  Returns
274  * an error if the vboot work buffer is inconsistent.
275  *
276  * If the workbuf needs to be relocated, call vb2api_relocate() instead
277  * of copying memory manually.
278  *
279  * @param workbuf	Workbuf memory location to check
280  * @param ctxptr	Pointer to a context pointer to be filled in
281  * @return VB2_SUCCESS, or non-zero error code.
282  */
283 vb2_error_t vb2api_reinit(void *workbuf, struct vb2_context **ctxptr);
284 
285 /**
286  * Relocate vboot data structures.
287  *
288  * Move the vboot work buffer from one memory location to another, and expand
289  * or contract the workbuf to fit.  The target memory location may be the same
290  * as the original (used for a "resize" operation), and it is safe to call this
291  * function with overlapping memory regions.
292  *
293  * A pointer to the context object is written to ctxptr.  Returns an error if
294  * the vboot work buffer is inconsistent, or if the new memory space is too
295  * small to contain the work buffer.
296  *
297  * @param new_workbuf	Target workbuf memory location
298  * @param cur_workbuf	Original workbuf memory location to relocate
299  * @param size		Target size of relocated workbuf
300  * @param ctxptr	Pointer to a context pointer to be filled in
301  * @return VB2_SUCCESS, or non-zero error code.
302  */
303 vb2_error_t vb2api_relocate(void *new_workbuf, const void *cur_workbuf,
304 			    uint32_t size, struct vb2_context **ctxptr);
305 
306 /**
307  * Export "VBSD" vboot1 data structure.
308  *
309  * Copy relevant fields from vboot2 data structures to VbSharedDataHeader
310  * format.  Takes a pointer to the memory space to be filled in.  Expects
311  * the memory available to be of size VB2_VBSD_SIZE.
312  *
313  * @param ctx		Context pointer
314  * @param dest		Target memory to store VbSharedDataHeader
315  */
316 void vb2api_export_vbsd(struct vb2_context *ctx, void *dest);
317 
318 /**
319  * Check the validity of firmware secure storage context.
320  *
321  * Checks version and CRC.
322  *
323  * @param ctx		Context pointer
324  * @return VB2_SUCCESS, or non-zero error code if error.
325  */
326 vb2_error_t vb2api_secdata_firmware_check(struct vb2_context *ctx);
327 
328 /**
329  * Create fresh data in firmware secure storage context.
330  *
331  * Use this only when initializing the secure storage context on a new machine
332  * the first time it boots.  Do NOT simply use this if
333  * vb2api_secdata_firmware_check() (or any other API in this library) fails;
334  * that could allow the secure data to be rolled back to an insecure state.
335  *
336  * @param ctx		Context pointer
337  * @return size of created firmware secure storage data in bytes
338  */
339 uint32_t vb2api_secdata_firmware_create(struct vb2_context *ctx);
340 
341 /**
342  * Check the validity of kernel secure storage context (ctx->secdata_kernel).
343  *
344  * Checks version, UID, and CRC.
345  *
346  * @param ctx		Context pointer
347  * @param size		(IN) Size of data to be checked
348  * 			(OUT) Expected size of data
349  * @return VB2_SUCCESS, or non-zero error code if error. If data is missing,
350  * 	   it returns VB2_ERROR_SECDATA_KERNEL_INCOMPLETE and informs the caller
351  * 	   of the expected size.
352  */
353 vb2_error_t vb2api_secdata_kernel_check(struct vb2_context *ctx, uint8_t *size);
354 
355 /**
356  * Create fresh data in kernel secure storage context.
357  *
358  * Use this only when initializing the secure storage context on a new machine
359  * the first time it boots.  Do NOT simply use this if
360  * vb2api_secdata_kernel_check() (or any other API in this library) fails; that
361  * could allow the secure data to be rolled back to an insecure state.
362  *
363  * vb2api_secdata_kernel_create always creates secdata kernel using the latest
364  * revision.
365  *
366  * @param ctx		Context pointer
367  * @return size of created kernel secure storage data in bytes
368  */
369 uint32_t vb2api_secdata_kernel_create(struct vb2_context *ctx);
370 uint32_t vb2api_secdata_kernel_create_v0(struct vb2_context *ctx);
371 
372 /**
373  * Create an empty Firmware Management Parameters (FWMP) in secure storage
374  * context.
375  *
376  * @param ctx		Context pointer
377  * @return size of created FWMP secure storage data in bytes
378  */
379 uint32_t vb2api_secdata_fwmp_create(struct vb2_context *ctx);
380 
381 /**
382  * Check the validity of firmware management parameters (FWMP) space.
383  *
384  * Checks size, version, and CRC.  If the struct size is larger than the size
385  * passed in, the size pointer is set to the expected full size of the struct,
386  * and VB2_ERROR_SECDATA_FWMP_INCOMPLETE is returned.  The caller should
387  * re-read the returned number of bytes, and call this function again.
388  *
389  * @param ctx		Context pointer
390  * @param size		Amount of struct which has been read
391  * @return VB2_SUCCESS, or non-zero error code if error.
392  */
393 vb2_error_t vb2api_secdata_fwmp_check(struct vb2_context *ctx, uint8_t *size);
394 
395 /**
396  * Report firmware failure to vboot.
397  *
398  * If the failure occurred after choosing a firmware slot, and the other
399  * firmware slot is not known-bad, try the other firmware slot after reboot.
400  *
401  * If the failure occurred before choosing a firmware slot, or both slots have
402  * failed in successive boots, request recovery.
403  *
404  * This may be called before vb2api_phase1() to indicate errors in the boot
405  * process prior to the start of vboot.  On return, the calling firmware should
406  * check for updates to secdata and/or nvdata, then reboot.
407  *
408  * @param reason	Recovery reason
409  * @param subcode	Recovery subcode
410  */
411 void vb2api_fail(struct vb2_context *ctx, uint8_t reason, uint8_t subcode);
412 
413 /**
414  * Report firmware failure from previous boot to vboot.
415  *
416  * This function can only be called before vb2api_fw_phase1 (nvdata is
417  * initialized). Otherwise an assert is raised. This function is required to be
418  * called in the following environment:
419  * - Context has to be initialized using vb2api_init
420  * - NV data has to be read into context
421  * - Secdata may or may not have been read
422  * - vb2api_fw_phase1 must not have been called.
423  *
424  * If the other slot is not known bad then try the other firmware slot.
425  * If both the slots are known bad, then request recovery.
426  *
427  * @param reason	Recovery reason
428  * @param subcode	Recovery subcode
429  */
430 void vb2api_previous_boot_fail(struct vb2_context *ctx,
431 			       uint8_t reason, uint8_t subcode);
432 
433 /**
434  * Entry point for setting up a context that can only load and verify a kernel.
435  *
436  * The only allowed usage is to call vb2api_init, then this entry point,
437  * then vb2api_load_kernel.
438  *
439  * @param ctx				Vboot context
440  * @param kernel_packed_key_data	Packed public key for kernel
441  *					verification
442  * @param kernel_packed_key_data_size	Size in bytes of kernel_packed_key_data
443  * @return VB2_SUCCESS, or error code on error.
444  */
445 vb2_error_t vb2api_inject_kernel_subkey(struct vb2_context *ctx,
446 					const uint8_t *kernel_packed_key_data,
447 					uint32_t kernel_packed_key_data_size);
448 
449 /**
450  * Firmware selection, phase 1.
451  *
452  * If the returned error is VB2_ERROR_API_PHASE1_RECOVERY, the calling firmware
453  * should jump directly to recovery-mode firmware without rebooting.
454  *
455  * For other errors, the calling firmware should check for updates to secdata
456  * and/or nvdata, then reboot.
457  *
458  * @param ctx		Vboot context
459  * @return VB2_SUCCESS, or error code on error.
460  */
461 vb2_error_t vb2api_fw_phase1(struct vb2_context *ctx);
462 
463 /**
464  * Firmware selection, phase 2.
465  *
466  * On error, the calling firmware should check for updates to secdata and/or
467  * nvdata, then reboot.
468  *
469  * @param ctx		Vboot context
470  * @return VB2_SUCCESS, or error code on error.
471  */
472 vb2_error_t vb2api_fw_phase2(struct vb2_context *ctx);
473 
474 /**
475  * Firmware selection, phase 3.
476  *
477  * On error, the calling firmware should check for updates to secdata and/or
478  * nvdata, then reboot.
479  *
480  * On success, the calling firmware should lock down secdata before continuing
481  * with the boot process.
482  *
483  * @param ctx		Vboot context
484  * @return VB2_SUCCESS, or error code on error.
485  */
486 vb2_error_t vb2api_fw_phase3(struct vb2_context *ctx);
487 
488 /**
489  * Initialize hashing data for the specified tag.
490  * This function is not legal when running from a coreboot image that has
491  * CONFIG_VBOOT_CBFS_INTEGRATION=y set. In that case, vb2api_get_metadata_hash()
492  * must be used instead.
493  *
494  * @param ctx		Vboot context
495  * @param tag		Tag to start hashing (enum vb2_hash_tag)
496  * @return VB2_SUCCESS, or error code on error.
497  */
498 vb2_error_t vb2api_init_hash(struct vb2_context *ctx, uint32_t tag);
499 
500 /**
501  * Extend the hash started by vb2api_init_hash() with additional data.
502  *
503  * (This is the same for both old and new style structs.)
504  *
505  * @param ctx		Vboot context
506  * @param buf		Data to hash
507  * @param size		Size of data in bytes
508  * @return VB2_SUCCESS, or error code on error.
509  */
510 vb2_error_t vb2api_extend_hash(struct vb2_context *ctx, const void *buf,
511 			       uint32_t size);
512 
513 /**
514  * Check the hash value started by vb2api_init_hash().
515  *
516  * @param ctx		Vboot context
517  * @return VB2_SUCCESS, or error code on error.
518  */
519 int vb2api_check_hash(struct vb2_context *ctx);
520 
521 /**
522  * Check the hash value started by vb2api_init_hash() while retrieving
523  * calculated digest.
524  *
525  * @param ctx			Vboot context
526  * @param digest_out		optional pointer to buffer to store digest
527  * @param digest_out_size	optional size of buffer to store digest
528  * @return VB2_SUCCESS, or error code on error.
529  */
530 vb2_error_t vb2api_check_hash_get_digest(struct vb2_context *ctx,
531 					 void *digest_out,
532 					 uint32_t digest_out_size);
533 
534 /**
535  * Get pointer to metadata hash from body signature in preamble.
536  * Body signature data size has to be zero to indicate that it contains
537  * metadata hash. This is only legal to call after vb2api_fw_phase3() has
538  * returned successfully, and will return with error otherwise.
539  * This function is only legal to call from coreboot with
540  * CONFIG_VBOOT_CBFS_INTEGRATION=y. `futility sign` will automatically detect
541  * the presence of that option in an image and prepare the correct kind
542  * of signature.
543  *
544  * @param ctx			Vboot context
545  * @param hash_ptr_out		pointer to output hash to
546  * @return VB2_SUCCESS, or error code on error.
547  */
548 vb2_error_t vb2api_get_metadata_hash(struct vb2_context *ctx,
549 				     struct vb2_hash **hash_ptr_out);
550 
551 /**
552  * Get a PCR digest
553  *
554  * @param ctx		Vboot context
555  * @param which_digest	PCR index of the digest
556  * @param dest		Destination where the digest is copied.
557  * 			Recommended size is VB2_PCR_DIGEST_RECOMMENDED_SIZE.
558  * @param dest_size	IN: size of the buffer pointed by dest
559  * 			OUT: size of the copied digest
560  * @return VB2_SUCCESS, or error code on error
561  */
562 vb2_error_t vb2api_get_pcr_digest(struct vb2_context *ctx,
563 				  enum vb2_pcr_digest which_digest,
564 				  uint8_t *dest, uint32_t *dest_size);
565 
566 /**
567  * Prepare for kernel verification stage.
568  *
569  * Must be called before other vb2api kernel functions.
570  *
571  * @param ctx		Vboot context
572  * @return VB2_SUCCESS, or error code on error.
573  */
574 vb2_error_t vb2api_kernel_phase1(struct vb2_context *ctx);
575 
576 /**
577  * Do kernel verification.
578  *
579  * Must be called after vb2api_kernel_phase1.
580  *
581  * @param ctx		Vboot context
582  * @return VB2_SUCCESS, or error code on error.
583  */
584 vb2_error_t vb2api_kernel_phase2(struct vb2_context *ctx);
585 
586 /**
587  * Finalize for kernel verification stage.
588  *
589  * Handle NO_BOOT flag. Also, check and roll forward kernel version.
590  *
591  * @param ctx		Vboot context
592  * @return VB2_SUCCESS, or error code on error.
593  */
594 vb2_error_t vb2api_kernel_finalize(struct vb2_context *ctx);
595 
596 struct vb2_kernel_params {
597 	/* Inputs to vb2api_load_kernel(). */
598 	/* Destination buffer for kernel (normally at 0x100000 on x86). */
599 	void *kernel_buffer;
600 	/* Size of kernel buffer in bytes. */
601 	uint32_t kernel_buffer_size;
602 
603 	/*
604 	 * Outputs from vb2api_load_kernel(); valid only if it returns success.
605 	 */
606 	/* Handle of disk containing loaded kernel. */
607 	vb2ex_disk_handle_t disk_handle;
608 	/* Partition number on disk to boot (1...M). */
609 	uint32_t partition_number;
610 	/* Offset of bootloader image from `kernel_buffer` address. */
611 	uint64_t bootloader_offset;
612 	/* Size of bootloader image in bytes. */
613 	uint32_t bootloader_size;
614 	/* UniquePartitionGuid for boot partition. */
615 	uint8_t partition_guid[16];
616 	/* Flags set by signer. */
617 	uint32_t flags;
618 };
619 
620 /*****************************************************************************/
621 /* Disk access */
622 
623 /* Flags for vb2_disk_info */
624 
625 /*
626  * Disk selection in the lower 16 bits (where the disk lives), and disk
627  * attributes in the higher 16 bits (extra information about the disk
628  * needed to access it correctly).
629  */
630 #define VB2_DISK_FLAG_SELECT_MASK 0xffff
631 #define VB2_DISK_FLAG_ATTRIBUTE_MASK (0xffff << 16)
632 
633 /*
634  * Disks are used in two ways:
635  * - As a random-access device to read and write the GPT
636  * - As a streaming device to read the kernel
637  * These are implemented differently on raw NAND vs eMMC/SATA/USB
638  * - On eMMC/SATA/USB, both of these refer to the same underlying
639  *   storage, so they have the same size and LBA size. In this case,
640  *   the GPT should not point to the same address as itself.
641  * - On raw NAND, the GPT is held on a portion of the SPI flash.
642  *   Random access GPT operations refer to the SPI and streaming
643  *   operations refer to NAND. The GPT may therefore point into
644  *   the same offsets as itself.
645  * These types are distinguished by the following flag and vb2_disk_info
646  * has separate fields to describe the random-access ("GPT") and
647  * streaming aspects of the disk. If a disk is random-access (i.e.
648  * not raw NAND) then these fields are equal.
649  */
650 #define VB2_DISK_FLAG_EXTERNAL_GPT (1 << 16)
651 
652 /* Information on a single disk. */
653 struct vb2_disk_info {
654 	/* Disk handle. */
655 	vb2ex_disk_handle_t handle;
656 	/* Size of a random-access LBA sector in bytes. */
657 	uint64_t bytes_per_lba;
658 	/* Number of random-access LBA sectors on the device.
659 	 * If streaming_lba_count is 0, this stands in for the size of the
660 	 * randomly accessed portion as well as the streaming portion.
661 	 * Otherwise, this is only the randomly-accessed portion. */
662 	uint64_t lba_count;
663 	/* Number of streaming sectors on the device. */
664 	uint64_t streaming_lba_count;
665 	/* Flags (see VB2_DISK_FLAG_* constants). */
666 	uint32_t flags;
667 	/*
668 	 * Optional name string, for use in debugging.  May be empty or null if
669 	 * not available.
670 	 */
671 	const char *name;
672 };
673 
674 /**
675  * Attempt to load kernel from the specified device. On success, the output
676  * fields of params will be filled. The caller should set the input fields of
677  * params.
678  *
679  *
680  * @param ctx		Vboot context
681  * @param params	Params specific to loading the kernel
682  * @param disk_info	Disk from which to read kernel
683  *
684  * @return VB2_SUCCESS, or non-zero error code.
685  */
686 vb2_error_t vb2api_load_kernel(struct vb2_context *ctx,
687 			       struct vb2_kernel_params *params,
688 			       struct vb2_disk_info *disk_info);
689 
690 /* miniOS flags */
691 
692 /* Boot from non-active miniOS partition only. */
693 #define VB2_MINIOS_FLAG_NON_ACTIVE (1 << 0)
694 
695 /**
696  * Attempt to load miniOS kernel from the specified device. On success, the
697  * output fields of params will be filled. The caller should set the input
698  * fields of params.
699  *
700  * @param ctx		Vboot context
701  * @param params	Params specific to loading the kernel
702  * @param disk_info	Disk from which to read kernel
703  * @param minios_flags	Flags for miniOS
704  *
705  * @return VB2_SUCCESS, or non-zero error code.
706  */
707 vb2_error_t vb2api_load_minios_kernel(struct vb2_context *ctx,
708 				      struct vb2_kernel_params *params,
709 				      struct vb2_disk_info *disk_info,
710 				      uint32_t minios_flags);
711 
712 /**
713  * Load the verified boot block (vblock) for a kernel.
714  *
715  * This function may be called multiple times, to load and verify the
716  * vblocks from multiple kernel partitions.
717  *
718  * @param ctx		Vboot context
719  * @param stream	Kernel stream
720  * @return VB2_SUCCESS, or error code on error.
721  */
722 vb2_error_t vb2api_load_kernel_vblock(struct vb2_context *ctx);
723 
724 /**
725  * Get the size and offset of the kernel data for the most recent vblock.
726  *
727  * Valid after a successful call to vb2api_load_kernel_vblock().
728  *
729  * @param ctx		Vboot context
730  * @param offset_ptr	Destination for offset in bytes of kernel data as
731  *			reported by vblock.
732  * @param size_ptr      Destination for size of kernel data in bytes.
733  * @return VB2_SUCCESS, or error code on error.
734  */
735 vb2_error_t vb2api_get_kernel_size(struct vb2_context *ctx,
736 				   uint32_t *offset_ptr, uint32_t *size_ptr);
737 
738 /**
739  * Verify kernel data using the previously loaded kernel vblock.
740  *
741  * Valid after a successful call to vb2api_load_kernel_vblock().  This allows
742  * the caller to load or map the kernel data, as appropriate, and pass the
743  * pointer to the kernel data into vboot.
744  *
745  * @param ctx		Vboot context
746  * @param buf		Pointer to kernel data
747  * @param size		Size of kernel data in bytes
748  * @return VB2_SUCCESS, or error code on error.
749  */
750 vb2_error_t vb2api_verify_kernel_data(struct vb2_context *ctx, const void *buf,
751 				      uint32_t size);
752 
753 /**
754  * Clean up after kernel verification.
755  *
756  * Call this after successfully loading a vblock and verifying kernel data,
757  * or if you've run out of boot devices and/or kernel partitions.
758  *
759  * This cleans up intermediate data structures in the vboot context, and
760  * updates the version in the secure data if necessary.
761  */
762 vb2_error_t vb2api_kernel_phase3(struct vb2_context *ctx);
763 
764 /**
765  * Read the hardware ID from the GBB, and store it onto the given buffer.
766  *
767  * @param ctx		Vboot context.
768  * @param hwid		Buffer to store HWID, which will be null-terminated.
769  * @param size		Maximum size of HWID including null terminator.  HWID
770  * 			length may not exceed 256 (VB2_GBB_HWID_MAX_SIZE), so
771  * 			this value is suggested.  If size is too small, then
772  * 			VB2_ERROR_INVALID_PARAMETER is returned.  Actual size
773  * 			of the output HWID string is returned in this pointer,
774  * 			also including null terminator.
775  * @return VB2_SUCCESS, or error code on error.
776  */
777 vb2_error_t vb2api_gbb_read_hwid(struct vb2_context *ctx, char *hwid,
778 				 uint32_t *size);
779 
780 /**
781  * Retrieve current GBB flags.
782  *
783  * See enum vb2_gbb_flag in 2gbb_flags.h for a list of all GBB flags.
784  *
785  * @param ctx		Vboot context.
786  *
787  * @return vb2_gbb_flags_t representing current GBB flags.
788  */
789 vb2_gbb_flags_t vb2api_gbb_get_flags(struct vb2_context *ctx);
790 
791 /**
792  * Get the size of the signed firmware body.
793  *
794  * This is only legal to call after vb2api_fw_phase3() has returned
795  * successfully, and will die otherwise. This should never be called when
796  * running from a coreboot image that has CONFIG_VBOOT_CBFS_INTEGRATION=y set,
797  * or it will also die (with data size in signature being 0). In that case,
798  * vb2api_get_metadata_hash() should be used instead.
799  *
800  * @param ctx		Vboot context
801  *
802  * @return The firmware body size in bytes (or 0 if called too early).
803  */
804 uint32_t vb2api_get_firmware_size(struct vb2_context *ctx);
805 
806 /**
807  * Check if this firmware was bundled with the well-known public developer key
808  * set (more specifically, checks the recovery key in recovery mode and the
809  * kernel subkey from the firmware preamble in other modes). This is a best
810  * effort check that could be misled by a specifically crafted key.
811  *
812  * May only be called after vb2api_kernel_phase1() has run.
813  *
814  * @param ctx		Vboot context
815  *
816  * @return 1 for developer keys, 0 for any others.
817  */
818 int vb2api_is_developer_signed(struct vb2_context *ctx);
819 
820 /**
821  * Return the current kernel rollback version from secdata.
822  *
823  * @param ctx		Vboot context
824  *
825  * @return The rollback version number.
826  */
827 uint32_t vb2api_get_kernel_rollback_version(struct vb2_context *ctx);
828 
829 /**
830  * If no display is available, set DISPLAY_REQUEST in nvdata.
831  *
832  * @param ctx           Vboot2 context
833  * @return 1 if DISPLAY_REQUEST is set and a reboot is required, or 0 otherwise.
834  */
835 int vb2api_need_reboot_for_display(struct vb2_context *ctx);
836 
837 /**
838  * Get the current recovery reason.
839  *
840  * See enum vb2_nv_recovery in 2recovery_reasons.h.
841  *
842  * @param ctx		Vboot context
843  * @return Current recovery reason.
844  */
845 uint32_t vb2api_get_recovery_reason(struct vb2_context *ctx);
846 
847 /**
848  * Get the current locale id from nvdata.
849  *
850  * @param ctx		Vboot context
851  * @return Current locale id.
852  */
853 uint32_t vb2api_get_locale_id(struct vb2_context *ctx);
854 
855 /**
856  * Set the locale id in nvdata.
857  *
858  * @param ctx		Vboot context
859  * @param locale_id 	The locale id to be set
860  */
861 void vb2api_set_locale_id(struct vb2_context *ctx, uint32_t locale_id);
862 
863 /**
864  * Whether diagnostic UI functionality is enabled or not.
865  *
866  * @param ctx		Vboot context
867  * @return 1 if enabled, 0 if disabled.
868  */
869 int vb2api_diagnostic_ui_enabled(struct vb2_context *ctx);
870 
871 /* Default boot target in developer mode. */
872 enum vb2_dev_default_boot_target {
873 	/* Default to boot from internal disk. */
874 	VB2_DEV_DEFAULT_BOOT_TARGET_INTERNAL = 0,
875 
876 	/* Default to boot from external disk. */
877 	VB2_DEV_DEFAULT_BOOT_TARGET_EXTERNAL = 1,
878 
879 	/* Default to boot altfw. */
880 	VB2_DEV_DEFAULT_BOOT_TARGET_ALTFW = 2,
881 };
882 
883 /**
884  * Get the default boot target in developer mode. This function must be called
885  * after vb2api_kernel_phase1.
886  *
887  * @param ctx		Vboot context
888  * @return The developer mode default boot target.
889  */
890 enum vb2_dev_default_boot_target vb2api_get_dev_default_boot_target(
891 	struct vb2_context *ctx);
892 
893 /**
894  * Whether to use short delay instead of the normal delay in developer screens.
895  *
896  * @param ctx		Vboot context
897  * @return 1 for short delay and 0 otherwise.
898  */
899 int vb2api_use_short_dev_screen_delay(struct vb2_context *ctx);
900 
901 /**
902  * Request to enable developer mode.
903  *
904  * Enables the developer flag in vb2_context firmware secdata.  Note that
905  * modified secdata must be saved for change to apply on reboot.
906  *
907  * NOTE: Doesn't update the LAST_BOOT_DEVELOPER secdata flag.  That should be
908  * done on the next boot.
909  *
910  * @param ctx		Vboot context
911  * @return VB2_SUCCESS if success; error if enabling developer mode is not
912  * allowed.
913  */
914 vb2_error_t vb2api_enable_developer_mode(struct vb2_context *ctx);
915 
916 /**
917  * Request to disable developer mode by setting VB2_NV_DISABLE_DEV_REQUEST.
918  *
919  * @param ctx		Vboot context
920  * @return VB2_SUCCESS if success; other errors if the check of
921  * VB2_GBB_FLAG_FORCE_DEV_SWITCH_ON failed.
922  */
923 vb2_error_t vb2api_disable_developer_mode(struct vb2_context *ctx);
924 
925 /**
926  * Request diagnostics by setting VB2_NV_DIAG_REQUEST.
927  *
928  * @param ctx		Vboot context
929  */
930 void vb2api_request_diagnostics(struct vb2_context *ctx);
931 
932 /*****************************************************************************/
933 /* APIs provided by the caller to verified boot */
934 
935 /**
936  * Read a verified boot resource.
937  *
938  * @param ctx		Vboot context
939  * @param index		Resource index to read
940  * @param offset	Byte offset within resource to start at
941  * @param buf		Destination for data
942  * @param size		Amount of data to read
943  * @return VB2_SUCCESS, or error code on error.
944  */
945 vb2_error_t vb2ex_read_resource(struct vb2_context *ctx,
946 				enum vb2_resource_index index, uint32_t offset,
947 				void *buf, uint32_t size);
948 
949 /**
950  * Print debug output.
951  *
952  * This should work like printf().  If func!=NULL, it will be a string with
953  * the current function name; that can be used to generate prettier debug
954  * output.  If func==NULL, don't print any extra header/trailer so that this
955  * can be used to composite a bigger output string from several calls - for
956  * example, when doing a hex dump.
957  *
958  * @param func		Function name generating output, or NULL.
959  * @param fmt		Printf format string
960  */
961 __attribute__((format(printf, 2, 3)))
962 void vb2ex_printf(const char *func, const char *fmt, ...);
963 
964 /**
965  * Initialize the hardware crypto engine to calculate a block-style digest.
966  *
967  * @param hash_alg	Hash algorithm to use
968  * @param data_size	Expected total size of data to hash, or 0. If 0, the
969  *			total size is not known in advance. Implementations that
970  *			cannot handle unknown sizes should return UNSUPPORTED
971  *			in that case. If the value is non-zero, implementations
972  *			can trust it to be accurate.
973  * @return VB2_SUCCESS, or non-zero error code (HWCRYPTO_UNSUPPORTED not fatal).
974  */
975 vb2_error_t vb2ex_hwcrypto_digest_init(enum vb2_hash_algorithm hash_alg,
976 				       uint32_t data_size);
977 
978 /**
979  * Extend the hash in the hardware crypto engine with another block of data.
980  *
981  * @param buf		Next data block to hash
982  * @param size		Length of data block in bytes
983  * @return VB2_SUCCESS, or non-zero error code.
984  */
985 vb2_error_t vb2ex_hwcrypto_digest_extend(const uint8_t *buf, uint32_t size);
986 
987 /**
988  * Finalize the digest in the hardware crypto engine and extract the result.
989  *
990  * @param digest	Destination buffer for resulting digest
991  * @param digest_size	Length of digest buffer in bytes
992  * @return VB2_SUCCESS, or non-zero error code.
993  */
994 vb2_error_t vb2ex_hwcrypto_digest_finalize(uint8_t *digest,
995 					   uint32_t digest_size);
996 
997 /**
998  * Verify a RSA PKCS1.5 signature in hardware crypto engine
999  * against an expected hash digest.
1000  *
1001  * @param key		Key to use in signature verification
1002  * @param sig		Signature to verify (destroyed in process)
1003  * @param digest	Digest of signed data
1004  * @return VB2_SUCCESS, or non-zero error code (HWCRYPTO_UNSUPPORTED not fatal).
1005  */
1006 vb2_error_t vb2ex_hwcrypto_rsa_verify_digest(const struct vb2_public_key *key,
1007 					     const uint8_t *sig,
1008 					     const uint8_t *digest);
1009 
1010 /**
1011  * Calculate modexp using hardware crypto engine.
1012  *
1013  * @param key		Key to use in signing
1014  * @param inout		Input and output big-endian byte array
1015  * @param workbuf	Work buffer
1016  * @param workbuf_size	Work buffer size
1017  * @param exp		RSA public exponent: either 65537 (F4) or 3
1018  * @return VB2_SUCCESS, HWCRYPTO_UNSUPPORTED or WORKBUF_SMALL.
1019  */
1020 vb2_error_t vb2ex_hwcrypto_modexp(const struct vb2_public_key *key,
1021 				  uint8_t *inout,
1022 				  void *workbuf, size_t workbuf_size,
1023 				  int exp);
1024 
1025 /*
1026  * Report if hardware crypto is allowed in the current context. It may be
1027  * disabled by TPM flag and is categorically disallowed in recovery mode.
1028  *
1029  * @param ctx		Vboot context
1030  * @returns 1 if hardware crypto is allowed, 0 if it is forbidden.
1031  */
1032 bool vb2api_hwcrypto_allowed(struct vb2_context *ctx);
1033 
1034 /*
1035  * Abort vboot flow due to a failed assertion or broken assumption.
1036  *
1037  * Likely due to caller misusing vboot (e.g. calling API functions
1038  * out-of-order, filling in vb2_context fields inappropriately).
1039  * Implementation should reboot or halt the machine, or fall back to some
1040  * alternative boot flow.  Retrying vboot is unlikely to succeed.
1041  */
1042 void vb2ex_abort(void);
1043 
1044 /**
1045  * Commit any pending data to disk.
1046  *
1047  * Commit nvdata and secdata spaces if modified.  Normally this should be
1048  * performed after vboot has completed executing and control has been passed
1049  * back to the caller.  However, in certain kernel verification cases (e.g.
1050  * right before attempting to boot an OS; from a UI screen which requires
1051  * user-initiated shutdown; just prior to triggering battery cut-off), the
1052  * caller may not get a chance to commit this data.
1053  *
1054  * @param ctx		Vboot context
1055  * @return VB2_SUCCESS, or non-zero error code.
1056  */
1057 vb2_error_t vb2ex_commit_data(struct vb2_context *ctx);
1058 
1059 /*****************************************************************************/
1060 /* TPM functionality */
1061 
1062 /**
1063  * Initialize the TPM.
1064  *
1065  * @return VB2_SUCCESS, or non-zero error code.
1066  */
1067 vb2_error_t vb2ex_tpm_init(void);
1068 
1069 /**
1070  * Close and open the TPM.
1071  *
1072  * This is needed for running more complex commands at user level, such as
1073  * TPM_TakeOwnership, since the TPM device can be opened only by one process at
1074  * a time.
1075  *
1076  * @return VB2_SUCCESS, or non-zero error code.
1077  */
1078 vb2_error_t vb2ex_tpm_close(void);
1079 vb2_error_t vb2ex_tpm_open(void);
1080 
1081 /**
1082  * Send request to TPM and receive response
1083  *
1084  * Send a request_length-byte request to the TPM and receive a response.  On
1085  * input, response_length is the size of the response buffer in bytes.  On
1086  * exit, response_length is set to the actual received response length in
1087  * bytes.
1088  *
1089  * @param request		Pointer to request buffer
1090  * @param request_length	Number of bytes to send
1091  * @param response		Pointer to response buffer
1092  * @param response_length	Size of response buffer; on return,
1093  * 				set to number of received bytes
1094  * @return TPM_SUCCESS, or non-zero if error.
1095  */
1096 uint32_t vb2ex_tpm_send_recv(const uint8_t *request, uint32_t request_length,
1097 			     uint8_t *response, uint32_t *response_length);
1098 
1099 #ifdef CHROMEOS_ENVIRONMENT
1100 
1101 /**
1102  * Obtain cryptographically secure random bytes.
1103  *
1104  * This function is used to generate random nonces for TPM auth sessions for
1105  * example. As an implication, the generated random bytes should not be
1106  * predictable for a TPM communication interception attack. This implies a
1107  * local source of randomness should be used, i.e. this should not be wired to
1108  * the TPM RNG directly. Otherwise, an attacker with communication interception
1109  * abilities could launch replay attacks by reusing previous nonces.
1110  *
1111  * @return VB2_SUCCESS, or non-zero error code.
1112  */
1113 vb2_error_t vb2ex_tpm_get_random(uint8_t *buf, uint32_t length);
1114 
1115 #endif  /* CHROMEOS_ENVIRONMENT */
1116 
1117 /* Modes for vb2ex_tpm_set_mode. */
1118 enum vb2_tpm_mode {
1119 	/*
1120 	 * TPM is enabled tentatively, and may be set to either
1121 	 * ENABLED or DISABLED mode.
1122 	 */
1123 	VB2_TPM_MODE_ENABLED_TENTATIVE = 0,
1124 
1125 	/* TPM is enabled, and mode may not be changed. */
1126 	VB2_TPM_MODE_ENABLED = 1,
1127 
1128 	/* TPM is disabled, and mode may not be changed. */
1129 	VB2_TPM_MODE_DISABLED = 2,
1130 };
1131 
1132 /**
1133  * Set the current TPM mode value, and validate that it was changed.  If one
1134  * of the following occurs, the function call fails:
1135  *   - TPM does not understand the instruction (old version)
1136  *   - TPM has already left the TpmModeEnabledTentative mode
1137  *   - TPM responds with a mode other than the requested mode
1138  *   - Some other communication error occurs
1139  *  Otherwise, the function call succeeds.
1140  *
1141  * @param mode_val       Desired TPM mode to set.  May be one of ENABLED
1142  *                       or DISABLED from vb2_tpm_mode enum.
1143  * @return VB2_SUCCESS, or non-zero error code.
1144  */
1145 vb2_error_t vb2ex_tpm_set_mode(enum vb2_tpm_mode mode_val);
1146 
1147 /**
1148  * Clear the TPM owner.
1149  *
1150  * @param ctx		Vboot context
1151  * @return VB2_SUCCESS, or error code on error.
1152  */
1153 vb2_error_t vb2ex_tpm_clear_owner(struct vb2_context *ctx);
1154 
1155 /*****************************************************************************/
1156 /* Auxiliary firmware (auxfw) */
1157 
1158 /**
1159  * Sync all auxiliary firmware to the expected versions.
1160  *
1161  * This function will first check if an auxfw update is needed and
1162  * what the "severity" of that update is (i.e., if any auxfw devices
1163  * exist and the relative quickness of updating it.  If the update is
1164  * deemed slow, it may display a screen to notify the user.  The
1165  * platform is then instructed to perform the update.  Finally, an EC
1166  * reboot to its RO section is performed to ensure that auxfw devices
1167  * are also reset and running the new firmware.
1168  *
1169  * @param ctx           Vboot2 context
1170  * @return VB2_SUCCESS, or non-zero error code.
1171  */
1172 vb2_error_t vb2api_auxfw_sync(struct vb2_context *ctx);
1173 
1174 /*
1175  * severity levels for an auxiliary firmware update request
1176  */
1177 enum vb2_auxfw_update_severity {
1178 	/* no update needed and no protection needed */
1179 	VB2_AUXFW_NO_DEVICE = 0,
1180 	/* no update needed */
1181 	VB2_AUXFW_NO_UPDATE = 1,
1182 	/* update needed, can be done quickly */
1183 	VB2_AUXFW_FAST_UPDATE = 2,
1184 	/* update needed, "this would take a while..." */
1185 	VB2_AUXFW_SLOW_UPDATE = 3,
1186 };
1187 
1188 /*
1189  * Check if any auxiliary firmware needs updating.
1190  *
1191  * This is called after the EC has been updated and is intended to
1192  * version-check additional firmware blobs such as TCPCs.
1193  *
1194  * @param severity	return parameter for health of auxiliary firmware
1195  *			(see vb2_auxfw_update_severity above)
1196  * @return VBERROR_... error, VB2_SUCCESS on success.
1197  */
1198 vb2_error_t vb2ex_auxfw_check(enum vb2_auxfw_update_severity *severity);
1199 
1200 /*
1201  * Perform auxiliary firmware update(s).
1202  *
1203  * This is called after the EC has been updated and is intended to
1204  * update additional firmware blobs such as TCPCs.
1205  *
1206  * @return VBERROR_... error, VB2_SUCCESS on success.
1207  */
1208 vb2_error_t vb2ex_auxfw_update(void);
1209 
1210 /*
1211  * Notify client that vboot is done with auxfw.
1212  *
1213  * If auxfw sync was successful, this will be called at the end so that
1214  * the client may perform actions that require the auxfw to be in its
1215  * final state.  This may include protecting the communcations tunnels that
1216  * allow auxiliary firmware updates from the OS.
1217  *
1218  * @param ctx		Vboot context
1219  * @return VBERROR_... error, VB2_SUCCESS on success.
1220  */
1221 vb2_error_t vb2ex_auxfw_finalize(struct vb2_context *ctx);
1222 
1223 /*****************************************************************************/
1224 /* Embedded controller (EC) */
1225 
1226 /*
1227  * Firmware selection type for EC software sync logic.  Note that we store
1228  * these in a uint32_t because enum maps to int, which isn't fixed-size.
1229  */
1230 enum vb2_firmware_selection {
1231 	/* Read only firmware for normal or developer path. */
1232 	VB_SELECT_FIRMWARE_READONLY = 3,
1233 	/* Rewritable EC firmware currently set active */
1234 	VB_SELECT_FIRMWARE_EC_ACTIVE = 4,
1235 	/* Rewritable EC firmware currently not set active thus updatable */
1236 	VB_SELECT_FIRMWARE_EC_UPDATE = 5,
1237 	/* Keep this at the end */
1238 	VB_SELECT_FIRMWARE_COUNT,
1239 };
1240 
1241 /**
1242  * Sync the Embedded Controller device to the expected version.
1243  *
1244  * This function will check if EC software sync is allowed, and if it
1245  * is, it will compare the expected image hash to the actual image
1246  * hash.  If they are the same, the EC will simply jump to its RW
1247  * firwmare.  Otherwise, the specified flash image will be updated to
1248  * the new version, and the EC will reboot into its new firmware.
1249  *
1250  * @param ctx		Vboot context
1251  * @return VB2_SUCCESS, or non-zero if error.
1252  */
1253 vb2_error_t vb2api_ec_sync(struct vb2_context *ctx);
1254 
1255 /**
1256  * Check if the EC is currently running rewritable code.
1257  *
1258  * If the EC is in RO code, sets *in_rw=0.
1259  * If the EC is in RW code, sets *in_rw non-zero.
1260  * If the current EC image is unknown, returns error. */
1261 vb2_error_t vb2ex_ec_running_rw(int *in_rw);
1262 
1263 /**
1264  * Request the EC jump to its rewritable code.  If successful, returns when the
1265  * EC has booting its RW code far enough to respond to subsequent commands.
1266  * Does nothing if the EC is already in its rewritable code.
1267  */
1268 vb2_error_t vb2ex_ec_jump_to_rw(void);
1269 
1270 /**
1271  * Tell the EC to refuse another jump until it reboots. Subsequent calls to
1272  * vb2ex_ec_jump_to_rw() in this boot will fail.
1273  */
1274 vb2_error_t vb2ex_ec_disable_jump(void);
1275 
1276 /**
1277  * Read the SHA-256 hash of the selected EC image.
1278  *
1279  * @param select    Image to get hash of. RO or RW.
1280  * @param hash      Pointer to the hash.
1281  * @param hash_size Pointer to the hash size.
1282  * @return VB2_SUCCESS, or error code on error.
1283  */
1284 vb2_error_t vb2ex_ec_hash_image(enum vb2_firmware_selection select,
1285 				const uint8_t **hash, int *hash_size);
1286 
1287 /**
1288  * Read the SHA-256 hash of the expected contents of the EC image associated
1289  * with the main firmware specified by the "select" argument.
1290  *
1291  * @param select	Image to get expected hash for (RO or RW).
1292  * @param hash		Pointer to the hash.
1293  * @param hash_size	Pointer to the hash size (in bytes).
1294  * @return VB2_SUCCESS, or error code on error.
1295  */
1296 vb2_error_t vb2ex_ec_get_expected_image_hash(enum vb2_firmware_selection select,
1297 					     const uint8_t **hash,
1298 					     int *hash_size);
1299 
1300 /**
1301  * Update the selected EC image to the expected version.
1302  *
1303  * @param select	Image to get expected hash for (RO or RW).
1304  * @return VB2_SUCCESS, or error code on error.
1305  */
1306 vb2_error_t vb2ex_ec_update_image(enum vb2_firmware_selection select);
1307 
1308 /**
1309  * Lock the EC code to prevent updates until the EC is rebooted.
1310  * Subsequent calls to vb2ex_ec_update_image() during boot will fail.
1311  *
1312  * @return VB2_SUCCESS, or error code on error.
1313  */
1314 vb2_error_t vb2ex_ec_protect(void);
1315 
1316 /**
1317  * Perform EC post-verification / updating / jumping actions.
1318  *
1319  * This routine is called to perform certain actions that must wait until
1320  * after the EC resides in its `final` image (the image the EC will
1321  * run for the duration of boot). These actions include verifying that
1322  * enough power is available to continue with boot.
1323  *
1324  * @param ctx		Pointer to vboot context.
1325  * @return VB2_SUCCESS, or error code on error.
1326  */
1327 vb2_error_t vb2ex_ec_vboot_done(struct vb2_context *ctx);
1328 
1329 /**
1330  * Request EC to stop discharging and cut-off battery.
1331  */
1332 vb2_error_t vb2ex_ec_battery_cutoff(void);
1333 
1334 /*****************************************************************************/
1335 /* Functions for firmware UI. */
1336 
1337 /**
1338  * Get the vboot debug info.
1339  *
1340  * Return a pointer to the vboot debug info string which is guaranteed to be
1341  * null-terminated.  The caller owns the string and should call free() when
1342  * finished with it.
1343  *
1344  * @param ctx		Vboot context
1345  * @return The pointer to the vboot debug info string.  NULL on error.
1346  */
1347 char *vb2api_get_debug_info(struct vb2_context *ctx);
1348 
1349 /*****************************************************************************/
1350 /* Timer. */
1351 
1352 /**
1353  * Read a millisecond timer.
1354  *
1355  * This should have a sufficient number of bits to avoid wraparound for at
1356  * least 10 minutes.
1357  *
1358  * @return Current timer value in milliseconds.
1359  */
1360 uint32_t vb2ex_mtime(void);
1361 
1362 /*****************************************************************************/
1363 /* Firmware slot information. */
1364 
1365 union vb2_fw_boot_info {
1366 	uint8_t raw[4];
1367 	struct {
1368 		uint8_t tries       : 4;
1369 		uint8_t slot        : 1;
1370 		uint8_t prev_slot   : 1;
1371 		uint8_t prev_result : 2;
1372 		uint8_t boot_mode;
1373 		/* The following 2 bytes only exist for recovery mode */
1374 		uint8_t recovery_reason;
1375 		uint8_t recovery_subcode;
1376 	};
1377 };
1378 
1379 /**
1380  * Return `vb2_fw_boot_info` and can be used
1381  * to log information about the current boot in a compact format.
1382  *
1383  * Note: Only call this API at minimum after `vb2api_fw_phase2` function
1384  * returns.
1385  *
1386  * @param ctx          Vboot context
1387  * @return filled out vb2 info as per `union vb2_fw_boot_info`.
1388  */
1389 union vb2_fw_boot_info vb2api_get_fw_boot_info(struct vb2_context *ctx);
1390 
1391 /**
1392  * Clear recovery request appropriately.
1393  *
1394  * To avoid the recovery request "sticking" and the user being in a permanent
1395  * recovery loop, the recovery request must be cleared and committed to nvdata.
1396  * Note that this should be done at some point after we are certain the system
1397  * does not require any reboots for non-vboot-related reasons (e.g. FSP
1398  * initialization), and before triggering a reboot to exit a transient recovery
1399  * mode (e.g. memory retraining request).
1400  *
1401  * In BROKEN cases, the recovery reason will be stowed away as subcode, to be
1402  * retrieved after the user reboots in manual recovery.  In manual recovery,
1403  * subcode will be left alone to keep available for subsequent manual recovery
1404  * requests, or for accessing from userspace on the next boot.
1405  *
1406  * This function modifies nvdata in vb2_context, but the caller is still
1407  * expected to call vb2_commit_data.
1408  *
1409  * @param ctx		Vboot context
1410  */
1411 void vb2api_clear_recovery(struct vb2_context *ctx);
1412 
1413 #endif  /* VBOOT_REFERENCE_2API_H_ */
1414