Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > linux.kernel > #1370169 > unrolled thread

[PATCH 0/8] Replay Protected Memory Block (RPMB) subsystem

Started byTomas Winkler <tomas.winkler@intel.com>
First post2016-04-03 11:50 +0200
Last post2016-04-03 21:30 +0200
Articles 10 — 5 participants

Back to article view | Back to linux.kernel


Contents

  [PATCH 0/8] Replay Protected Memory Block (RPMB) subsystem Tomas Winkler <tomas.winkler@intel.com> - 2016-04-03 11:50 +0200
    [PATCH 4/8] char: rpmb: provide user space interface Tomas Winkler <tomas.winkler@intel.com> - 2016-04-03 11:50 +0200
      [PATCH] char: rpmb: fix memdup_user.cocci warnings kbuild test robot <lkp@intel.com> - 2016-04-03 12:40 +0200
      Re: [PATCH 4/8] char: rpmb: provide user space interface kbuild test robot <lkp@intel.com> - 2016-04-03 12:40 +0200
    [PATCH 8/8] scsi: ufs: connect to RPMB subsystem Tomas Winkler <tomas.winkler@intel.com> - 2016-04-03 11:50 +0200
      Re: [PATCH 8/8] scsi: ufs: connect to RPMB subsystem Joao Pinto <Joao.Pinto@synopsys.com> - 2016-04-04 12:40 +0200
        RE: [PATCH 8/8] scsi: ufs: connect to RPMB subsystem "Winkler, Tomas" <tomas.winkler@intel.com> - 2016-04-04 12:40 +0200
    [PATCH 6/8] tools rpmb: add RPBM access tool Tomas Winkler <tomas.winkler@intel.com> - 2016-04-03 11:50 +0200
    Re: [PATCH 0/8] Replay Protected Memory Block (RPMB) subsystem Andy Lutomirski <luto@kernel.org> - 2016-04-03 15:30 +0200
      RE: [PATCH 0/8] Replay Protected Memory Block (RPMB) subsystem "Winkler, Tomas" <tomas.winkler@intel.com> - 2016-04-03 21:30 +0200

#1370169 — [PATCH 0/8] Replay Protected Memory Block (RPMB) subsystem

FromTomas Winkler <tomas.winkler@intel.com>
Date2016-04-03 11:50 +0200
Subject[PATCH 0/8] Replay Protected Memory Block (RPMB) subsystem
Message-ID<rjMPp-1o7-7@gated-at.bofh.it>
Few storage technology such is EMMC, UFS, and NVMe support RPMB
hardware partition with common protocol and frame layout.
The RPMB partition cannot be accessed via standard block layer, but
by a set of specific commands: WRITE, READ, GET_WRITE_COUNTER, and
PROGRAM_KEY.
Such a partition provides authenticated and replay protected access,
hence suitable as a secure storage.

A storage device registers its RPMB hardware (emmc) partition or
RPMB W-LUN (ufs) with the RPMB layer providing an implementation for
send_rpmb_req() handler.
Tere is as well simulation platform device. This is handy as an RPMB
key can be programmed only once at storage device lifetime.

The RPMB layer aims to provide in-kernel API for Trusted Execution
Environment (TEE) devices that are capable to securely compute block
frame signature. A TEE driver can claim rpmb interface, for example,
via  class_interface_register ().

A parallel user space API is provided via /dev/rpmbX character
device with a single IOCTL command similar to the one provided by
mmc/ioctl. h
There is a sample tool under tools/rpmb/ directory that exercises
this interface.

Tomas Winkler (8):
  rpmb: add Replay Protected Memory Block (RPMB) subsystem
  char: rpmb: add sysfs-class ABI documentation
  char: rpmb: add device attributes
  char: rpmb: provide user space interface
  char: rpmb: add RPMB simulation device
  tools rpmb: add RPBM access tool
  mmc: block: register rpmb partition with the RPMB subsystem
  scsi: ufs: connect to RPMB subsystem

 Documentation/ABI/testing/sysfs-class-rpmb |  39 ++
 Documentation/ioctl/ioctl-number.txt       |   1 +
 MAINTAINERS                                |  10 +
 drivers/char/Kconfig                       |   2 +
 drivers/char/Makefile                      |   1 +
 drivers/char/rpmb/Kconfig                  |  25 +
 drivers/char/rpmb/Makefile                 |   6 +
 drivers/char/rpmb/cdev.c                   | 209 ++++++++
 drivers/char/rpmb/core.c                   | 408 +++++++++++++++
 drivers/char/rpmb/rpmb-cdev.h              |  31 ++
 drivers/char/rpmb/rpmb_sim.c               | 584 +++++++++++++++++++++
 drivers/mmc/card/block.c                   | 289 +++++++++++
 drivers/scsi/ufs/ufshcd.c                  | 219 ++++++++
 drivers/scsi/ufs/ufshcd.h                  |   2 +
 include/linux/rpmb.h                       | 138 +++++
 include/uapi/linux/rpmb.h                  | 120 +++++
 tools/Makefile                             |  16 +-
 tools/rpmb/.gitignore                      |   2 +
 tools/rpmb/Makefile                        |  32 ++
 tools/rpmb/rpmb.c                          | 807 +++++++++++++++++++++++++++++
 20 files changed, 2936 insertions(+), 5 deletions(-)
 create mode 100644 Documentation/ABI/testing/sysfs-class-rpmb
 create mode 100644 drivers/char/rpmb/Kconfig
 create mode 100644 drivers/char/rpmb/Makefile
 create mode 100644 drivers/char/rpmb/cdev.c
 create mode 100644 drivers/char/rpmb/core.c
 create mode 100644 drivers/char/rpmb/rpmb-cdev.h
 create mode 100644 drivers/char/rpmb/rpmb_sim.c
 create mode 100644 include/linux/rpmb.h
 create mode 100644 include/uapi/linux/rpmb.h
 create mode 100644 tools/rpmb/.gitignore
 create mode 100644 tools/rpmb/Makefile
 create mode 100644 tools/rpmb/rpmb.c

-- 
2.4.3

[toc] | [next] | [standalone]


#1370170 — [PATCH 4/8] char: rpmb: provide user space interface

FromTomas Winkler <tomas.winkler@intel.com>
Date2016-04-03 11:50 +0200
Subject[PATCH 4/8] char: rpmb: provide user space interface
Message-ID<rjMPp-1o7-29@gated-at.bofh.it>
In reply to#1370169
The user space API is achieved via single synchronous IOCTL.
The request is submitted in_frames_ptr pointer and received
in out_frames_ptr.

Signed-off-by: Tomas Winkler <tomas.winkler@intel.com>
---
 Documentation/ioctl/ioctl-number.txt |   1 +
 MAINTAINERS                          |   1 +
 drivers/char/rpmb/Kconfig            |   7 ++
 drivers/char/rpmb/Makefile           |   1 +
 drivers/char/rpmb/cdev.c             | 209 +++++++++++++++++++++++++++++++++++
 drivers/char/rpmb/core.c             |   9 +-
 drivers/char/rpmb/rpmb-cdev.h        |  31 ++++++
 include/linux/rpmb.h                 |  78 ++-----------
 include/uapi/linux/rpmb.h            | 120 ++++++++++++++++++++
 9 files changed, 386 insertions(+), 71 deletions(-)
 create mode 100644 drivers/char/rpmb/cdev.c
 create mode 100644 drivers/char/rpmb/rpmb-cdev.h
 create mode 100644 include/uapi/linux/rpmb.h

diff --git a/Documentation/ioctl/ioctl-number.txt b/Documentation/ioctl/ioctl-number.txt
index 9369d3b0f09a..51a514befa48 100644
--- a/Documentation/ioctl/ioctl-number.txt
+++ b/Documentation/ioctl/ioctl-number.txt
@@ -320,6 +320,7 @@ Code  Seq#(hex)	Include File		Comments
 0xB1	00-1F	PPPoX			<mailto:mostrows@styx.uwaterloo.ca>
 0xB3	00	linux/mmc/ioctl.h
 0xB4	00-0F	linux/gpio.h		<mailto:linux-gpio@vger.kernel.org>
+0xB5	00	linux/uapi/linux/rpmb.h <mailto:linux-mei@linux.intel.com>
 0xC0	00-0F	linux/usb/iowarrior.h
 0xCA	00-0F	uapi/misc/cxl.h
 0xCA	80-8F	uapi/scsi/cxlflash_ioctl.h
diff --git a/MAINTAINERS b/MAINTAINERS
index 08316d8284ed..8704b40eaf27 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -9429,6 +9429,7 @@ M:	Tomas Winkler <tomas.winkler@intel.com>
 L:	linux-kernel@vger.kernel.org
 S:	Supported
 F:	drivers/char/rpmb/*
+F:	include/uapi/linux/rpmb.h
 F:	include/linux/rpmb.h
 F:	Documentation/ABI/testing/sysfs-class-rpmb
 
diff --git a/drivers/char/rpmb/Kconfig b/drivers/char/rpmb/Kconfig
index c5e6e909efce..6794be9fcc5e 100644
--- a/drivers/char/rpmb/Kconfig
+++ b/drivers/char/rpmb/Kconfig
@@ -6,3 +6,10 @@ config RPMB
 	  access RPMB partition.
 
 	  If unsure, select N.
+
+config RPMB_INTF_DEV
+	bool "RPMB character device interface /dev/rpmbN"
+	depends on RPMB
+	help
+	  Say yes here if you want to access RPMB from user space
+	  via character device interface /dev/rpmb%d
diff --git a/drivers/char/rpmb/Makefile b/drivers/char/rpmb/Makefile
index 812b3ed264c0..b5dc087b1299 100644
--- a/drivers/char/rpmb/Makefile
+++ b/drivers/char/rpmb/Makefile
@@ -1,4 +1,5 @@
 obj-$(CONFIG_RPMB) += rpmb.o
 rpmb-objs += core.o
+rpmb-$(CONFIG_RPMB_INTF_DEV) += cdev.o
 
 ccflags-y += -D__CHECK_ENDIAN__
diff --git a/drivers/char/rpmb/cdev.c b/drivers/char/rpmb/cdev.c
new file mode 100644
index 000000000000..a57c08fce70a
--- /dev/null
+++ b/drivers/char/rpmb/cdev.c
@@ -0,0 +1,209 @@
+/*
+ * Copyright (C) 2015-2016 Intel Corp. All rights reserved
+ *
+ * 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; version 2 of the License.
+ *
+ * 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.
+ */
+
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
+#include <linux/module.h>
+#include <linux/fs.h>
+#include <linux/uaccess.h>
+#include <linux/compat.h>
+#include <linux/slab.h>
+#include <linux/rpmb.h>
+
+#include "rpmb-cdev.h"
+
+static dev_t rpmb_devt;
+#define RPMB_MAX_DEVS  MINORMASK
+
+#define RPMB_DEV_OPEN    0  /** single open bit (position) */
+
+/**
+ * rpmb_open - the open function
+ *
+ * @inode: pointer to inode structure
+ * @file: pointer to file structure
+ *
+ * Return: 0 on success, <0 on error
+ */
+static int rpmb_open(struct inode *inode, struct file *file)
+{
+	struct rpmb_dev *rdev;
+
+	rdev = container_of(inode->i_cdev, struct rpmb_dev, cdev);
+	if (!rdev)
+		return -ENODEV;
+
+	/* the rpmb is single open! */
+	if (test_and_set_bit(RPMB_DEV_OPEN, &rdev->status))
+		return -EBUSY;
+
+	mutex_lock(&rdev->lock);
+
+	file->private_data = rdev;
+
+	mutex_unlock(&rdev->lock);
+
+	return nonseekable_open(inode, file);
+}
+
+static int rpmb_release(struct inode *inode, struct file *file)
+{
+	struct rpmb_dev *rdev = file->private_data;
+
+	clear_bit(RPMB_DEV_OPEN, &rdev->status);
+
+	return 0;
+}
+
+/*
+ * FIMXE: will be exported by the kernel in future version
+ * helper to convert user pointers passed inside __aligned_u64 fields
+ */
+static void __user *u64_to_ptr(__u64 val)
+{
+	return (void __user *) (unsigned long) val;
+}
+
+static int rpmb_ioctl_cmd(struct rpmb_dev *rdev,
+			  struct rpmb_ioc_cmd __user *ptr)
+{
+	struct rpmb_ioc_cmd cmd;
+	struct rpmb_data rpmbd;
+	struct rpmb_frame *in_frames = NULL;
+	struct rpmb_frame *out_frames = NULL;
+	size_t in_sz, out_sz;
+	int ret;
+
+	if (copy_from_user(&cmd, ptr, sizeof(cmd)))
+		return -EFAULT;
+
+	if (cmd.in_frames_count == 0 || cmd.out_frames_count == 0)
+		return -EINVAL;
+
+	in_sz = sizeof(struct rpmb_frame) * cmd.in_frames_count;
+	in_frames = kmalloc(in_sz, GFP_KERNEL);
+	if (!in_frames)
+		return -ENOMEM;
+
+	if (copy_from_user(in_frames, u64_to_ptr(cmd.in_frames_ptr), in_sz)) {
+		ret = -EINVAL;
+		goto out;
+	}
+
+	out_sz = sizeof(struct rpmb_frame) * cmd.out_frames_count;
+	out_frames = kmalloc(out_sz, GFP_KERNEL);
+	if (!out_frames) {
+		ret = -ENOMEM;
+		goto out;
+	}
+
+	rpmbd.req_type = cmd.req;
+	rpmbd.in_frames = in_frames;
+	rpmbd.out_frames = out_frames;
+	rpmbd.in_frames_cnt = cmd.in_frames_count;
+	rpmbd.out_frames_cnt = cmd.out_frames_count;
+
+	ret  = rpmb_send_req(rdev, &rpmbd);
+	if (ret) {
+		dev_err(&rdev->dev, "Failed to process request = %d.\n", ret);
+		goto out;
+	}
+
+	if (copy_to_user(u64_to_ptr(cmd.out_frames_ptr), out_frames, out_sz)) {
+		ret = -EFAULT;
+		goto out;
+	}
+
+	if (copy_to_user(ptr, &cmd, sizeof(cmd))) {
+		ret = -EFAULT;
+		goto out;
+	}
+out:
+	kfree(in_frames);
+	kfree(out_frames);
+	return ret;
+}
+
+static long rpmb_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
+{
+	struct rpmb_dev *rdev = file->private_data;
+	struct rpmb_ioc_cmd __user *req = (void __user *)arg;
+
+	if (cmd != RPMB_IOC_REQ) {
+		dev_err(&rdev->dev, "unsupported ioctl 0x%x.\n", cmd);
+		return -ENOIOCTLCMD;
+	}
+
+	return rpmb_ioctl_cmd(rdev, req);
+}
+
+#ifdef CONFIG_COMPAT
+static long compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
+{
+	struct rpmb_dev *rdev = file->private_data;
+	struct rpmb_ioc_cmd __user *req = (void __user *)compat_ptr(arg);
+
+	if (cmd != RPMB_IOC_REQ) {
+		dev_err(&rdev->dev, "unsupported ioctl 0x%x.\n", cmd);
+		return -ENOIOCTLCMD;
+	}
+
+	return rpmb_ioctl_cmd(rdev, req);
+}
+#endif /* CONFIG_COMPAT */
+
+static const struct file_operations rpmb_fops = {
+	.open           = rpmb_open,
+	.release        = rpmb_release,
+	.unlocked_ioctl = rpmb_ioctl,
+#ifdef CONFIG_COMPAT
+	.compat_ioctl   = compat_ioctl,
+#endif
+	.owner          = THIS_MODULE,
+	.llseek         = noop_llseek,
+};
+
+void rpmb_cdev_prepare(struct rpmb_dev *rdev)
+{
+	rdev->dev.devt = MKDEV(MAJOR(rpmb_devt), rdev->id);
+	rdev->cdev.owner = THIS_MODULE;
+	cdev_init(&rdev->cdev, &rpmb_fops);
+}
+
+void rpmb_cdev_add(struct rpmb_dev *rdev)
+{
+	cdev_add(&rdev->cdev, rdev->dev.devt, 1);
+}
+
+void rpmb_cdev_del(struct rpmb_dev *rdev)
+{
+	if (rdev->dev.devt)
+		cdev_del(&rdev->cdev);
+}
+
+int __init rpmb_cdev_init(void)
+{
+	int ret;
+
+	ret = alloc_chrdev_region(&rpmb_devt, 0, RPMB_MAX_DEVS, "rpmb");
+	if (ret < 0)
+		pr_err("unable to allocate char dev region\n");
+
+	return ret;
+}
+
+void __exit rpmb_cdev_exit(void)
+{
+	if (rpmb_devt)
+		unregister_chrdev_region(rpmb_devt, RPMB_MAX_DEVS);
+}
diff --git a/drivers/char/rpmb/core.c b/drivers/char/rpmb/core.c
index fb401331d345..ce875d773ee4 100644
--- a/drivers/char/rpmb/core.c
+++ b/drivers/char/rpmb/core.c
@@ -20,6 +20,7 @@
 #include <linux/slab.h>
 
 #include <linux/rpmb.h>
+#include "rpmb-cdev.h"
 
 static DEFINE_IDA(rpmb_ida);
 
@@ -313,6 +314,7 @@ int rpmb_dev_unregister(struct device *dev)
 	rpmb_dev_put(rdev);
 
 	mutex_lock(&rdev->lock);
+	rpmb_cdev_del(rdev);
 	device_del(&rdev->dev);
 	mutex_unlock(&rdev->lock);
 
@@ -364,10 +366,14 @@ struct rpmb_dev *rpmb_dev_register(struct device *dev,
 	rdev->dev.parent = dev;
 	rdev->dev.groups = rpmb_attr_groups;
 
+	rpmb_cdev_prepare(rdev);
+
 	ret = device_register(&rdev->dev);
 	if (ret)
 		goto exit;
 
+	rpmb_cdev_add(rdev);
+
 	dev_dbg(&rdev->dev, "registered disk\n");
 
 	return rdev;
@@ -384,11 +390,12 @@ static int __init rpmb_init(void)
 {
 	ida_init(&rpmb_ida);
 	class_register(&rpmb_class);
-	return 0;
+	return rpmb_cdev_init();
 }
 
 static void __exit rpmb_exit(void)
 {
+	rpmb_cdev_exit();
 	class_unregister(&rpmb_class);
 	ida_destroy(&rpmb_ida);
 }
diff --git a/drivers/char/rpmb/rpmb-cdev.h b/drivers/char/rpmb/rpmb-cdev.h
new file mode 100644
index 000000000000..d20e0f16f1a1
--- /dev/null
+++ b/drivers/char/rpmb/rpmb-cdev.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2015-2016 Intel Corp. All rights reserved
+ *
+ * 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; version 2 of the License.
+ *
+ * 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.
+ */
+
+
+#ifdef CONFIG_RPMB_INTF_DEV
+int __init rpmb_cdev_init(void);
+void __exit rpmb_cdev_exit(void);
+void rpmb_cdev_prepare(struct rpmb_dev *rdev);
+void rpmb_cdev_add(struct rpmb_dev *rdev);
+void rpmb_cdev_del(struct rpmb_dev *rdev);
+
+#else
+static inline int __init rpmb_cdev_init(void)
+{
+	return 0;
+}
+static inline void __exit rpmb_cdev_exit(void) {}
+static inline void rpmb_cdev_prepare(struct rpmb_dev *rdev) {}
+static inline void rpmb_cdev_add(struct rpmb_dev *rdev) {}
+static inline void rpmb_cdev_del(struct rpmb_dev *rdev) {}
+#endif /* CONFIG_RPMB_INTF_DEV */
diff --git a/include/linux/rpmb.h b/include/linux/rpmb.h
index 2c1e259f1a04..446c6639d275 100644
--- a/include/linux/rpmb.h
+++ b/include/linux/rpmb.h
@@ -15,79 +15,11 @@
 
 #include <linux/types.h>
 #include <linux/device.h>
+#include <linux/cdev.h>
+#include <uapi/linux/rpmb.h>
 #include <linux/kref.h>
 
 /**
- * struct rpmb_frame - rpmb frame as defined by specs
- *
- * @stuff        : stuff bytes
- * @key_mac      : The authentication key or the message authentication
- *                 code (MAC) depending on the request/response type.
- *                 The MAC will be delivered in the last (or the only)
- *                 block of data.
- * @data         : Data to be written or read by signed access.
- * @nonce        : Random number generated by the host for the requests
- *                 and copied to the response by the RPMB engine.
- * @write_counter: Counter value for the total amount of the successful
- *                 authenticated data write requests made by the host.
- * @addr         : Address of the data to be programmed to or read
- *                 from the RPMB. Address is the serial number of
- *                 the accessed block (half sector 256B).
- * @block_count  : Number of blocks (half sectors, 256B) requested to be
- *                 read/programmed.
- * @result       : Includes information about the status of the write counter
- *                 (valid, expired) and result of the access made to the RPMB.
- * @req_resp     : Defines the type of request and response to/from the memory.
- */
-struct rpmb_frame {
-	u8     stuff[196];
-	u8     key_mac[32];
-	u8     data[256];
-	u8     nonce[16];
-	__be32 write_counter;
-	__be16 addr;
-	__be16 block_count;
-	__be16 result;
-	__be16 req_resp;
-} __packed;
-
-#define RPMB_PROGRAM_KEY       0x1    /* Program RPMB Authentication Key */
-#define RPMB_GET_WRITE_COUNTER 0x2    /* Read RPMB write counter */
-#define RPMB_WRITE_DATA        0x3    /* Write data to RPMB partition */
-#define RPMB_READ_DATA         0x4    /* Read data from RPMB partition */
-#define RPMB_RESULT_READ       0x5    /* Read result request  (Internal) */
-
-#define RPMB_REQ2RESP(_OP) ((_OP) << 8)
-#define RPMB_RESP2REQ(_OP) ((_OP) >> 8)
-
-/**
- * enum rpmb_op_result - rpmb operation results
- *
- * @RPMB_ERR_OK      : operation successful
- * @RPMB_ERR_GENERAL : general failure
- * @RPMB_ERR_AUTH    : mac doesn't match or ac calculation failure
- * @RPMB_ERR_COUNTER : counter doesn't match or counter increment failure
- * @RPMB_ERR_ADDRESS : address out of range or wrong address alignment
- * @RPMB_ERR_WRITE   : data, counter, or result write failure
- * @RPMB_ERR_READ    : data, counter, or result read failure
- * @RPMB_ERR_NO_KEY  : authentication key not yet programmed
- *
- * @RPMB_ERR_COUNTER_EXPIRED:  counter expired
- */
-enum rpmb_op_result {
-	RPMB_ERR_OK      = 0x0000,
-	RPMB_ERR_GENERAL = 0x0001,
-	RPMB_ERR_AUTH    = 0x0002,
-	RPMB_ERR_COUNTER = 0x0003,
-	RPMB_ERR_ADDRESS = 0x0004,
-	RPMB_ERR_WRITE   = 0x0005,
-	RPMB_ERR_READ    = 0x0006,
-	RPMB_ERR_NO_KEY  = 0x0007,
-
-	RPMB_ERR_COUNTER_EXPIRED = 0x0080
-};
-
-/**
  * enum rpmb_type - type of underlaying storage technology
  *
  * @RPMB_TYPE_ANY   : any type used for search only
@@ -144,12 +76,18 @@ struct rpmb_ops {
  * @lock       : lock
  * @dev        : device
  * @id         : device id
+ * @cdev       : character dev
+ * @status     : device status
  * @ops        : operation exported by block layer
  */
 struct rpmb_dev {
 	struct mutex lock;
 	struct device dev;
 	int    id;
+#ifdef CONFIG_RPMB_INTF_DEV
+	struct cdev cdev;
+	unsigned long status;
+#endif /* CONFIG_RPMB_INTF_DEV */
 	const struct rpmb_ops *ops;
 };
 
diff --git a/include/uapi/linux/rpmb.h b/include/uapi/linux/rpmb.h
new file mode 100644
index 000000000000..55aa92e11280
--- /dev/null
+++ b/include/uapi/linux/rpmb.h
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2015-2016, Intel Corp.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License version
+ * 2 as published by the Free Software Foundation;
+ *
+ * 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.
+ */
+
+#ifndef _UAPI_LINUX_RPMB_H_
+#define _UAPI_LINUX_RPMB_H_
+
+#include <linux/types.h>
+
+/**
+ * struct rpmb_frame - rpmb frame as defined by specs
+ *
+ * @stuff        : stuff bytes
+ * @key_mac      : The authentication key or the message authentication
+ *                 code (MAC) depending on the request/response type.
+ *                 The MAC will be delivered in the last (or the only)
+ *                 block of data.
+ * @data         : Data to be written or read by signed access.
+ * @nonce        : Random number generated by the host for the requests
+ *                 and copied to the response by the RPMB engine.
+ * @write_counter: Counter value for the total amount of the successful
+ *                 authenticated data write requests made by the host.
+ * @addr         : Address of the data to be programmed to or read
+ *                 from the RPMB. Address is the serial number of
+ *                 the accessed block (half sector 256B).
+ * @block_count  : Number of blocks (half sectors, 256B) requested to be
+ *                 read/programmed.
+ * @result       : Includes information about the status of the write counter
+ *                 (valid, expired) and result of the access made to the RPMB.
+ * @req_resp     : Defines the type of request and response to/from the memory.
+ */
+struct rpmb_frame {
+	__u8   stuff[196];
+	__u8   key_mac[32];
+	__u8   data[256];
+	__u8   nonce[16];
+	__be32 write_counter;
+	__be16 addr;
+	__be16 block_count;
+	__be16 result;
+	__be16 req_resp;
+} __attribute__((packed));
+
+#define RPMB_PROGRAM_KEY       0x1    /* Program RPMB Authentication Key */
+#define RPMB_GET_WRITE_COUNTER 0x2    /* Read RPMB write counter */
+#define RPMB_WRITE_DATA        0x3    /* Write data to RPMB partition */
+#define RPMB_READ_DATA         0x4    /* Read data from RPMB partition */
+#define RPMB_RESULT_READ       0x5    /* Read result request  (Internal) */
+
+#define RPMB_REQ2RESP(_OP) ((_OP) << 8)
+#define RPMB_RESP2REQ(_OP) ((_OP) >> 8)
+
+/* length of the part of the frame used for HMAC computation */
+#define hmac_data_len \
+	(sizeof(struct rpmb_frame) - offsetof(struct rpmb_frame, data))
+
+/**
+ * enum rpmb_op_result - rpmb operation results
+ *
+ * @RPMB_ERR_OK:       operation successful
+ * @RPMB_ERR_GENERAL:  general failure
+ * @RPMB_ERR_AUTH:     mac doesn't match or ac calculation failure
+ * @RPMB_ERR_COUNTER:  counter doesn't match or counter increment failure
+ * @RPMB_ERR_ADDRESS:  address out of range or wrong address alignment
+ * @RPMB_ERR_WRITE:    data, counter, or result write failure
+ * @RPMB_ERR_READ:     data, counter, or result read failure
+ * @RPMB_ERR_NO_KEY:   authentication key not yet programmed
+ *
+ * @RPMB_ERR_COUNTER_EXPIRED:  counter expired
+ */
+enum rpmb_op_result {
+	RPMB_ERR_OK      = 0x0000,
+	RPMB_ERR_GENERAL = 0x0001,
+	RPMB_ERR_AUTH    = 0x0002,
+	RPMB_ERR_COUNTER = 0x0003,
+	RPMB_ERR_ADDRESS = 0x0004,
+	RPMB_ERR_WRITE   = 0x0005,
+	RPMB_ERR_READ    = 0x0006,
+	RPMB_ERR_NO_KEY  = 0x0007,
+
+	RPMB_ERR_COUNTER_EXPIRED = 0x0080
+};
+
+/**
+ * struct rpmb_ioc_cmd - rpmb operation request command
+ *
+ * @req:                request type:  must match the in frame req_resp
+ *                          program key
+ *                          get write counter
+ *                          write/read data
+ * @in_frames_count:    number of in frames
+ * @out_frames_count:   number of out frames
+ * @in_frames_ptr:      a pointer to the input frames buffer
+ * @out_frames_ptr:     a pointer to output frames buffer
+ */
+struct rpmb_ioc_cmd {
+	__u32  req;
+	__u32  in_frames_count;
+	__u32  out_frames_count;
+	__aligned_u64 in_frames_ptr;
+	__aligned_u64 out_frames_ptr;
+};
+
+#define rpmb_ioc_cmd_set_in_frames(_ic, _ptr) \
+	(_ic).in_frames_ptr = (__aligned_u64)(intptr_t)(_ptr)
+#define rpmb_ioc_cmd_set_out_frames(_ic, _ptr) \
+	(_ic).out_frames_ptr = (__aligned_u64)(intptr_t)(_ptr)
+
+#define RPMB_IOC_REQ _IOWR(0xB5, 1, struct rpmb_ioc_cmd)
+
+#endif /* _UAPI_LINUX_RPMB_H_ */
-- 
2.4.3

[toc] | [prev] | [next] | [standalone]


#1370187 — [PATCH] char: rpmb: fix memdup_user.cocci warnings

Fromkbuild test robot <lkp@intel.com>
Date2016-04-03 12:40 +0200
Subject[PATCH] char: rpmb: fix memdup_user.cocci warnings
Message-ID<rjNBM-201-13@gated-at.bofh.it>
In reply to#1370170
drivers/char/rpmb/cdev.c:94:13-20: WARNING opportunity for memdup_user

 Use memdup_user rather than duplicating its implementation
 This is a little bit restricted to reduce false positives

Generated by: scripts/coccinelle/api/memdup_user.cocci

CC: Tomas Winkler <tomas.winkler@intel.com>
Signed-off-by: Fengguang Wu <fengguang.wu@intel.com>
---

 0 files changed

rule starting on line 17: position variables or mixed modifs interfere with comm_assoc isobool (
(

(
(unknown *to == NULL)
  >>> IS_ERR(rule starting on line 17:to)

|
!unknown *to
  >>> IS_ERR(rule starting on line 17:to)

)
|
(unknown *NULL == unknown *to)
  >>> IS_ERR(rule starting on line 17:to)

) || ...)

[toc] | [prev] | [next] | [standalone]


#1370188 — Re: [PATCH 4/8] char: rpmb: provide user space interface

Fromkbuild test robot <lkp@intel.com>
Date2016-04-03 12:40 +0200
SubjectRe: [PATCH 4/8] char: rpmb: provide user space interface
Message-ID<rjNBM-201-15@gated-at.bofh.it>
In reply to#1370170
Hi Tomas,

[auto build test WARNING on char-misc/char-misc-testing]
[also build test WARNING on v4.6-rc1 next-20160401]
[if your patch is applied to the wrong git tree, please drop us a note to help improving the system]

url:    https://github.com/0day-ci/linux/commits/Tomas-Winkler/Replay-Protected-Memory-Block-RPMB-subsystem/20160403-174929


coccinelle warnings: (new ones prefixed by >>)

>> drivers/char/rpmb/cdev.c:94:13-20: WARNING opportunity for memdup_user

Please review and possibly fold the followup patch.

---
0-DAY kernel test infrastructure                Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all                   Intel Corporation

[toc] | [prev] | [next] | [standalone]


#1370171 — [PATCH 8/8] scsi: ufs: connect to RPMB subsystem

FromTomas Winkler <tomas.winkler@intel.com>
Date2016-04-03 11:50 +0200
Subject[PATCH 8/8] scsi: ufs: connect to RPMB subsystem
Message-ID<rjMPp-1o7-25@gated-at.bofh.it>
In reply to#1370169
Register UFS RPMB LUN with the RPMB subsystem and provide
implementation for the RPMB access operations. RPMB partition is
accessed via a sequence of security protocol in and security protocol
out commands with UFS specific parameters. This multi step process is
abstracted into 4 basic RPMB commands.

Signed-off-by: Alexander Usyskin <alexander.usyskin@intel.com>
Signed-off-by: Tomas Winkler <tomas.winkler@intel.com>
---
 drivers/scsi/ufs/ufshcd.c | 219 ++++++++++++++++++++++++++++++++++++++++++++++
 drivers/scsi/ufs/ufshcd.h |   2 +
 2 files changed, 221 insertions(+)

diff --git a/drivers/scsi/ufs/ufshcd.c b/drivers/scsi/ufs/ufshcd.c
index f8fa72c31a9d..c087e9713db3 100644
--- a/drivers/scsi/ufs/ufshcd.c
+++ b/drivers/scsi/ufs/ufshcd.c
@@ -37,10 +37,13 @@
  * license terms, and distributes only under these terms.
  */
 
+#include <asm/unaligned.h>
 #include <linux/async.h>
 #include <linux/devfreq.h>
 #include <linux/nls.h>
 #include <linux/of.h>
+#include <linux/rpmb.h>
+
 #include "ufshcd.h"
 #include "ufs_quirks.h"
 #include "unipro.h"
@@ -4744,6 +4747,214 @@ static void ufshcd_init_icc_levels(struct ufs_hba *hba)
 
 }
 
+#define SEC_PROTOCOL_UFS  0xEC
+#define   SEC_SPECIFIC_UFS_RPMB 0x0001
+
+#define SEC_PROTOCOL_CMD_SIZE 12
+#define SEC_PROTOCOL_RETRIES 3
+#define SEC_PROTOCOL_RETRIES_ON_RESET 10
+#define SEC_PROTOCOL_TIMEOUT msecs_to_jiffies(1000)
+
+static int
+ufshcd_rpmb_security_out(struct scsi_device *sdev,
+			 struct rpmb_frame *frames, u32 cnt)
+{
+	struct scsi_sense_hdr sshdr;
+	u32 trans_len = cnt * sizeof(struct rpmb_frame);
+	int reset_retries = SEC_PROTOCOL_RETRIES_ON_RESET;
+	int ret;
+	u8 cmd[SEC_PROTOCOL_CMD_SIZE];
+
+retry:
+	memset(cmd, 0, SEC_PROTOCOL_CMD_SIZE);
+	cmd[0] = SECURITY_PROTOCOL_OUT;
+	cmd[1] = SEC_PROTOCOL_UFS;
+	put_unaligned_be16(SEC_SPECIFIC_UFS_RPMB, cmd + 2);
+	cmd[4] = 0;                              /* inc_512 bit 7 set to 0 */
+	put_unaligned_be32(trans_len, cmd + 6);  /* transfer length */
+
+	ret = scsi_execute_req_flags(sdev, cmd, DMA_TO_DEVICE,
+				     frames, trans_len, &sshdr,
+				     SEC_PROTOCOL_TIMEOUT, SEC_PROTOCOL_RETRIES,
+				     NULL, 0);
+	if (ret && scsi_sense_valid(&sshdr) &&
+	    sshdr.sense_key == UNIT_ATTENTION &&
+	    sshdr.asc == 0x29 && sshdr.ascq == 0x00)
+		/* Device reset might occur several times,
+		 * give it one more chance
+		 */
+		if (--reset_retries > 0)
+			goto retry;
+
+	if (ret)
+		pr_err("%s: failed with err %0x\n", __func__, ret);
+
+	if (driver_byte(ret) & DRIVER_SENSE)
+		scsi_print_sense_hdr(sdev, "rpmb: security out", &sshdr);
+
+	return ret;
+}
+
+static int
+ufshcd_rpmb_security_in(struct scsi_device *sdev,
+			struct rpmb_frame *frames, u32 cnt)
+{
+	struct scsi_sense_hdr sshdr;
+	u32 alloc_len = cnt * sizeof(struct rpmb_frame);
+	int reset_retries = SEC_PROTOCOL_RETRIES_ON_RESET;
+	int ret;
+	u8 cmd[SEC_PROTOCOL_CMD_SIZE];
+
+retry:
+	memset(cmd, 0, SEC_PROTOCOL_CMD_SIZE);
+	cmd[0] = SECURITY_PROTOCOL_IN;
+	cmd[1] = SEC_PROTOCOL_UFS;
+	put_unaligned_be16(SEC_SPECIFIC_UFS_RPMB, cmd + 2);
+	cmd[4] = 0;                             /* inc_512 bit 7 set to 0 */
+	put_unaligned_be32(alloc_len, cmd + 6); /* allocation length */
+
+	ret = scsi_execute_req_flags(sdev, cmd, DMA_FROM_DEVICE,
+				     frames, alloc_len, &sshdr,
+				     SEC_PROTOCOL_TIMEOUT, SEC_PROTOCOL_RETRIES,
+				     NULL, 0);
+	if (ret && scsi_sense_valid(&sshdr) &&
+	    sshdr.sense_key == UNIT_ATTENTION &&
+	    sshdr.asc == 0x29 && sshdr.ascq == 0x00)
+		/* Device reset might occur several times,
+		 * give it one more chance
+		 */
+		if (--reset_retries > 0)
+			goto retry;
+
+	if (ret)
+		pr_err("%s: failed with err %0x\n", __func__, ret);
+
+	if (driver_byte(ret) & DRIVER_SENSE)
+		scsi_print_sense_hdr(sdev, "rpmb: security in", &sshdr);
+
+	return ret;
+}
+
+
+static int ufshcd_rpmb_send_req(struct device *dev, struct rpmb_data *rpmbd)
+{
+	unsigned long flags;
+	struct ufs_hba *hba = dev_get_drvdata(dev);
+	struct scsi_device *sdev;
+	struct rpmb_frame *in_frames, *out_frames;
+	u16 blks;
+	u16 type;
+	int ret;
+
+	in_frames = rpmbd->in_frames;
+	out_frames = rpmbd->out_frames;
+
+	type = rpmbd->req_type;
+	blks = be16_to_cpu(in_frames[0].block_count);
+
+	dev_dbg(hba->dev, "RPMB : type = %d, blocks = %d\n", type, blks);
+
+	spin_lock_irqsave(hba->host->host_lock, flags);
+	sdev = hba->sdev_ufs_rpmb;
+	if (sdev) {
+		ret = scsi_device_get(sdev);
+		if (!ret && !scsi_device_online(sdev)) {
+			ret = -ENODEV;
+			scsi_device_put(sdev);
+		}
+	} else {
+		ret = -ENODEV;
+	}
+	spin_unlock_irqrestore(hba->host->host_lock, flags);
+	if (ret)
+		return ret;
+
+	switch (type) {
+	case RPMB_PROGRAM_KEY:
+		blks = 1;
+		/* fall through */
+	case RPMB_WRITE_DATA:
+		/* STEP 1: send request to RPMB partition */
+		ret = ufshcd_rpmb_security_out(sdev, in_frames, blks);
+		if (ret)
+			break;
+
+		/* STEP 2: check write result (reuse out_frames) */
+		memset(out_frames, 0, 512);
+		out_frames[0].req_resp = cpu_to_be16(RPMB_RESULT_READ);
+		ret = ufshcd_rpmb_security_out(sdev, out_frames, 1);
+		if (ret)
+			break;
+
+		/* STEP 3: get response from RPMB partition */
+		ret = ufshcd_rpmb_security_in(sdev, out_frames, 1);
+		if (ret)
+			break;
+
+		break;
+	case RPMB_GET_WRITE_COUNTER:
+		blks = 1;
+		/* fall through */
+	case RPMB_READ_DATA:
+		/* STEP 1: send request to RPMB partition */
+		ret = ufshcd_rpmb_security_out(sdev, in_frames, 1);
+		if (ret)
+			break;
+		/* STEP 2: get response from RPMB partition */
+		ret = ufshcd_rpmb_security_in(sdev, out_frames, blks);
+		if (ret)
+			break;
+		break;
+	default:
+		ret = -EINVAL;
+		break;
+	}
+
+	scsi_device_put(sdev);
+	return ret;
+}
+
+static struct rpmb_ops ufshcd_rpmb_dev_ops = {
+	.send_rpmb_req = ufshcd_rpmb_send_req,
+	.type = RPMB_TYPE_UFS,
+};
+
+static inline void ufshcd_rpmb_add(struct ufs_hba *hba)
+{
+	struct rpmb_dev *rdev;
+
+	scsi_device_get(hba->sdev_ufs_rpmb);
+	rdev = rpmb_dev_register(hba->dev, &ufshcd_rpmb_dev_ops);
+	if (IS_ERR(rdev)) {
+		dev_warn(hba->dev, "%s: cannot register to rpmb %ld\n",
+			 dev_name(hba->dev), PTR_ERR(rdev));
+		goto out_put_dev;
+	}
+
+	return;
+
+out_put_dev:
+	scsi_device_put(hba->sdev_ufs_rpmb);
+	hba->sdev_ufs_rpmb = NULL;
+}
+
+static inline void ufshcd_rpmb_remove(struct ufs_hba *hba)
+{
+	unsigned long flags;
+
+	if (!hba->sdev_ufs_rpmb)
+		return;
+
+	spin_lock_irqsave(hba->host->host_lock, flags);
+
+	rpmb_dev_unregister(hba->dev);
+	scsi_device_put(hba->sdev_ufs_rpmb);
+	hba->sdev_ufs_rpmb = NULL;
+
+	spin_unlock_irqrestore(hba->host->host_lock, flags);
+}
+
+
 /**
  * ufshcd_scsi_add_wlus - Adds required W-LUs
  * @hba: per-adapter instance
@@ -4799,7 +5010,11 @@ static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
 		ret = PTR_ERR(sdev_rpmb);
 		goto remove_sdev_boot;
 	}
+	hba->sdev_ufs_rpmb = sdev_rpmb;
+
+	ufshcd_rpmb_add(hba);
 	scsi_device_put(sdev_rpmb);
+
 	goto out;
 
 remove_sdev_boot:
@@ -6168,6 +6383,8 @@ int ufshcd_shutdown(struct ufs_hba *hba)
 			goto out;
 	}
 
+	ufshcd_rpmb_remove(hba);
+
 	ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
 out:
 	if (ret)
@@ -6184,6 +6401,8 @@ EXPORT_SYMBOL(ufshcd_shutdown);
  */
 void ufshcd_remove(struct ufs_hba *hba)
 {
+	ufshcd_rpmb_remove(hba);
+
 	scsi_remove_host(hba->host);
 	/* disable interrupts */
 	ufshcd_disable_intr(hba, hba->intr_mask);
diff --git a/drivers/scsi/ufs/ufshcd.h b/drivers/scsi/ufs/ufshcd.h
index 4bb65669f052..92bfddf80ae8 100644
--- a/drivers/scsi/ufs/ufshcd.h
+++ b/drivers/scsi/ufs/ufshcd.h
@@ -346,6 +346,7 @@ struct ufs_init_prefetch {
  * @utmrdl_dma_addr: UTMRDL DMA address
  * @host: Scsi_Host instance of the driver
  * @dev: device handle
+ * @sdev_ufs_rpmb: reference to RPMB device W-LU
  * @lrb: local reference block
  * @lrb_in_use: lrb in use
  * @outstanding_tasks: Bits representing outstanding task requests
@@ -408,6 +409,7 @@ struct ufs_hba {
 	 * "UFS device" W-LU.
 	 */
 	struct scsi_device *sdev_ufs_device;
+	struct scsi_device *sdev_ufs_rpmb;
 
 	enum ufs_dev_pwr_mode curr_dev_pwr_mode;
 	enum uic_link_state uic_link_state;
-- 
2.4.3

[toc] | [prev] | [next] | [standalone]


#1370529 — Re: [PATCH 8/8] scsi: ufs: connect to RPMB subsystem

FromJoao Pinto <Joao.Pinto@synopsys.com>
Date2016-04-04 12:40 +0200
SubjectRe: [PATCH 8/8] scsi: ufs: connect to RPMB subsystem
Message-ID<rka5k-1Fr-1@gated-at.bofh.it>
In reply to#1370171
Hi!

On 4/3/2016 10:42 AM, Tomas Winkler wrote:
> Register UFS RPMB LUN with the RPMB subsystem and provide
> implementation for the RPMB access operations. RPMB partition is
> accessed via a sequence of security protocol in and security protocol
> out commands with UFS specific parameters. This multi step process is
> abstracted into 4 basic RPMB commands.
> 
> Signed-off-by: Alexander Usyskin <alexander.usyskin@intel.com>
> Signed-off-by: Tomas Winkler <tomas.winkler@intel.com>
> ---
>  drivers/scsi/ufs/ufshcd.c | 219 ++++++++++++++++++++++++++++++++++++++++++++++
>  drivers/scsi/ufs/ufshcd.h |   2 +
>  2 files changed, 221 insertions(+)
> 
> diff --git a/drivers/scsi/ufs/ufshcd.c b/drivers/scsi/ufs/ufshcd.c
> index f8fa72c31a9d..c087e9713db3 100644
> --- a/drivers/scsi/ufs/ufshcd.c
> +++ b/drivers/scsi/ufs/ufshcd.c
> @@ -37,10 +37,13 @@
>   * license terms, and distributes only under these terms.
>   */
>  

[snip]

>  	scsi_remove_host(hba->host);
>  	/* disable interrupts */
>  	ufshcd_disable_intr(hba, hba->intr_mask);
> diff --git a/drivers/scsi/ufs/ufshcd.h b/drivers/scsi/ufs/ufshcd.h
> index 4bb65669f052..92bfddf80ae8 100644
> --- a/drivers/scsi/ufs/ufshcd.h
> +++ b/drivers/scsi/ufs/ufshcd.h
> @@ -346,6 +346,7 @@ struct ufs_init_prefetch {
>   * @utmrdl_dma_addr: UTMRDL DMA address
>   * @host: Scsi_Host instance of the driver
>   * @dev: device handle
> + * @sdev_ufs_rpmb: reference to RPMB device W-LU
>   * @lrb: local reference block
>   * @lrb_in_use: lrb in use
>   * @outstanding_tasks: Bits representing outstanding task requests
> @@ -408,6 +409,7 @@ struct ufs_hba {
>  	 * "UFS device" W-LU.
>  	 */
>  	struct scsi_device *sdev_ufs_device;
> +	struct scsi_device *sdev_ufs_rpmb;
>  
>  	enum ufs_dev_pwr_mode curr_dev_pwr_mode;
>  	enum uic_link_state uic_link_state;
> 

I saw some kbuild robot issues regarding the patchset, so I would suggest you
make a v2 of the patch set and I can run some tests with the DW UFS Host design.

Thanks.
Joao

[toc] | [prev] | [next] | [standalone]


#1370530 — RE: [PATCH 8/8] scsi: ufs: connect to RPMB subsystem

From"Winkler, Tomas" <tomas.winkler@intel.com>
Date2016-04-04 12:40 +0200
SubjectRE: [PATCH 8/8] scsi: ufs: connect to RPMB subsystem
Message-ID<rka5k-1Fr-3@gated-at.bofh.it>
In reply to#1370529
> 

I saw some kbuild robot issues regarding the patchset, so I would suggest you make a v2 of the patch set and I can run some tests with the DW UFS Host design.

Yes the second round is on the way but there are (for)  quite minor issues. 
Tomas

[toc] | [prev] | [next] | [standalone]


#1370172 — [PATCH 6/8] tools rpmb: add RPBM access tool

FromTomas Winkler <tomas.winkler@intel.com>
Date2016-04-03 11:50 +0200
Subject[PATCH 6/8] tools rpmb: add RPBM access tool
Message-ID<rjMPp-1o7-19@gated-at.bofh.it>
In reply to#1370169
Add simple RPMB host testing tool. It can be used
to program key, write and read data block, and retrieve
write counter.

Signed-off-by: Tomas Winkler <tomas.winkler@intel.com>
---
 MAINTAINERS           |   1 +
 tools/Makefile        |  16 +-
 tools/rpmb/.gitignore |   2 +
 tools/rpmb/Makefile   |  32 ++
 tools/rpmb/rpmb.c     | 807 ++++++++++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 853 insertions(+), 5 deletions(-)
 create mode 100644 tools/rpmb/.gitignore
 create mode 100644 tools/rpmb/Makefile
 create mode 100644 tools/rpmb/rpmb.c

diff --git a/MAINTAINERS b/MAINTAINERS
index 8704b40eaf27..75e63de9283a 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -9432,6 +9432,7 @@ F:	drivers/char/rpmb/*
 F:	include/uapi/linux/rpmb.h
 F:	include/linux/rpmb.h
 F:	Documentation/ABI/testing/sysfs-class-rpmb
+F:	tools/rpmb/
 
 RTL2830 MEDIA DRIVER
 M:	Antti Palosaari <crope@iki.fi>
diff --git a/tools/Makefile b/tools/Makefile
index 60c7e6c8ff17..5b37ccd95cab 100644
--- a/tools/Makefile
+++ b/tools/Makefile
@@ -19,6 +19,7 @@ help:
 	@echo '  lguest                 - a minimal 32-bit x86 hypervisor'
 	@echo '  net                    - misc networking tools'
 	@echo '  perf                   - Linux performance measurement and analysis tool'
+	@echo '  rpmb                   - Replay protected memory block access tool'
 	@echo '  selftests              - various kernel selftests'
 	@echo '  spi                    - spi tools'
 	@echo '  objtool                - an ELF object analysis tool'
@@ -55,7 +56,8 @@ acpi: FORCE
 cpupower: FORCE
 	$(call descend,power/$@)
 
-cgroup firewire hv guest spi usb virtio vm net iio gpio objtool: FORCE
+cgroup firewire hv guest rpmb spi usb virtio vm net iio gpio objtool: FORCE
+cgroup firewire hv guest rpmb spi usb virtio vm net iio: FORCE
 	$(call descend,$@)
 
 liblockdep: FORCE
@@ -85,7 +87,7 @@ freefall: FORCE
 	$(call descend,laptop/$@)
 
 all: acpi cgroup cpupower hv firewire lguest \
-		perf selftests turbostat usb \
+		perf rpmb selftests turbostat usb \
 		virtio vm net x86_energy_perf_policy \
 		tmon freefall objtool
 
@@ -95,7 +97,8 @@ acpi_install:
 cpupower_install:
 	$(call descend,power/$(@:_install=),install)
 
-cgroup_install firewire_install hv_install lguest_install perf_install usb_install virtio_install vm_install net_install objtool_install:
+cgroup_install firewire_install hv_install lguest_install perf_install rpmb_install usb_install virtio_install vm_install net_install objtool_install:
+cgroup_install firewire_install hv_install lguest_install perf_install rpmb_install usb_install virtio_install vm_install net_install:
 	$(call descend,$(@:_install=),install)
 
 selftests_install:
@@ -111,7 +114,7 @@ freefall_install:
 	$(call descend,laptop/$(@:_install=),install)
 
 install: acpi_install cgroup_install cpupower_install hv_install firewire_install lguest_install \
-		perf_install selftests_install turbostat_install usb_install \
+		perf_install rpmb_install selftests_install turbostat_install usb_install \
 		virtio_install vm_install net_install x86_energy_perf_policy_install \
 		tmon_install freefall_install objtool_install
 
@@ -139,6 +142,9 @@ libsubcmd_clean:
 perf_clean:
 	$(call descend,$(@:_clean=),clean)
 
+rpmb_clean:
+	$(call descend,$(@:_clean=),clean)
+
 selftests_clean:
 	$(call descend,testing/$(@:_clean=),clean)
 
@@ -155,7 +161,7 @@ build_clean:
 	$(call descend,build,clean)
 
 clean: acpi_clean cgroup_clean cpupower_clean hv_clean firewire_clean lguest_clean \
-		perf_clean selftests_clean turbostat_clean spi_clean usb_clean virtio_clean \
+		perf_clean rpmb_clean selftests_clean turbostat_clean spi_clean usb_clean virtio_clean \
 		vm_clean net_clean iio_clean x86_energy_perf_policy_clean tmon_clean \
 		freefall_clean build_clean libbpf_clean libsubcmd_clean liblockdep_clean \
 		gpio_clean objtool_clean
diff --git a/tools/rpmb/.gitignore b/tools/rpmb/.gitignore
new file mode 100644
index 000000000000..218f680548e6
--- /dev/null
+++ b/tools/rpmb/.gitignore
@@ -0,0 +1,2 @@
+*.o
+rpmb
diff --git a/tools/rpmb/Makefile b/tools/rpmb/Makefile
new file mode 100644
index 000000000000..e0e51f306dac
--- /dev/null
+++ b/tools/rpmb/Makefile
@@ -0,0 +1,32 @@
+CC = $(CROSS_COMPILE)gcc
+LD = $(CROSS_COMPILE)ld
+PKG_CONFIG = $(CROSS_COMPILE)pkg-config
+
+ifeq ($(srctree),)
+srctree := $(patsubst %/,%,$(dir $(shell pwd)))
+srctree := $(patsubst %/,%,$(dir $(srctree)))
+#$(info Determined 'srctree' to be $(srctree))
+endif
+
+INSTALL = install
+prefix ?= /usr/local
+bindir = $(prefix)/bin
+
+
+CFLAGS += -D__EXPORTED_HEADERS__
+CFLAGS += -I$(srctree)/include/uapi -I$(srctree)/include
+LDLIBS += $(shell $(PKG_CONFIG) --libs libcrypto)
+
+prog := rpmb
+
+all : $(prog)
+
+$(prog): rpmb.o
+
+clean :
+	$(RM) $(prog) *.o
+
+install: $(prog)
+	$(INSTALL) -m755 -d $(DESTDIR)$(bindir)
+	$(INSTALL) $(prog) $(DESTDIR)$(bindir)
+
diff --git a/tools/rpmb/rpmb.c b/tools/rpmb/rpmb.c
new file mode 100644
index 000000000000..e55f4d4e7ef7
--- /dev/null
+++ b/tools/rpmb/rpmb.c
@@ -0,0 +1,807 @@
+/******************************************************************************
+ * This file is provided under a dual BSD/GPLv2 license.  When using or
+ * redistributing this file, you may do so under either license.
+ *
+ * GPL LICENSE SUMMARY
+ *
+ * Copyright(c) 2016 Intel Corporation. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * 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.
+ *
+ * The full GNU General Public License is included in this distribution
+ * in the file called LICENSE.GPL.
+ *
+ * Contact Information:
+ *	Intel Corporation.
+ *	linux-mei@linux.intel.com
+ *	http://www.intel.com
+ *
+ * BSD LICENSE
+ *
+ * Copyright(c) 2016 Intel Corporation. All rights reserved.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *  * Neither the name Intel Corporation nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ *****************************************************************************/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <dirent.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <libgen.h>
+#include <limits.h>
+#include <ctype.h>
+#include <errno.h>
+#include <stdint.h>
+#include <stdbool.h>
+
+#include <openssl/engine.h>
+#include <openssl/hmac.h>
+
+#include "linux/rpmb.h"
+
+#define RPMB_KEY_SIZE 32
+#define RPMB_MAC_SIZE 32
+#define RPMB_NONCE_SIZE 16
+
+#define rpmb_msg(fmt, ARGS...) \
+	fprintf(stderr, "rpmb: " fmt, ##ARGS)
+
+#define rpmb_err(fmt, ARGS...) \
+	fprintf(stderr, "rpmb: error: " fmt, ##ARGS)
+
+static const char *rpmb_op_str(uint16_t op)
+{
+#define RPMB_OP(_op) case RPMB_##_op: return #_op
+
+	switch (op) {
+	RPMB_OP(PROGRAM_KEY);
+	RPMB_OP(GET_WRITE_COUNTER);
+	RPMB_OP(WRITE_DATA);
+	RPMB_OP(READ_DATA);
+	RPMB_OP(RESULT_READ);
+	break;
+	default:
+		return "unknown";
+	}
+}
+
+static const char *rpmb_result_str(enum rpmb_op_result result)
+{
+#define str(x) #x
+#define RPMB_ERR(_res) case RPMB_ERR_##_res:         \
+	{ if (result & RPMB_ERR_COUNTER_EXPIRED)     \
+		return "COUNTER_EXPIRE:" str(_res);  \
+	else                                         \
+		return #_res;                        \
+	}
+
+	switch (result & 0x000F) {
+	RPMB_ERR(OK);
+	RPMB_ERR(GENERAL);
+	RPMB_ERR(AUTH);
+	RPMB_ERR(COUNTER);
+	RPMB_ERR(ADDRESS);
+	RPMB_ERR(WRITE);
+	RPMB_ERR(READ);
+	RPMB_ERR(NO_KEY);
+	break;
+	default:
+		return "unknown";
+	}
+#undef RPMB_ERR
+};
+
+static inline void __dump_buffer(const char *buf)
+{
+	fprintf(stderr, "%s\n", buf);
+}
+static void rpmb_dump_hex_buffer(const unsigned char *buf, size_t len)
+{
+	const size_t pbufsz = 16 * 3;
+	char pbuf[pbufsz];
+	int j = 0;
+
+	while (len-- > 0) {
+		snprintf(&pbuf[j], pbufsz - j, "%02X ", *buf++);
+		j += 3;
+		if (j == 16 * 3) {
+			__dump_buffer(pbuf);
+			j = 0;
+		}
+	}
+	if (j)
+		__dump_buffer(pbuf);
+}
+
+static int open_dev_file(const char *devfile)
+{
+	int fd;
+
+	fd = open(devfile, O_RDWR);
+	if (fd < 0)
+		rpmb_err("Cannot open: %s: %s\n", devfile, strerror(errno));
+	return fd;
+}
+
+static int open_rd_file(const char *datafile, const char *type)
+{
+	int fd;
+
+	if (!strcmp(datafile, "-"))
+		fd = STDIN_FILENO;
+	else
+		fd = open(datafile, O_RDONLY);
+
+	if (fd < 0)
+		rpmb_err("Cannot open %s: %s: %s\n",
+			type, datafile, strerror(errno));
+
+	return fd;
+}
+
+static int open_wr_file(const char *datafile, const char *type)
+{
+	int fd;
+
+	if (!strcmp(datafile, "-"))
+		fd = STDOUT_FILENO;
+	else
+		fd = open(datafile, O_WRONLY | O_CREAT | O_APPEND,
+					   S_IRUSR | S_IWUSR);
+	if (fd < 0)
+		rpmb_err("Cannot open %s: %s: %s\n",
+			type, datafile, strerror(errno));
+	return fd;
+}
+
+static void close_fd(int fd)
+{
+	if (fd > 0 && fd != STDIN_FILENO && fd != STDOUT_FILENO)
+		close(fd);
+}
+
+/* blocking rw wrapper */
+#define rw(func, fd, buf, size)                              \
+({                                                           \
+	ssize_t nread = 0, n;                                \
+	char *_buf = (char *)buf;                            \
+	do {                                                 \
+		n = func(fd, _buf + nread, size - nread);    \
+		if (n == -1 && errno != EINTR) {             \
+			nread = -1;                          \
+			break;                               \
+		} else if (n > 0) {                          \
+			nread += n;                          \
+		}                                            \
+	} while (n != 0 && (size_t)nread != size);           \
+	nread;                                               \
+})
+
+
+static ssize_t read_file(int fd, unsigned char *data, size_t size)
+{
+	ssize_t ret;
+
+	ret = rw(read, fd, data, size);
+	if (ret < 0) {
+		rpmb_err("cannot read file: %s\n", strerror(errno));
+	} else if (ret != size) {
+		rpmb_err("read %zd but must be %zu bytes length\n",
+			ret, size);
+		ret = -EINVAL;
+	}
+
+	return ret;
+}
+
+static ssize_t write_file(int fd, unsigned char *data, size_t size)
+{
+	ssize_t ret;
+
+	ret = rw(write, fd, data, size);
+	if (ret < 0) {
+		rpmb_err("cannot read file: %s\n", strerror(errno));
+	} else if (ret != size) {
+		rpmb_err("data is %zd but must be %zu bytes length\n",
+			ret, size);
+		ret = -EINVAL;
+	}
+	return ret;
+}
+
+static int rpmb_calc_hmac_sha256(struct rpmb_frame *frames, size_t blocks_cnt,
+				 const unsigned char key[],
+				 unsigned int key_size,
+				 unsigned char mac[],
+				 unsigned int mac_size)
+{
+	HMAC_CTX ctx;
+	int ret;
+	int i;
+
+	 /* SSL returns 1 on success 0 on failure */
+
+	HMAC_CTX_init(&ctx);
+	ret = HMAC_Init_ex(&ctx, key, key_size, EVP_sha256(), NULL);
+	if (ret == 0)
+		goto out;
+	for (i = 0; i < blocks_cnt; i++)
+		HMAC_Update(&ctx, frames[i].data, hmac_data_len);
+
+	ret = HMAC_Final(&ctx, mac, &mac_size);
+	if (ret == 0)
+		goto out;
+	if (mac_size != RPMB_MAC_SIZE)
+		ret = 0;
+
+	ret = 1;
+out:
+	HMAC_CTX_cleanup(&ctx);
+	return ret == 1 ? 0 : -1;
+}
+
+static int rpmb_ioctl(int fd, uint16_t req,
+	const struct rpmb_frame *frames_in,
+	unsigned int in_cnt,
+	struct rpmb_frame *frames_out,
+	unsigned int out_cnt)
+{
+	int ret;
+	struct rpmb_ioc_cmd icmd;
+
+	icmd.req = req;
+	icmd.in_frames_count = in_cnt;
+	rpmb_ioc_cmd_set_in_frames(icmd, frames_in);
+	rpmb_ioc_cmd_set_out_frames(icmd, frames_out);
+	icmd.out_frames_count = out_cnt;
+
+	ret = ioctl(fd, RPMB_IOC_REQ, &icmd);
+	if (ret < 0)
+		rpmb_err("ioctl failure %d: %s\n", ret, strerror(errno));
+
+	return ret;
+}
+
+
+static int op_rpmb_program_key(int nargs, char *argv[])
+{
+	int ret;
+	int  dev_fd = -1, key_fd = -1;
+	uint16_t req = RPMB_PROGRAM_KEY;
+	struct rpmb_frame frame_in, frame_out;
+
+	ret = -EINVAL;
+	if (nargs != 2)
+		return ret;
+
+	dev_fd = open_dev_file(argv[0]);
+	if (dev_fd < 0)
+		goto out;
+	argv++;
+
+	key_fd = open_rd_file(argv[0], "key file");
+	if (key_fd < 0)
+		goto out;
+	argv++;
+
+	memset(&frame_in, 0, sizeof(frame_in));
+	frame_in.req_resp = htobe16(req);
+
+	read_file(key_fd, frame_in.key_mac, RPMB_KEY_SIZE);
+
+	ret = rpmb_ioctl(dev_fd, req, &frame_in, 1, &frame_out, 1);
+	if (ret)
+		goto out;
+
+	ret = be16toh(frame_out.result);
+	if (ret)
+		rpmb_err("RPMB operation %s failed, %s[0x%04x]\n",
+			 rpmb_op_str(req), rpmb_result_str(ret), ret);
+
+out:
+	close_fd(dev_fd);
+	close_fd(key_fd);
+
+	return ret;
+}
+
+static int rpmb_get_write_counter(int dev_fd, unsigned int *cnt,
+				  const unsigned char *key)
+{
+	int ret;
+	uint16_t req = RPMB_GET_WRITE_COUNTER;
+	unsigned char mac[RPMB_MAC_SIZE];
+	struct rpmb_frame frame_in;
+	struct rpmb_frame frame_out;
+
+	memset(&frame_in, 0, sizeof(frame_in));
+	frame_in.req_resp = htobe16(req);
+	RAND_bytes(frame_in.nonce, RPMB_NONCE_SIZE);
+
+	ret = rpmb_ioctl(dev_fd, req, &frame_in, 1, &frame_out, 1);
+	if (ret != 0)
+		return ret;
+
+	ret = be16toh(frame_out.result);
+	if (ret)
+		goto out;
+
+	if (key) {
+		rpmb_calc_hmac_sha256(&frame_out, 1,
+				      key, RPMB_KEY_SIZE,
+				      mac, RPMB_MAC_SIZE);
+		if (memcmp(mac, frame_out.key_mac, RPMB_MAC_SIZE)) {
+			rpmb_err("RPMB hmac mismatch\n");
+			rpmb_dump_hex_buffer(frame_out.key_mac, RPMB_MAC_SIZE);
+			rpmb_dump_hex_buffer(mac, RPMB_MAC_SIZE);
+			ret = RPMB_ERR_AUTH;
+			goto out;
+		}
+	}
+
+	*cnt = be32toh(frame_out.write_counter);
+
+out:
+	if (ret) {
+		rpmb_err("RPMB operation %s failed, %s[0x%04x]\n",
+			 rpmb_op_str(req), rpmb_result_str(ret), ret);
+	}
+	return ret;
+}
+
+static int op_rpmb_get_write_counter(int nargs, char **argv)
+{
+	int ret;
+	int dev_fd = -1, key_fd = -1;
+	bool has_key;
+	unsigned char key[RPMB_KEY_SIZE];
+	unsigned int cnt;
+
+	if (nargs == 2)
+		has_key = true;
+	else if (nargs == 1)
+		has_key = false;
+	else
+		return -EINVAL;
+
+	ret = -EINVAL;
+	dev_fd = open_dev_file(argv[0]);
+	if (dev_fd < 0)
+		return ret;
+	argv++;
+
+	if (has_key) {
+		key_fd = open_rd_file(argv[0], "key file");
+		if (key_fd < 0)
+			goto out;
+		argv++;
+
+		ret = read_file(key_fd, key, RPMB_KEY_SIZE);
+		if (ret < 0)
+			goto out;
+
+		ret = rpmb_get_write_counter(dev_fd, &cnt, key);
+	} else {
+		ret = rpmb_get_write_counter(dev_fd, &cnt, NULL);
+	}
+
+	if (!ret)
+		printf("Counter value: 0x%08x\n", cnt);
+
+out:
+	close_fd(dev_fd);
+	close_fd(key_fd);
+	return ret;
+}
+
+static int op_rpmb_read_blocks(int nargs, char **argv)
+{
+	int i, ret;
+	int dev_fd = -1, data_fd = -1, key_fd = -1;
+	uint16_t req = RPMB_READ_DATA;
+	uint16_t addr, blocks_cnt;
+	unsigned char key[RPMB_KEY_SIZE];
+	unsigned char mac[RPMB_MAC_SIZE];
+	unsigned long numarg;
+	bool has_key;
+	struct rpmb_frame frame_in;
+	struct rpmb_frame *frames_out = NULL;
+	struct rpmb_frame *frame_out;
+
+	ret = -EINVAL;
+	if (nargs == 4)
+		has_key = false;
+	else if (nargs == 5)
+		has_key = true;
+	else
+		return ret;
+
+	dev_fd = open_dev_file(argv[0]);
+	if (dev_fd < 0)
+		goto out;
+	argv++;
+
+	errno = 0;
+	numarg = strtoul(argv[0], NULL, 0);
+	if (errno || numarg > USHRT_MAX) {
+		rpmb_err("wrong block address\n");
+		goto out;
+	}
+	addr = (uint16_t)numarg;
+	argv++;
+
+	errno = 0;
+	numarg = strtoul(argv[0], NULL, 0);
+	if (errno || numarg > USHRT_MAX) {
+		rpmb_err("wrong blocks count\n");
+		goto out;
+	}
+	blocks_cnt = (uint16_t)numarg;
+	argv++;
+
+	if (blocks_cnt == 0) {
+		rpmb_err("wrong blocks count\n");
+		goto out;
+	}
+
+	data_fd = open_wr_file(argv[0], "output data");
+	if (data_fd < 0)
+		goto out;
+	argv++;
+
+	if (has_key) {
+		key_fd = open_rd_file(argv[0], "key file");
+		if (key_fd < 0)
+			goto out;
+		argv++;
+
+		ret = read_file(key_fd, key, RPMB_KEY_SIZE);
+		if (ret < 0)
+			goto out;
+	}
+
+	ret = 0;
+	memset(&frame_in, 0, sizeof(frame_in));
+	frame_in.req_resp = htobe16(req);
+	frame_in.addr = htobe16(addr);
+	frame_in.block_count = htobe16(blocks_cnt);
+	if (has_key)
+		RAND_bytes(frame_in.nonce, RPMB_NONCE_SIZE);
+
+	frames_out = calloc(blocks_cnt, sizeof(struct rpmb_frame));
+	if (!frames_out) {
+		rpmb_err("Cannot allocate %d RPMB frames\n", blocks_cnt);
+		ret = -ENOMEM;
+		goto out;
+	}
+
+	ret = rpmb_ioctl(dev_fd, req, &frame_in, 1, frames_out, blocks_cnt);
+	if (ret)
+		goto out;
+
+	frame_out = &frames_out[blocks_cnt - 1];
+	ret = be16toh(frame_out->result);
+	if (ret) {
+		rpmb_err("RPMB operation %s failed, %s[0x%04x]\n",
+			 rpmb_op_str(req), rpmb_result_str(ret), ret);
+		goto out;
+	}
+
+	if (has_key) {
+		rpmb_calc_hmac_sha256(frames_out, blocks_cnt,
+				      key, RPMB_KEY_SIZE,
+				      mac, RPMB_MAC_SIZE);
+		if (memcmp(mac, frame_out->key_mac, RPMB_MAC_SIZE)) {
+			rpmb_err("RPMB hmac mismatch\n");
+			rpmb_dump_hex_buffer(frame_out->key_mac, RPMB_MAC_SIZE);
+			rpmb_dump_hex_buffer(mac, RPMB_MAC_SIZE);
+			ret = RPMB_ERR_AUTH;
+			goto out;
+		}
+	}
+
+	for (i = 0; i < blocks_cnt; i++) {
+		ret = write_file(data_fd,
+				frames_out[i].data, sizeof(frames_out[i].data));
+		if (ret < 0)
+			goto out;
+	}
+
+out:
+	free(frames_out);
+	close_fd(dev_fd);
+	close_fd(data_fd);
+	close_fd(key_fd);
+
+	return ret;
+}
+
+static int op_rpmb_write_blocks(int nargs, char **argv)
+{
+	int ret;
+	int dev_fd = -1, key_fd = -1, data_fd = -1;
+	int i;
+	uint16_t req = RPMB_WRITE_DATA;
+	unsigned char key[RPMB_KEY_SIZE];
+	unsigned char mac[RPMB_MAC_SIZE];
+	unsigned long numarg;
+	uint16_t addr, blocks_cnt;
+	unsigned int cnt;
+	struct rpmb_frame *frames_in;
+	struct rpmb_frame frame_out;
+
+	ret = -EINVAL;
+	if (nargs != 5)
+		goto out;
+
+	dev_fd = open_dev_file(argv[0]);
+	if (dev_fd < 0)
+		goto out;
+	argv++;
+
+	errno = 0;
+	numarg = strtoul(argv[0], NULL, 0);
+	if (errno || numarg > USHRT_MAX) {
+		rpmb_err("wrong block address %s\n", argv[0]);
+		goto out;
+	}
+	addr = (uint16_t)numarg;
+	argv++;
+
+	errno = 0;
+	numarg = strtoul(argv[0], NULL, 0);
+	if (errno || numarg > USHRT_MAX) {
+		rpmb_err("wrong blocks count\n");
+		goto out;
+	}
+	blocks_cnt = (uint16_t)numarg;
+	argv++;
+
+	if (blocks_cnt == 0) {
+		rpmb_err("wrong blocks count\n");
+		goto out;
+	}
+
+	data_fd = open_rd_file(argv[0], "data file");
+	if (data_fd < 0)
+		goto out;
+	argv++;
+
+	key_fd = open_rd_file(argv[0], "key file");
+	if (key_fd < 0)
+		goto out;
+	argv++;
+
+	ret = read_file(key_fd, key, RPMB_KEY_SIZE);
+	if (ret < 0)
+		goto out;
+
+	frames_in = calloc(blocks_cnt, sizeof(struct rpmb_frame));
+	if (!frames_in) {
+		rpmb_err("can't allocate memory for RPMB outer frames\n");
+		exit(EXIT_FAILURE);
+	}
+
+	ret = rpmb_get_write_counter(dev_fd, &cnt, key);
+	if (ret)
+		goto out;
+
+	for (i = 0; i < blocks_cnt; i++) {
+		frames_in[i].req_resp      = htobe16(req);
+		frames_in[i].block_count   = htobe16(blocks_cnt);
+		frames_in[i].addr          = htobe16(addr);
+		frames_in[i].write_counter = htobe32(cnt);
+	}
+
+	for (i = 0; i < blocks_cnt; i++) {
+		ret = read_file(data_fd, frames_in[i].data,
+				sizeof(frames_in[0].data));
+		if (ret < 0)
+			goto out;
+	}
+
+	rpmb_calc_hmac_sha256(frames_in, blocks_cnt,
+			      key, RPMB_KEY_SIZE,
+			      mac, RPMB_MAC_SIZE);
+	memcpy(frames_in[blocks_cnt - 1].key_mac, mac, RPMB_MAC_SIZE);
+	ret = rpmb_ioctl(dev_fd, req, frames_in, blocks_cnt, &frame_out, 1);
+	if (ret != 0)
+		goto out;
+
+	ret = be16toh(frame_out.result);
+	if (ret) {
+		rpmb_err("RPMB operation %s failed, %s[0x%04x]\n",
+			 rpmb_op_str(req), rpmb_result_str(ret), ret);
+	}
+out:
+	close_fd(dev_fd);
+	close_fd(data_fd);
+	close_fd(key_fd);
+	return ret;
+}
+
+typedef int (*rpmb_op)(int argc, char *argv[]);
+
+struct rpmb_cmd {
+	const char *op_name;
+	rpmb_op     op;
+	const char  *usage; /* usage title */
+	const char  *help;  /* help */
+};
+
+
+static const struct rpmb_cmd cmds[] = {
+	{
+	 "program-key",
+	 op_rpmb_program_key,
+	 "<RPMB_DEVICE> <KEY_FILE>",
+	 "    Program authentication key of 32 bytes length from the KEY_FILE\n"
+	 "    when KEY_FILE is -, read standard input.\n"
+	 "    NOTE: This is a one-time programmable irreversible change.\n",
+	},
+	{
+	 "write-counter",
+	 op_rpmb_get_write_counter,
+	 "<RPMB_DEVICE> [KEY_FILE]",
+	 "    Rertrive write counter value from the <RPMB_DEVICE> to stdout.\n"
+	 "    When KEY_FILE is present data is verified via HMAC\n"
+	 "    when KEY_FILE is -, read standard input.\n"
+	},
+	{
+	  "write-blocks",
+	  op_rpmb_write_blocks,
+	  "<RPMB_DEVICE> <address> <block_count> <DATA_FILE> <KEY_FILE>",
+	  "    <block count> of 256 bytes will be written from the DATA_FILE\n"
+	  "    to the <RPMB_DEVICE> at block offset <address>.\n"
+	  "    When DATA_FILE is -, read from standard input.\n",
+	},
+	{
+	  "read-blocks",
+	  op_rpmb_read_blocks,
+	  "<RPMB_DEVICE> <address> <blocks count> <OUTPUT_FILE> [KEY_FILE]",
+	  "    <block count> of 256 bytes will be read from <RPMB_DEVICE>\n"
+	  "    to the OUTPUT_FILE\n"
+	  "    When KEY_FILE is present data is verified via HMAC\n"
+	  "    When OUTPUT/KEY_FILE is -, read from standard input.\n"
+	  "    When OUTPUT_FILE is -, write to standard output\n",
+	},
+
+	{ NULL, NULL, NULL, NULL }
+};
+
+static void help(const char *prog, const struct rpmb_cmd *cmd)
+{
+	printf("%s %s %s\n", prog, cmd->op_name, cmd->usage);
+	printf("%s\n", cmd->help);
+}
+
+static void usage(const char *prog)
+{
+	int i;
+
+	printf("\n");
+	printf("Usage: %s <command> <args>\n\n", prog);
+	for (i = 0; cmds[i].op_name; i++)
+		printf("       %s %s %s\n",
+			prog, cmds[i].op_name, cmds[i].usage);
+
+	printf("\n");
+	printf("      %s help : shows this help\n", prog);
+	printf("      %s help <command>: shows detailed help\n", prog);
+}
+
+static bool call_for_help(const char *arg)
+{
+	return !strcmp(arg, "help") ||
+	       !strcmp(arg, "-h")   ||
+	       !strcmp(arg, "--help");
+}
+
+static const
+struct rpmb_cmd *parse_args(const char *prog, int *_argc, char **_argv[])
+{
+
+	int i;
+	int argc = *_argc;
+	char **argv =  *_argv;
+	const struct rpmb_cmd *cmd = NULL;
+	bool need_help = false;
+
+	argc--; argv++;
+
+	if (argc == 0)
+		goto out;
+
+	if (call_for_help(argv[0])) {
+		argc--; argv++;
+		if (argc == 0)
+			goto out;
+		else
+			need_help = true;
+	}
+
+	for (i = 0; cmds[i].op_name; i++) {
+		if (!strncmp(argv[0], cmds[i].op_name,
+			     strlen(cmds[i].op_name))) {
+			cmd = &cmds[i];
+			argc--; argv++;
+			break;
+		}
+	}
+
+	if (!cmd)
+		goto out;
+
+	if (need_help || (argc > 0 && call_for_help(argv[0]))) {
+		help(prog, cmd);
+		argc--; argv++;
+		return NULL;
+	}
+
+out:
+	*_argc = argc;
+	*_argv = argv;
+
+	if (!cmd)
+		usage(prog);
+
+	return cmd;
+}
+
+int main(int argc, char *argv[])
+{
+	const char *prog = basename(argv[0]);
+	const struct rpmb_cmd *cmd;
+	int ret;
+
+	cmd = parse_args(prog, &argc, &argv);
+	if (!cmd)
+		exit(EXIT_SUCCESS);
+
+	ret = cmd->op(argc, argv);
+	if (ret == -EINVAL)
+		help(prog, cmd);
+
+	if (ret)
+		exit(EXIT_FAILURE);
+
+	exit(EXIT_SUCCESS);
+}
-- 
2.4.3

[toc] | [prev] | [next] | [standalone]


#1370218

FromAndy Lutomirski <luto@kernel.org>
Date2016-04-03 15:30 +0200
Message-ID<rjQgi-3Sk-9@gated-at.bofh.it>
In reply to#1370169
On 04/03/2016 02:42 AM, Tomas Winkler wrote:
> Few storage technology such is EMMC, UFS, and NVMe support RPMB
> hardware partition with common protocol and frame layout.
> The RPMB partition cannot be accessed via standard block layer, but
> by a set of specific commands: WRITE, READ, GET_WRITE_COUNTER, and
> PROGRAM_KEY.
> Such a partition provides authenticated and replay protected access,
> hence suitable as a secure storage.
>
> A storage device registers its RPMB hardware (emmc) partition or
> RPMB W-LUN (ufs) with the RPMB layer providing an implementation for
> send_rpmb_req() handler.
> Tere is as well simulation platform device. This is handy as an RPMB
> key can be programmed only once at storage device lifetime.
>
> The RPMB layer aims to provide in-kernel API for Trusted Execution
> Environment (TEE) devices that are capable to securely compute block
> frame signature. A TEE driver can claim rpmb interface, for example,
> via  class_interface_register ().

What's the workflow?  Does the TEE ask the kernel to do RPMB operations 
for it and supply the kernel with the authenticated request blobs to 
forward to the RPMB?

--Andy

[toc] | [prev] | [next] | [standalone]


#1370279

From"Winkler, Tomas" <tomas.winkler@intel.com>
Date2016-04-03 21:30 +0200
Message-ID<rjVSG-8av-25@gated-at.bofh.it>
In reply to#1370218

On 04/03/2016 02:42 AM, Tomas Winkler wrote:
> Few storage technology such is EMMC, UFS, and NVMe support RPMB 
> hardware partition with common protocol and frame layout.
> The RPMB partition cannot be accessed via standard block layer, but by 
> a set of specific commands: WRITE, READ, GET_WRITE_COUNTER, and 
> PROGRAM_KEY.
> Such a partition provides authenticated and replay protected access, 
> hence suitable as a secure storage.
>
> A storage device registers its RPMB hardware (emmc) partition or RPMB 
> W-LUN (ufs) with the RPMB layer providing an implementation for
> send_rpmb_req() handler.
> Tere is as well simulation platform device. This is handy as an RPMB 
> key can be programmed only once at storage device lifetime.
>
> The RPMB layer aims to provide in-kernel API for Trusted Execution 
> Environment (TEE) devices that are capable to securely compute block 
> frame signature. A TEE driver can claim rpmb interface, for example, 
> via  class_interface_register ().

What's the workflow?  Does the TEE ask the kernel to do RPMB operations for it and supply the kernel with the authenticated request blobs to forward to the RPMB?

Exactly, though it's not exactly a blob, just the data part,  but it has to have the whole frame in orther to copute the signature correctly.   Neither emmc nor ufs  have dual head so a TEE device cannot access the RPMB partition directly and the access has to done via kernel storage device.

Thanks
Tomas 

[toc] | [prev] | [standalone]


Back to top | Article view | linux.kernel


csiph-web