+static int stm32l4_protect_same_bank(struct flash_bank *bank, enum stm32_bank_id bank_id, int set,
+ unsigned int first, unsigned int last)
+{
+ unsigned int i;
+
+ /* check if the desired protection is already configured */
+ for (i = first; i <= last; i++) {
+ if (bank->sectors[i].is_protected != set)
+ break;
+ else if (i == last) {
+ LOG_INFO("The specified sectors are already %s", set ? "protected" : "unprotected");
+ return ERROR_OK;
+ }
+ }
+
+ /* all sectors from first to last (or part of them) could have different
+ * protection other than the requested */
+ unsigned int n_wrp;
+ struct stm32l4_wrp wrpxy[4];
+
+ int ret = stm32l4_get_all_wrpxy(bank, bank_id, wrpxy, &n_wrp);
+ if (ret != ERROR_OK)
+ return ret;
+
+ /* use bitmap and range helpers to optimize the WRP usage */
+ DECLARE_BITMAP(pages, bank->num_sectors);
+ bitmap_zero(pages, bank->num_sectors);
+
+ for (i = 0; i < n_wrp; i++) {
+ if (wrpxy[i].used) {
+ for (int p = wrpxy[i].first; p <= wrpxy[i].last; p++)
+ set_bit(p, pages);
+ }
+ }
+
+ /* we have at most 'n_wrp' WRP areas
+ * add one range if the user is trying to protect a fifth range */
+ struct range ranges[n_wrp + 1];
+ unsigned int ranges_count = 0;
+
+ bitmap_to_ranges(pages, bank->num_sectors, ranges, &ranges_count);
+
+ /* pretty-print the currently protected ranges */
+ if (ranges_count > 0) {
+ char *ranges_str = range_print_alloc(ranges, ranges_count);
+ LOG_DEBUG("current protected areas: %s", ranges_str);
+ free(ranges_str);
+ } else
+ LOG_DEBUG("current protected areas: none");
+
+ if (set) { /* flash protect */
+ for (i = first; i <= last; i++)
+ set_bit(i, pages);
+ } else { /* flash unprotect */
+ for (i = first; i <= last; i++)
+ clear_bit(i, pages);
+ }
+
+ /* check the ranges_count after the user request */
+ bitmap_to_ranges(pages, bank->num_sectors, ranges, &ranges_count);
+
+ /* pretty-print the requested areas for protection */
+ if (ranges_count > 0) {
+ char *ranges_str = range_print_alloc(ranges, ranges_count);
+ LOG_DEBUG("requested areas for protection: %s", ranges_str);
+ free(ranges_str);
+ } else
+ LOG_DEBUG("requested areas for protection: none");
+
+ if (ranges_count > n_wrp) {
+ LOG_ERROR("cannot set the requested protection "
+ "(only %u write protection areas are available)" , n_wrp);
+ return ERROR_FAIL;
+ }
+
+ /* re-init all WRPxy as disabled (first > last)*/
+ for (i = 0; i < n_wrp; i++) {
+ wrpxy[i].first = wrpxy[i].offset + 1;
+ wrpxy[i].last = wrpxy[i].offset;
+ }
+
+ /* then configure WRPxy areas */
+ for (i = 0; i < ranges_count; i++) {
+ wrpxy[i].first = ranges[i].start;
+ wrpxy[i].last = ranges[i].end;
+ }
+
+ /* finally write WRPxy registers */
+ return stm32l4_write_all_wrpxy(bank, wrpxy, n_wrp);
+}
+
+static int stm32l4_protect(struct flash_bank *bank, int set, unsigned int first, unsigned int last)