+/*
+ * Take *addr in Flash and adjust it to fall on the end of its sector
+ */
+int flash_sect_roundb (ulong *addr)
+{
+ flash_info_t *info;
+ ulong bank, sector_end_addr;
+ char found;
+ int i;
+
+ /* find the end addr of the sector where the *addr is */
+ found = 0;
+ for (bank = 0; bank < CFG_MAX_FLASH_BANKS && !found; ++bank) {
+ info = &flash_info[bank];
+ for (i = 0; i < info->sector_count && !found; ++i) {
+ /* get the end address of the sector */
+ if (i == info->sector_count - 1) {
+ sector_end_addr = info->start[0] +
+ info->size - 1;
+ } else {
+ sector_end_addr = info->start[i+1] - 1;
+ }
+
+ if (*addr <= sector_end_addr &&
+ *addr >= info->start[i]) {
+ found = 1;
+ /* adjust *addr if necessary */
+ if (*addr < sector_end_addr)
+ *addr = sector_end_addr;
+ } /* sector */
+ } /* bank */
+ }
+ if (!found) {
+ /* error, addres not in flash */
+ printf("Error: end address (0x%08lx) not in flash!\n", *addr);
+ return 1;
+ }
+
+ return 0;
+}
+
+/*
+ * This function computes the start and end addresses for both
+ * erase and protect commands. The range of the addresses on which
+ * either of the commands is to operate can be given in two forms:
+ * 1. <cmd> start end - operate on <'start', 'end')
+ * 2. <cmd> start +length - operate on <'start', start + length)
+ * If the second form is used and the end address doesn't fall on the
+ * sector boundary, than it will be adjusted to the next sector boundary.
+ * If it isn't in the flash, the function will fail (return -1).
+ * Input:
+ * arg1, arg2: address specification (i.e. both command arguments)
+ * Output:
+ * addr_first, addr_last: computed address range
+ * Return:
+ * 1: success
+ * -1: failure (bad format, bad address).
+*/
+static int
+addr_spec(char *arg1, char *arg2, ulong *addr_first, ulong *addr_last)
+{
+ char *ep;
+ char len_used; /* indicates if the "start +length" form used */
+
+ *addr_first = simple_strtoul(arg1, &ep, 16);
+ if (ep == arg1 || *ep != '\0')
+ return -1;
+
+ len_used = 0;
+ if (arg2 && *arg2 == '+'){
+ len_used = 1;
+ ++arg2;
+ }
+
+ *addr_last = simple_strtoul(arg2, &ep, 16);
+ if (ep == arg2 || *ep != '\0')
+ return -1;
+
+ if (len_used){
+ /*
+ * *addr_last has the length, compute correct *addr_last
+ * XXX watch out for the integer overflow! Right now it is
+ * checked for in both the callers.
+ */
+ *addr_last = *addr_first + *addr_last - 1;
+
+ /*
+ * It may happen that *addr_last doesn't fall on the sector
+ * boundary. We want to round such an address to the next
+ * sector boundary, so that the commands don't fail later on.
+ */
+
+ if (flash_sect_roundb(addr_last) > 0)
+ return -1;
+ } /* "start +length" from used */
+
+ return 1;
+}
+