1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2022, Linaro Limited
4  */
5 
6 #include <dm.h>
7 #include <efi.h>
8 #include <efi_loader.h>
9 #include <efi_variable.h>
10 #include <event.h>
11 #include <fwu.h>
12 #include <fwu_mdata.h>
13 #include <malloc.h>
14 
15 #include <linux/errno.h>
16 #include <linux/types.h>
17 
18 static u8 in_trial;
19 static u8 boottime_check;
20 
21 #include <linux/errno.h>
22 #include <linux/types.h>
23 #include <u-boot/crc.h>
24 
25 enum {
26 	IMAGE_ACCEPT_SET = 1,
27 	IMAGE_ACCEPT_CLEAR,
28 };
29 
30 enum {
31 	PRIMARY_PART = 1,
32 	SECONDARY_PART,
33 	BOTH_PARTS,
34 };
35 
fwu_get_dev_mdata(struct udevice ** dev,struct fwu_mdata * mdata)36 static int fwu_get_dev_mdata(struct udevice **dev, struct fwu_mdata *mdata)
37 {
38 	int ret;
39 
40 	ret = uclass_first_device_err(UCLASS_FWU_MDATA, dev);
41 	if (ret) {
42 		log_debug("Cannot find fwu device\n");
43 		return ret;
44 	}
45 
46 	if (!mdata)
47 		return 0;
48 
49 	ret = fwu_get_mdata(*dev, mdata);
50 	if (ret < 0)
51 		log_debug("Unable to get valid FWU metadata\n");
52 
53 	return ret;
54 }
55 
trial_counter_update(u16 * trial_state_ctr)56 static int trial_counter_update(u16 *trial_state_ctr)
57 {
58 	bool delete;
59 	u32 var_attr;
60 	efi_status_t status;
61 	efi_uintn_t var_size;
62 
63 	delete = !trial_state_ctr ? true : false;
64 	var_size = !trial_state_ctr ? 0 : (efi_uintn_t)sizeof(*trial_state_ctr);
65 	var_attr = !trial_state_ctr ? 0 : EFI_VARIABLE_NON_VOLATILE |
66 		EFI_VARIABLE_BOOTSERVICE_ACCESS;
67 	status = efi_set_variable_int(u"TrialStateCtr",
68 				      &efi_global_variable_guid,
69 				      var_attr,
70 				      var_size, trial_state_ctr, false);
71 
72 	if ((delete && (status != EFI_NOT_FOUND &&
73 			status != EFI_SUCCESS)) ||
74 	    (!delete && status != EFI_SUCCESS))
75 		return -1;
76 
77 	return 0;
78 }
79 
trial_counter_read(u16 * trial_state_ctr)80 static int trial_counter_read(u16 *trial_state_ctr)
81 {
82 	efi_status_t status;
83 	efi_uintn_t var_size;
84 
85 	var_size = (efi_uintn_t)sizeof(trial_state_ctr);
86 	status = efi_get_variable_int(u"TrialStateCtr",
87 				      &efi_global_variable_guid,
88 				      NULL,
89 				      &var_size, trial_state_ctr,
90 				      NULL);
91 	if (status != EFI_SUCCESS) {
92 		log_err("Unable to read TrialStateCtr variable\n");
93 		return -1;
94 	}
95 
96 	return 0;
97 }
98 
fwu_trial_count_update(void)99 static int fwu_trial_count_update(void)
100 {
101 	int ret;
102 	u16 trial_state_ctr;
103 
104 	ret = trial_counter_read(&trial_state_ctr);
105 	if (ret) {
106 		log_debug("Unable to read trial_state_ctr\n");
107 		goto out;
108 	}
109 
110 	++trial_state_ctr;
111 	if (trial_state_ctr > CONFIG_FWU_TRIAL_STATE_CNT) {
112 		log_info("Trial State count exceeded. Revert back to previous_active_index\n");
113 		ret = fwu_revert_boot_index();
114 		if (ret)
115 			log_err("Unable to revert active_index\n");
116 		ret = 1;
117 	} else {
118 		ret = trial_counter_update(&trial_state_ctr);
119 		if (ret)
120 			log_err("Unable to increment TrialStateCtr variable\n");
121 	}
122 
123 out:
124 	return ret;
125 }
126 
in_trial_state(struct fwu_mdata * mdata)127 static int in_trial_state(struct fwu_mdata *mdata)
128 {
129 	u32 i, active_bank;
130 	struct fwu_image_entry *img_entry;
131 	struct fwu_image_bank_info *img_bank_info;
132 
133 	active_bank = mdata->active_index;
134 	img_entry = &mdata->img_entry[0];
135 	for (i = 0; i < CONFIG_FWU_NUM_IMAGES_PER_BANK; i++) {
136 		img_bank_info = &img_entry[i].img_bank_info[active_bank];
137 		if (!img_bank_info->accepted) {
138 			log_info("System booting in Trial State\n");
139 			return 1;
140 		}
141 	}
142 
143 	return 0;
144 }
145 
fwu_get_image_type_id(u8 * image_index,efi_guid_t * image_type_id)146 static int fwu_get_image_type_id(u8 *image_index, efi_guid_t *image_type_id)
147 {
148 	u8 index;
149 	int i;
150 	struct efi_fw_image *image;
151 
152 	index = *image_index;
153 	image = update_info.images;
154 	for (i = 0; i < num_image_type_guids; i++) {
155 		if (index == image[i].image_index) {
156 			guidcpy(image_type_id, &image[i].image_type_id);
157 			return 0;
158 		}
159 	}
160 
161 	return -ENOENT;
162 }
163 
164 /**
165  * fwu_verify_mdata() - Verify the FWU metadata
166  * @mdata: FWU metadata structure
167  * @pri_part: FWU metadata partition is primary or secondary
168  *
169  * Verify the FWU metadata by computing the CRC32 for the metadata
170  * structure and comparing it against the CRC32 value stored as part
171  * of the structure.
172  *
173  * Return: 0 if OK, -ve on error
174  *
175  */
fwu_verify_mdata(struct fwu_mdata * mdata,bool pri_part)176 int fwu_verify_mdata(struct fwu_mdata *mdata, bool pri_part)
177 {
178 	u32 calc_crc32;
179 	void *buf;
180 
181 	buf = &mdata->version;
182 	calc_crc32 = crc32(0, buf, sizeof(*mdata) - sizeof(u32));
183 
184 	if (calc_crc32 != mdata->crc32) {
185 		log_debug("crc32 check failed for %s FWU metadata partition\n",
186 			  pri_part ? "primary" : "secondary");
187 		return -EINVAL;
188 	}
189 
190 	return 0;
191 }
192 
193 /**
194  * fwu_check_mdata_validity() - Check for validity of the FWU metadata copies
195  *
196  * Read both the metadata copies from the storage media, verify their checksum,
197  * and ascertain that both copies match. If one of the copies has gone bad,
198  * restore it from the good copy.
199  *
200  * Return: 0 if OK, -ve on error
201  *
202  */
fwu_check_mdata_validity(void)203 int fwu_check_mdata_validity(void)
204 {
205 	int ret;
206 	struct udevice *dev;
207 	struct fwu_mdata pri_mdata;
208 	struct fwu_mdata secondary_mdata;
209 	uint mdata_parts[2];
210 	uint valid_partitions, invalid_partitions;
211 
212 	ret = fwu_get_dev_mdata(&dev, NULL);
213 	if (ret)
214 		return ret;
215 
216 	/*
217 	 * Check if the platform has defined its own
218 	 * function to check the metadata partitions'
219 	 * validity. If so, that takes precedence.
220 	 */
221 	ret = fwu_mdata_check(dev);
222 	if (!ret || ret != -ENOSYS)
223 		return ret;
224 
225 	/*
226 	 * Two FWU metadata partitions are expected.
227 	 * If we don't have two, user needs to create
228 	 * them first
229 	 */
230 	valid_partitions = 0;
231 	ret = fwu_get_mdata_part_num(dev, mdata_parts);
232 	if (ret < 0) {
233 		log_debug("Error getting the FWU metadata partitions\n");
234 		return -ENOENT;
235 	}
236 
237 	ret = fwu_read_mdata_partition(dev, &pri_mdata, mdata_parts[0]);
238 	if (!ret) {
239 		ret = fwu_verify_mdata(&pri_mdata, 1);
240 		if (!ret)
241 			valid_partitions |= PRIMARY_PART;
242 	}
243 
244 	ret = fwu_read_mdata_partition(dev, &secondary_mdata, mdata_parts[1]);
245 	if (!ret) {
246 		ret = fwu_verify_mdata(&secondary_mdata, 0);
247 		if (!ret)
248 			valid_partitions |= SECONDARY_PART;
249 	}
250 
251 	if (valid_partitions == (PRIMARY_PART | SECONDARY_PART)) {
252 		/*
253 		 * Before returning, check that both the
254 		 * FWU metadata copies are the same. If not,
255 		 * populate the secondary partition from the
256 		 * primary partition copy.
257 		 */
258 		if (!memcmp(&pri_mdata, &secondary_mdata,
259 			    sizeof(struct fwu_mdata))) {
260 			ret = 0;
261 		} else {
262 			log_info("Both FWU metadata copies are valid but do not match.");
263 			log_info(" Restoring the secondary partition from the primary\n");
264 			ret = fwu_write_mdata_partition(dev, &pri_mdata,
265 							mdata_parts[1]);
266 			if (ret)
267 				log_debug("Restoring secondary FWU metadata partition failed\n");
268 		}
269 		goto out;
270 	}
271 
272 	if (!(valid_partitions & BOTH_PARTS)) {
273 		log_info("Both FWU metadata partitions invalid\n");
274 		ret = -EBADMSG;
275 		goto out;
276 	}
277 
278 	invalid_partitions = valid_partitions ^ BOTH_PARTS;
279 	ret = fwu_write_mdata_partition(dev,
280 					(invalid_partitions == PRIMARY_PART) ?
281 					&secondary_mdata : &pri_mdata,
282 					(invalid_partitions == PRIMARY_PART) ?
283 					mdata_parts[0] : mdata_parts[1]);
284 
285 	if (ret)
286 		log_debug("Restoring %s FWU metadata partition failed\n",
287 			  (invalid_partitions == PRIMARY_PART) ?
288 			  "primary" : "secondary");
289 
290 out:
291 	return ret;
292 }
293 
294 /**
295  * fwu_get_active_index() - Get active_index from the FWU metadata
296  * @active_idx: active_index value to be read
297  *
298  * Read the active_index field from the FWU metadata and place it in
299  * the variable pointed to be the function argument.
300  *
301  * Return: 0 if OK, -ve on error
302  *
303  */
fwu_get_active_index(uint * active_idx)304 int fwu_get_active_index(uint *active_idx)
305 {
306 	int ret;
307 	struct udevice *dev;
308 	struct fwu_mdata mdata = { 0 };
309 
310 	ret = fwu_get_dev_mdata(&dev, &mdata);
311 	if (ret)
312 		return ret;
313 
314 	/*
315 	 * Found the FWU metadata partition, now read the active_index
316 	 * value
317 	 */
318 	*active_idx = mdata.active_index;
319 	if (*active_idx >= CONFIG_FWU_NUM_BANKS) {
320 		log_debug("Active index value read is incorrect\n");
321 		ret = -EINVAL;
322 	}
323 
324 	return ret;
325 }
326 
327 /**
328  * fwu_set_active_index() - Set active_index in the FWU metadata
329  * @active_idx: active_index value to be set
330  *
331  * Update the active_index field in the FWU metadata
332  *
333  * Return: 0 if OK, -ve on error
334  *
335  */
fwu_set_active_index(uint active_idx)336 int fwu_set_active_index(uint active_idx)
337 {
338 	int ret;
339 	struct udevice *dev;
340 	struct fwu_mdata mdata = { 0 };
341 
342 	if (active_idx >= CONFIG_FWU_NUM_BANKS) {
343 		log_debug("Invalid active index value\n");
344 		return -EINVAL;
345 	}
346 
347 	ret = fwu_get_dev_mdata(&dev, &mdata);
348 	if (ret)
349 		return ret;
350 
351 	/*
352 	 * Update the active index and previous_active_index fields
353 	 * in the FWU metadata
354 	 */
355 	mdata.previous_active_index = mdata.active_index;
356 	mdata.active_index = active_idx;
357 
358 	/*
359 	 * Now write this updated FWU metadata to both the
360 	 * FWU metadata partitions
361 	 */
362 	ret = fwu_update_mdata(dev, &mdata);
363 	if (ret) {
364 		log_debug("Failed to update FWU metadata partitions\n");
365 		ret = -EIO;
366 	}
367 
368 	return ret;
369 }
370 
371 /**
372  * fwu_get_image_index() - Get the Image Index to be used for capsule update
373  * @image_index: The Image Index for the image
374  *
375  * The FWU multi bank update feature computes the value of image_index at
376  * runtime, based on the bank to which the image needs to be written to.
377  * Derive the image_index value for the image.
378  *
379  * Currently, the capsule update driver uses the DFU framework for
380  * the updates. This function gets the DFU alt number which is to
381  * be used as the Image Index
382  *
383  * Return: 0 if OK, -ve on error
384  *
385  */
fwu_get_image_index(u8 * image_index)386 int fwu_get_image_index(u8 *image_index)
387 {
388 	int ret, i;
389 	u8 alt_num;
390 	uint update_bank;
391 	efi_guid_t *image_guid, image_type_id;
392 	struct udevice *dev;
393 	struct fwu_mdata mdata = { 0 };
394 	struct fwu_image_entry *img_entry;
395 	struct fwu_image_bank_info *img_bank_info;
396 
397 	ret = fwu_get_dev_mdata(&dev, &mdata);
398 	if (ret)
399 		return ret;
400 
401 	ret = fwu_plat_get_update_index(&update_bank);
402 	if (ret) {
403 		log_debug("Failed to get the FWU update bank\n");
404 		goto out;
405 	}
406 
407 	ret = fwu_get_image_type_id(image_index, &image_type_id);
408 	if (ret) {
409 		log_debug("Unable to get image_type_id for image_index %u\n",
410 			  *image_index);
411 		goto out;
412 	}
413 
414 	ret = -EINVAL;
415 	/*
416 	 * The FWU metadata has been read. Now get the image_uuid for the
417 	 * image with the update_bank.
418 	 */
419 	for (i = 0; i < CONFIG_FWU_NUM_IMAGES_PER_BANK; i++) {
420 		if (!guidcmp(&image_type_id,
421 			     &mdata.img_entry[i].image_type_uuid)) {
422 			img_entry = &mdata.img_entry[i];
423 			img_bank_info = &img_entry->img_bank_info[update_bank];
424 			image_guid = &img_bank_info->image_uuid;
425 			ret = fwu_plat_get_alt_num(dev, image_guid, &alt_num);
426 			if (ret) {
427 				log_debug("alt_num not found for partition with GUID %pUs\n",
428 					  image_guid);
429 			} else {
430 				log_debug("alt_num %d for partition %pUs\n",
431 					  alt_num, image_guid);
432 				*image_index = alt_num + 1;
433 			}
434 
435 			goto out;
436 		}
437 	}
438 
439 	log_debug("Partition with the image type %pUs not found\n",
440 		  &image_type_id);
441 
442 out:
443 	return ret;
444 }
445 
446 /**
447  * fwu_revert_boot_index() - Revert the active index in the FWU metadata
448  *
449  * Revert the active_index value in the FWU metadata, by swapping the values
450  * of active_index and previous_active_index in both copies of the
451  * FWU metadata.
452  *
453  * Return: 0 if OK, -ve on error
454  *
455  */
fwu_revert_boot_index(void)456 int fwu_revert_boot_index(void)
457 {
458 	int ret;
459 	u32 cur_active_index;
460 	struct udevice *dev;
461 	struct fwu_mdata mdata = { 0 };
462 
463 	ret = fwu_get_dev_mdata(&dev, &mdata);
464 	if (ret)
465 		return ret;
466 
467 	/*
468 	 * Swap the active index and previous_active_index fields
469 	 * in the FWU metadata
470 	 */
471 	cur_active_index = mdata.active_index;
472 	mdata.active_index = mdata.previous_active_index;
473 	mdata.previous_active_index = cur_active_index;
474 
475 	/*
476 	 * Now write this updated FWU metadata to both the
477 	 * FWU metadata partitions
478 	 */
479 	ret = fwu_update_mdata(dev, &mdata);
480 	if (ret) {
481 		log_debug("Failed to update FWU metadata partitions\n");
482 		ret = -EIO;
483 	}
484 
485 	return ret;
486 }
487 
488 /**
489  * fwu_clrset_image_accept() - Set or Clear the Acceptance bit for the image
490  * @img_type_id: GUID of the image type for which the accepted bit is to be
491  *               set or cleared
492  * @bank: Bank of which the image's Accept bit is to be set or cleared
493  * @action: Action which specifies whether image's Accept bit is to be set or
494  *          cleared
495  *
496  * Set/Clear the accepted bit for the image specified by the img_guid parameter.
497  * This indicates acceptance or rejection of image for subsequent boots by some
498  * governing component like OS(or firmware).
499  *
500  * Return: 0 if OK, -ve on error
501  *
502  */
fwu_clrset_image_accept(efi_guid_t * img_type_id,u32 bank,u8 action)503 static int fwu_clrset_image_accept(efi_guid_t *img_type_id, u32 bank, u8 action)
504 {
505 	int ret, i;
506 	struct udevice *dev;
507 	struct fwu_mdata mdata = { 0 };
508 	struct fwu_image_entry *img_entry;
509 	struct fwu_image_bank_info *img_bank_info;
510 
511 	ret = fwu_get_dev_mdata(&dev, &mdata);
512 	if (ret)
513 		return ret;
514 
515 	img_entry = &mdata.img_entry[0];
516 	for (i = 0; i < CONFIG_FWU_NUM_IMAGES_PER_BANK; i++) {
517 		if (!guidcmp(&img_entry[i].image_type_uuid, img_type_id)) {
518 			img_bank_info = &img_entry[i].img_bank_info[bank];
519 			if (action == IMAGE_ACCEPT_SET)
520 				img_bank_info->accepted |= FWU_IMAGE_ACCEPTED;
521 			else
522 				img_bank_info->accepted = 0;
523 
524 			ret = fwu_update_mdata(dev, &mdata);
525 			goto out;
526 		}
527 	}
528 
529 	/* Image not found */
530 	ret = -ENOENT;
531 
532 out:
533 	return ret;
534 }
535 
536 /**
537  * fwu_accept_image() - Set the Acceptance bit for the image
538  * @img_type_id: GUID of the image type for which the accepted bit is to be
539  *               cleared
540  * @bank: Bank of which the image's Accept bit is to be set
541  *
542  * Set the accepted bit for the image specified by the img_guid parameter. This
543  * indicates acceptance of image for subsequent boots by some governing component
544  * like OS(or firmware).
545  *
546  * Return: 0 if OK, -ve on error
547  *
548  */
fwu_accept_image(efi_guid_t * img_type_id,u32 bank)549 int fwu_accept_image(efi_guid_t *img_type_id, u32 bank)
550 {
551 	return fwu_clrset_image_accept(img_type_id, bank,
552 				       IMAGE_ACCEPT_SET);
553 }
554 
555 /**
556  * fwu_clear_accept_image() - Clear the Acceptance bit for the image
557  * @img_type_id: GUID of the image type for which the accepted bit is to be
558  *               cleared
559  * @bank: Bank of which the image's Accept bit is to be cleared
560  *
561  * Clear the accepted bit for the image type specified by the img_type_id parameter.
562  * This function is called after the image has been updated. The accepted bit is
563  * cleared to be set subsequently after passing the image acceptance criteria, by
564  * either the OS(or firmware)
565  *
566  * Return: 0 if OK, -ve on error
567  *
568  */
fwu_clear_accept_image(efi_guid_t * img_type_id,u32 bank)569 int fwu_clear_accept_image(efi_guid_t *img_type_id, u32 bank)
570 {
571 	return fwu_clrset_image_accept(img_type_id, bank,
572 				       IMAGE_ACCEPT_CLEAR);
573 }
574 
575 /**
576  * fwu_plat_get_update_index() - Get the value of the update bank
577  * @update_idx: Bank number to which images are to be updated
578  *
579  * Get the value of the bank(partition) to which the update needs to be
580  * made.
581  *
582  * Note: This is a weak function and platforms can override this with
583  * their own implementation for selection of the update bank.
584  *
585  * Return: 0 if OK, -ve on error
586  *
587  */
fwu_plat_get_update_index(uint * update_idx)588 __weak int fwu_plat_get_update_index(uint *update_idx)
589 {
590 	int ret;
591 	u32 active_idx;
592 
593 	ret = fwu_get_active_index(&active_idx);
594 	if (ret < 0)
595 		return -1;
596 
597 	*update_idx = (active_idx + 1) % CONFIG_FWU_NUM_BANKS;
598 
599 	return ret;
600 }
601 
602 /**
603  * fwu_update_checks_pass() - Check if FWU update can be done
604  *
605  * Check if the FWU update can be executed. The updates are
606  * allowed only when the platform is not in Trial State and
607  * the boot time checks have passed
608  *
609  * Return: 1 if OK, 0 if checks do not pass
610  *
611  */
fwu_update_checks_pass(void)612 u8 fwu_update_checks_pass(void)
613 {
614 	return !in_trial && boottime_check;
615 }
616 
617 /**
618  * fwu_empty_capsule_checks_pass() - Check if empty capsule can be processed
619  *
620  * Check if the empty capsule can be processed to either accept or revert
621  * an earlier executed update. The empty capsules need to be processed
622  * only when the platform is in Trial State and the boot time checks have
623  * passed
624  *
625  * Return: 1 if OK, 0 if not to be allowed
626  *
627  */
fwu_empty_capsule_checks_pass(void)628 u8 fwu_empty_capsule_checks_pass(void)
629 {
630 	return in_trial && boottime_check;
631 }
632 
633 /**
634  * fwu_trial_state_ctr_start() - Start the Trial State counter
635  *
636  * Start the counter to identify the platform booting in the
637  * Trial State. The counter is implemented as an EFI variable.
638  *
639  * Return: 0 if OK, -ve on error
640  *
641  */
fwu_trial_state_ctr_start(void)642 int fwu_trial_state_ctr_start(void)
643 {
644 	int ret;
645 	u16 trial_state_ctr;
646 
647 	trial_state_ctr = 0;
648 	ret = trial_counter_update(&trial_state_ctr);
649 	if (ret)
650 		log_err("Unable to initialise TrialStateCtr\n");
651 
652 	return ret;
653 }
654 
fwu_boottime_checks(void * ctx,struct event * event)655 static int fwu_boottime_checks(void *ctx, struct event *event)
656 {
657 	int ret;
658 	u32 boot_idx, active_idx;
659 	struct udevice *dev;
660 	struct fwu_mdata mdata = { 0 };
661 
662 	/* Don't have boot time checks on sandbox */
663 	if (IS_ENABLED(CONFIG_SANDBOX)) {
664 		boottime_check = 1;
665 		return 0;
666 	}
667 
668 	ret = fwu_check_mdata_validity();
669 	if (ret)
670 		return 0;
671 
672 	/*
673 	 * Get the Boot Index, i.e. the bank from
674 	 * which the platform has booted. This value
675 	 * gets passed from the ealier stage bootloader
676 	 * which booted u-boot, e.g. tf-a. If the
677 	 * boot index is not the same as the
678 	 * active_index read from the FWU metadata,
679 	 * update the active_index.
680 	 */
681 	fwu_plat_get_bootidx(&boot_idx);
682 	if (boot_idx >= CONFIG_FWU_NUM_BANKS) {
683 		log_err("Received incorrect value of boot_index\n");
684 		return 0;
685 	}
686 
687 	ret = fwu_get_active_index(&active_idx);
688 	if (ret) {
689 		log_err("Unable to read active_index\n");
690 		return 0;
691 	}
692 
693 	if (boot_idx != active_idx) {
694 		log_info("Boot idx %u is not matching active idx %u, changing active_idx\n",
695 			 boot_idx, active_idx);
696 		ret = fwu_set_active_index(boot_idx);
697 		if (!ret)
698 			boottime_check = 1;
699 
700 		return 0;
701 	}
702 
703 	if (efi_init_obj_list() != EFI_SUCCESS)
704 		return 0;
705 
706 	ret = fwu_get_dev_mdata(&dev, &mdata);
707 	if (ret)
708 		return ret;
709 
710 	in_trial = in_trial_state(&mdata);
711 	if (!in_trial || (ret = fwu_trial_count_update()) > 0)
712 		ret = trial_counter_update(NULL);
713 
714 	if (!ret)
715 		boottime_check = 1;
716 
717 	return 0;
718 }
719 EVENT_SPY(EVT_MAIN_LOOP, fwu_boottime_checks);
720