version_rollback.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * Copyright (C) 2017-2020 Alibaba Group Holding Limited
  3. *
  4. * SPDX-License-Identifier: GPL-2.0+
  5. */
  6. #include <common.h>
  7. #include <command.h>
  8. #include <env.h>
  9. static int rollback_part(const char *partition, const char *partition_alt)
  10. {
  11. char *p;
  12. int ret;
  13. int tmp;
  14. p = env_get(partition_alt);
  15. if (p == NULL) {
  16. return 0;
  17. }
  18. tmp = 1;
  19. printf("Rollback partition %s to %s\n", partition, p);
  20. ret = env_set(partition, p);
  21. if (ret) {
  22. printf("Failed to set env %s %s: ret = %d\n", partition, p, ret);
  23. tmp = -1;
  24. }
  25. ret = env_set(partition_alt, NULL);
  26. if (ret) {
  27. printf("Failed to del env %s: ret = %d\n", partition_alt, ret);
  28. tmp = -1;
  29. }
  30. return tmp;
  31. }
  32. static int upgrade_rollback_check(void)
  33. {
  34. unsigned long bootlimit;
  35. unsigned long bootcount;
  36. char *p;
  37. char buf[20];
  38. int ret;
  39. int save;
  40. p = env_get("bootlimit");
  41. if (p == NULL) {
  42. return -1;
  43. }
  44. if (!strcmp(p, "0")) {
  45. return 0;
  46. } else {
  47. if (strict_strtoul(p, 16, &bootlimit) < 0) {
  48. printf("Failed to strict_strtoul bootlimit\n");
  49. return -1;
  50. }
  51. }
  52. p = env_get("bootcount");
  53. if (p == NULL) {
  54. bootcount = 0;
  55. } else if (strict_strtoul(p, 16, &bootcount) < 0) {
  56. bootcount = 0;
  57. }
  58. save = 0;
  59. bootcount++;
  60. if (bootcount == bootlimit + 1) {
  61. save = 1;
  62. printf("Failed to start for %lu times, will rollback!\n", bootlimit);
  63. rollback_part("boot_partition", "boot_partition_alt");
  64. rollback_part("root_partition", "root_partition_alt");
  65. } else if (bootcount < bootlimit + 1) {
  66. save = 1;
  67. }
  68. if (save) {
  69. snprintf(buf, sizeof(buf), "%lu", bootcount);
  70. ret = env_set("bootcount", buf);
  71. if (ret) {
  72. printf("Failed to set env bootcount %s: ret = %d\n", buf, ret);
  73. }
  74. ret = env_save();
  75. if (ret) {
  76. printf("Failed to env_save: ret = %d\n", ret);
  77. }
  78. }
  79. return 0;
  80. }
  81. static int do_rollback(cmd_tbl_t *cmdtp, int flag, int argc,
  82. char * const argv[])
  83. {
  84. upgrade_rollback_check();
  85. return CMD_RET_SUCCESS;
  86. }
  87. U_BOOT_CMD(
  88. rollback, 1, 1, do_rollback,
  89. "Automatic rollback if upgrade fails",
  90. NULL
  91. );