libflashrom,writeprotect: add functions for reading/writing WP configs

New functions are exposed through the libflashrom API for
reading/writing chip's WP settins: `flashrom_wp_{read,write}_cfg()`.

They read/write an opaque `struct flashrom_wp_cfg` instance, which
includes the flash protection range and status register protection mode.

This commit also adds `{read,write}_wp_bits()` helper functions that
read/write chip-specific WP configuration bits.

Tested: flashrom --wp-{enable,disable,range,list,status} at end of patch series

Change-Id: I3ad25708c3321b8fb0216c3eaf6ffc07616537ad
Signed-off-by: Nikolai Artemiev <nartemiev@google.com>
Original-Reviewed-on: https://review.coreboot.org/c/flashrom/+/58479
Original-Reviewed-by: Anastasia Klimchuk <aklm@chromium.org>
Original-Reviewed-by: Edward O'Callaghan <quasisec@chromium.org>
Original-Reviewed-by: Nico Huber <nico.h@gmx.de>
Reviewed-on: https://review.coreboot.org/c/flashrom-stable/+/70968
Reviewed-by: Nico Huber <nico.h@gmx.de>
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
diff --git a/Makefile b/Makefile
index a1d7d8d..c6841bd 100644
--- a/Makefile
+++ b/Makefile
@@ -571,7 +571,7 @@
 CHIP_OBJS = jedec.o stm50.o w39.o w29ee011.o \
 	sst28sf040.o 82802ab.o \
 	sst49lfxxxc.o sst_fwhub.o edi.o flashchips.o spi.o spi25.o spi25_statusreg.o \
-	spi95.o opaque.o sfdp.o en29lv640b.o at45db.o
+	spi95.o opaque.o sfdp.o en29lv640b.o at45db.o writeprotect.o
 
 ###############################################################################
 # Library code.
diff --git a/libflashrom.c b/libflashrom.c
index 51ad7d9..119f81f 100644
--- a/libflashrom.c
+++ b/libflashrom.c
@@ -32,6 +32,7 @@
 #include "hwaccess.h"
 #include "ich_descriptors.h"
 #include "libflashrom.h"
+#include "writeprotect.h"
 
 /**
  * @defgroup flashrom-general General
@@ -649,3 +650,127 @@
 }
 
 /** @} */ /* end flashrom-layout */
+
+
+/**
+ * @defgroup flashrom-wp
+ * @{
+ */
+
+/**
+ * @brief Create a new empty WP configuration.
+ *
+ * @param[out] cfg Points to a pointer of type struct flashrom_wp_cfg that will
+ *                 be set if creation succeeds. *cfg has to be freed by the
+ *                 caller with @ref flashrom_wp_cfg_release.
+ * @return  0 on success
+ *         >0 on failure
+ */
+enum flashrom_wp_result flashrom_wp_cfg_new(struct flashrom_wp_cfg **cfg)
+{
+	*cfg = calloc(1, sizeof(**cfg));
+	return *cfg ? 0 : FLASHROM_WP_ERR_OTHER;
+}
+
+/**
+ * @brief Free a WP configuration.
+ *
+ * @param[out] cfg Pointer to the flashrom_wp_cfg to free.
+ */
+void flashrom_wp_cfg_release(struct flashrom_wp_cfg *cfg)
+{
+	free(cfg);
+}
+
+/**
+ * @brief Set the protection mode for a WP configuration.
+ *
+ * @param[in]  mode The protection mode to set.
+ * @param[out] cfg  Pointer to the flashrom_wp_cfg structure to modify.
+ */
+void flashrom_wp_set_mode(struct flashrom_wp_cfg *cfg, enum flashrom_wp_mode mode)
+{
+	cfg->mode = mode;
+}
+
+/**
+ * @brief Get the protection mode from a WP configuration.
+ *
+ * @param[in] cfg The WP configuration to get the protection mode from.
+ * @return        The configuration's protection mode.
+ */
+enum flashrom_wp_mode flashrom_wp_get_mode(const struct flashrom_wp_cfg *cfg)
+{
+	return cfg->mode;
+}
+
+/**
+ * @brief Set the protection range for a WP configuration.
+ *
+ * @param[out] cfg   Pointer to the flashrom_wp_cfg structure to modify.
+ * @param[in]  start The range's start address.
+ * @param[in]  len   The range's length.
+ */
+void flashrom_wp_set_range(struct flashrom_wp_cfg *cfg, size_t start, size_t len)
+{
+	cfg->range.start = start;
+	cfg->range.len = len;
+}
+
+/**
+ * @brief Get the protection range from a WP configuration.
+ *
+ * @param[out] start Points to a size_t to write the range start to.
+ * @param[out] len   Points to a size_t to write the range length to.
+ * @param[in]  cfg   The WP configuration to get the range from.
+ */
+void flashrom_wp_get_range(size_t *start, size_t *len, const struct flashrom_wp_cfg *cfg)
+{
+	*start = cfg->range.start;
+	*len = cfg->range.len;
+}
+
+/**
+ * @brief Write a WP configuration to a flash chip.
+ *
+ * @param[in] flash The flash context used to access the chip.
+ * @param[in] cfg   The WP configuration to write to the chip.
+ * @return  0 on success
+ *         >0 on failure
+ */
+enum flashrom_wp_result flashrom_wp_write_cfg(struct flashctx *flash, const struct flashrom_wp_cfg *cfg)
+{
+	/*
+	 * TODO: Call custom implementation if the programmer is opaque, as
+	 * direct WP operations require SPI access. In particular, linux_mtd
+	 * has its own WP operations we should use instead.
+	 */
+	if (flash->mst->buses_supported & BUS_SPI)
+		return wp_write_cfg(flash, cfg);
+
+	return FLASHROM_WP_ERR_OTHER;
+}
+
+/**
+ * @brief Read the current WP configuration from a flash chip.
+ *
+ * @param[out] cfg   Pointer to a struct flashrom_wp_cfg to store the chip's
+ *                   configuration in.
+ * @param[in]  flash The flash context used to access the chip.
+ * @return  0 on success
+ *         >0 on failure
+ */
+enum flashrom_wp_result flashrom_wp_read_cfg(struct flashrom_wp_cfg *cfg, struct flashctx *flash)
+{
+	/*
+	 * TODO: Call custom implementation if the programmer is opaque, as
+	 * direct WP operations require SPI access. In particular, linux_mtd
+	 * has its own WP operations we should use instead.
+	 */
+	if (flash->mst->buses_supported & BUS_SPI)
+		return wp_read_cfg(cfg, flash);
+
+	return FLASHROM_WP_ERR_OTHER;
+}
+
+/** @} */ /* end flashrom-wp */
diff --git a/libflashrom.h b/libflashrom.h
index d0d5826..2890d0b 100644
--- a/libflashrom.h
+++ b/libflashrom.h
@@ -1,6 +1,7 @@
 /*
  * This file is part of the flashrom project.
  *
+ * Copyright (C) 2010 Google Inc.
  * Copyright (C) 2012 secunet Security Networks AG
  * (Written by Nico Huber <nico.huber@secunet.com> for secunet)
  *
@@ -117,4 +118,32 @@
 void flashrom_layout_release(struct flashrom_layout *);
 void flashrom_layout_set(struct flashrom_flashctx *, const struct flashrom_layout *);
 
+/** @ingroup flashrom-wp */
+enum flashrom_wp_result {
+	FLASHROM_WP_OK = 0,
+	FLASHROM_WP_ERR_CHIP_UNSUPPORTED = 1,
+	FLASHROM_WP_ERR_OTHER = 2,
+	FLASHROM_WP_ERR_READ_FAILED = 3,
+	FLASHROM_WP_ERR_WRITE_FAILED = 4,
+	FLASHROM_WP_ERR_VERIFY_FAILED = 5
+};
+
+enum flashrom_wp_mode {
+	FLASHROM_WP_MODE_DISABLED,
+	FLASHROM_WP_MODE_HARDWARE,
+	FLASHROM_WP_MODE_POWER_CYCLE,
+	FLASHROM_WP_MODE_PERMANENT
+};
+struct flashrom_wp_cfg;
+
+enum flashrom_wp_result flashrom_wp_cfg_new(struct flashrom_wp_cfg **);
+void flashrom_wp_cfg_release(struct flashrom_wp_cfg *);
+void flashrom_wp_set_mode(struct flashrom_wp_cfg *, enum flashrom_wp_mode);
+enum flashrom_wp_mode flashrom_wp_get_mode(const struct flashrom_wp_cfg *);
+void flashrom_wp_set_range(struct flashrom_wp_cfg *, size_t start, size_t len);
+void flashrom_wp_get_range(size_t *start, size_t *len, const struct flashrom_wp_cfg *);
+
+enum flashrom_wp_result flashrom_wp_read_cfg(struct flashrom_wp_cfg *, struct flashrom_flashctx *);
+enum flashrom_wp_result flashrom_wp_write_cfg(struct flashrom_flashctx *, const struct flashrom_wp_cfg *);
+
 #endif				/* !__LIBFLASHROM_H__ */
diff --git a/meson.build b/meson.build
index 375089c..a9043c6 100644
--- a/meson.build
+++ b/meson.build
@@ -333,6 +333,7 @@
 srcs += 'udelay.c'
 srcs += 'w29ee011.c'
 srcs += 'w39.c'
+srcs += 'writeprotect.c'
 
 mapfile = 'libflashrom.map'
 vflag = '-Wl,--version-script,@0@/@1@'.format(meson.current_source_dir(), mapfile)
diff --git a/writeprotect.c b/writeprotect.c
new file mode 100644
index 0000000..5f47bc0
--- /dev/null
+++ b/writeprotect.c
@@ -0,0 +1,214 @@
+/*
+ * This file is part of the flashrom project.
+ *
+ * Copyright (C) 2010 Google Inc.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "flash.h"
+#include "libflashrom.h"
+#include "chipdrivers.h"
+#include "writeprotect.h"
+
+/** Read and extract a single bit from the chip's registers */
+static enum flashrom_wp_result read_bit(uint8_t *value, bool *present, struct flashctx *flash, struct reg_bit_info bit)
+{
+	*present = bit.reg != INVALID_REG;
+	if (*present) {
+		if (spi_read_register(flash, bit.reg, value))
+			return FLASHROM_WP_ERR_READ_FAILED;
+		*value = (*value >> bit.bit_index) & 1;
+	} else {
+		/* Zero bit, it may be used by compare_ranges(). */
+		*value = 0;
+	}
+
+	return FLASHROM_WP_OK;
+}
+
+/** Read all WP configuration bits from the chip's registers. */
+static enum flashrom_wp_result read_wp_bits(struct wp_bits *bits, struct flashctx *flash)
+{
+	/*
+	 * For each WP bit that is included in the chip's register layout, read
+	 * the register that contains it, extracts the bit's value, and assign
+	 * it to the appropriate field in the wp_bits structure.
+	 */
+	const struct reg_bit_map *bit_map = &flash->chip->reg_bits;
+	bool ignored;
+	size_t i;
+	enum flashrom_wp_result ret;
+
+	ret = read_bit(&bits->tb,  &bits->tb_bit_present,  flash, bit_map->tb);
+	if (ret != FLASHROM_WP_OK)
+		return ret;
+
+	ret = read_bit(&bits->sec, &bits->sec_bit_present, flash, bit_map->sec);
+	if (ret != FLASHROM_WP_OK)
+		return ret;
+
+	ret = read_bit(&bits->cmp, &bits->cmp_bit_present, flash, bit_map->cmp);
+	if (ret != FLASHROM_WP_OK)
+		return ret;
+
+	ret = read_bit(&bits->srp, &bits->srp_bit_present, flash, bit_map->srp);
+	if (ret != FLASHROM_WP_OK)
+		return ret;
+
+	ret = read_bit(&bits->srl, &bits->srl_bit_present, flash, bit_map->srl);
+	if (ret != FLASHROM_WP_OK)
+		return ret;
+
+	for (i = 0; i < ARRAY_SIZE(bits->bp); i++) {
+		if (bit_map->bp[i].reg == INVALID_REG)
+			break;
+
+		bits->bp_bit_count = i + 1;
+		ret = read_bit(&bits->bp[i], &ignored, flash, bit_map->bp[i]);
+		if (ret != FLASHROM_WP_OK)
+			return ret;
+	}
+
+	return ret;
+}
+
+/** Helper function for write_wp_bits(). */
+static void set_reg_bit(
+		uint8_t *reg_values, uint8_t *write_masks,
+		struct reg_bit_info bit, uint8_t value)
+{
+	if (bit.reg != INVALID_REG) {
+		reg_values[bit.reg] |= value << bit.bit_index;
+		write_masks[bit.reg] |= 1 << bit.bit_index;
+	}
+}
+
+/** Write WP configuration bits to the flash's registers. */
+static enum flashrom_wp_result write_wp_bits(struct flashctx *flash, struct wp_bits bits)
+{
+	size_t i;
+	enum flash_reg reg;
+	const struct reg_bit_map *reg_bits = &flash->chip->reg_bits;
+
+	/* Convert wp_bits to register values and write masks */
+	uint8_t reg_values[MAX_REGISTERS] = {0};
+	uint8_t write_masks[MAX_REGISTERS] = {0};
+
+	for (i = 0; i < bits.bp_bit_count; i++)
+		set_reg_bit(reg_values, write_masks, reg_bits->bp[i], bits.bp[i]);
+
+	set_reg_bit(reg_values, write_masks, reg_bits->tb,  bits.tb);
+	set_reg_bit(reg_values, write_masks, reg_bits->sec, bits.sec);
+	set_reg_bit(reg_values, write_masks, reg_bits->cmp, bits.cmp);
+	set_reg_bit(reg_values, write_masks, reg_bits->srp, bits.srp);
+	set_reg_bit(reg_values, write_masks, reg_bits->srl, bits.srl);
+
+	/* Write each register */
+	for (reg = STATUS1; reg < MAX_REGISTERS; reg++) {
+		if (!write_masks[reg])
+			continue;
+
+		uint8_t value;
+		if (spi_read_register(flash, reg, &value))
+			return FLASHROM_WP_ERR_READ_FAILED;
+
+		value = (value & ~write_masks[reg]) | (reg_values[reg] & write_masks[reg]);
+
+		if (spi_write_register(flash, reg, value))
+			return FLASHROM_WP_ERR_WRITE_FAILED;
+	}
+
+	/* Verify each register */
+	for (reg = STATUS1; reg < MAX_REGISTERS; reg++) {
+		if (!write_masks[reg])
+			continue;
+
+		uint8_t value;
+		if (spi_read_register(flash, reg, &value))
+			return FLASHROM_WP_ERR_READ_FAILED;
+
+		uint8_t actual = value & write_masks[reg];
+		uint8_t expected = reg_values[reg] & write_masks[reg];
+
+		if (actual != expected)
+			return FLASHROM_WP_ERR_VERIFY_FAILED;
+	}
+
+	return FLASHROM_WP_OK;
+}
+
+static bool chip_supported(struct flashctx *flash)
+{
+	return false;
+}
+
+enum flashrom_wp_result wp_read_cfg(struct flashrom_wp_cfg *cfg, struct flashctx *flash)
+{
+	struct wp_bits bits;
+	enum flashrom_wp_result ret = FLASHROM_WP_OK;
+
+	if (!chip_supported(flash))
+		ret = FLASHROM_WP_ERR_CHIP_UNSUPPORTED;
+
+	if (ret == FLASHROM_WP_OK)
+		ret = read_wp_bits(&bits, flash);
+
+	/* TODO: implement get_wp_range() and get_wp_mode() and call them */
+	/*
+	if (ret == FLASHROM_WP_OK)
+		ret = get_wp_range(&cfg->range, flash, &bits);
+
+	if (ret == FLASHROM_WP_OK)
+		ret = get_wp_mode(&cfg->mode, &bits);
+	*/
+
+	return ret;
+}
+
+enum flashrom_wp_result wp_write_cfg(struct flashctx *flash, const struct flashrom_wp_cfg *cfg)
+{
+	struct wp_bits bits;
+	enum flashrom_wp_result ret = FLASHROM_WP_OK;
+
+	if (!chip_supported(flash))
+		ret = FLASHROM_WP_ERR_CHIP_UNSUPPORTED;
+
+	if (ret == FLASHROM_WP_OK)
+		ret = read_wp_bits(&bits, flash);
+
+	/* Set protection range */
+	/* TODO: implement set_wp_range() and use it */
+	/*
+	if (ret == FLASHROM_WP_OK)
+		ret = set_wp_range(&bits, flash, cfg->range);
+	if (ret == FLASHROM_WP_OK)
+		ret = write_wp_bits(flash, bits);
+	*/
+
+	/* Set protection mode */
+	/* TODO: implement set_wp_mode() and use it */
+	/*
+	if (ret == FLASHROM_WP_OK)
+		ret = set_wp_mode(&bits, cfg->mode);
+	*/
+	if (ret == FLASHROM_WP_OK)
+		ret = write_wp_bits(flash, bits);
+
+	return ret;
+}
+
+/** @} */ /* end flashrom-wp */
diff --git a/writeprotect.h b/writeprotect.h
index 2f473f7..d54befa 100644
--- a/writeprotect.h
+++ b/writeprotect.h
@@ -22,8 +22,21 @@
 #include <stdbool.h>
 #include <stddef.h>
 
+#include "libflashrom.h"
+
 #define MAX_BP_BITS 4
 
+/* Chip protection range: start address and length. */
+struct wp_range {
+        size_t start, len;
+};
+
+/* Generic description of a chip's write protection configuration. */
+struct flashrom_wp_cfg {
+        enum flashrom_wp_mode mode;
+        struct wp_range range;
+};
+
 /*
  * Description of a chip's write protection configuration.
  *
@@ -56,4 +69,12 @@
 	uint8_t bp[MAX_BP_BITS];
 };
 
+struct flashrom_flashctx;
+
+/* Write WP configuration to the chip */
+enum flashrom_wp_result wp_write_cfg(struct flashrom_flashctx *, const struct flashrom_wp_cfg *);
+
+/* Read WP configuration from the chip */
+enum flashrom_wp_result wp_read_cfg(struct flashrom_wp_cfg *, struct flashrom_flashctx *);
+
 #endif /* !__WRITEPROTECT_H__ */