mbox series

[v4,0/9] CXL 2.0 Support

Message ID 20210216014538.268106-1-ben.widawsky@intel.com
Headers show
Series CXL 2.0 Support | expand

Message

Ben Widawsky Feb. 16, 2021, 1:45 a.m. UTC
# Changes since v3 [1]

* Fix use of GET_SUPPORTED_LOGS (Ben)
  * Reported by Dan
* Rework userspace commands (Al, Dan)
  * Don't get_user twice (Al)
  * Don't pass __user @u to handle_mailbox_cmd_from_user()  (Dan)
* Use void * in cxl_mem_mbox_send_cmd() (Dan)
* Fix for 32b builds (Stephen, Randy, more)
  * Include io-64-nonatomic-lo-hi.h in mem.c
  * Use GENMASK_ULL where appropriate

---

In addition to the mailing list, please feel free to use #cxl on oftc IRC for
discussion.

---

# Summary

Introduce support for “type-3” memory devices defined in the Compute Express
Link (CXL) 2.0 specification [2]. Specifically, these are the memory devices
defined by section 8.2.8.5 of the CXL 2.0 spec. A reference implementation
emulating these devices has been submitted to the QEMU mailing list [3] and is
available on gitlab [4], but will move to a shared tree on kernel.org after
initial acceptance. “Type-3” is a CXL device that acts as a memory expander for
RAM or Persistent Memory. The device might be interleaved with other CXL devices
in a given physical address range.

In addition to the core functionality of discovering the spec defined registers
and resources, introduce a CXL device model that will be the foundation for
translating CXL capabilities into existing Linux infrastructure for Persistent
Memory and other memory devices. For now, this only includes support for the
management command mailbox the surfacing of type-3 devices. These control
devices fill the role of “DIMMs” / nmemX memory-devices in LIBNVDIMM terms.

## Userspace Interaction

Interaction with the driver and type-3 devices via the CXL drivers is introduced
in this patch series and considered stable ABI. They include

   * sysfs - Documentation/ABI/testing/sysfs-bus-cxl
   * IOCTL - Documentation/driver-api/cxl/memory-devices.rst
   * debugfs - Documentation/ABI/testing/debugfs-debug

Work is in process to add support for CXL interactions to the ndctl project [5]

### Development plans

One of the unique challenges that CXL imposes on the Linux driver model is that
it requires the operating system to perform physical address space management
interleaved across devices and bridges. Whereas LIBNVDIMM handles a list of
established static persistent memory address ranges (for example from the ACPI
NFIT), CXL introduces hotplug and the concept of allocating address space to
instantiate persistent memory ranges. This is similar to PCI in the sense that
the platform establishes the MMIO range for PCI BARs to be allocated, but it is
significantly complicated by the fact that a given device can optionally be
interleaved with other devices and can participate in several interleave-sets at
once. LIBNVDIMM handled something like this with the aliasing between PMEM and
BLOCK-WINDOW mode, but CXL adds flexibility to alias DEVICE MEMORY through up to
10 decoders per device.

All of the above needs to be enabled with respect to PCI hotplug events on
Type-3 memory device which needs hooks to determine if a given device is
contributing to a "System RAM" address range that is unable to be unplugged. In
other words CXL ties PCI hotplug to Memory Hotplug and PCI hotplug needs to be
able to negotiate with memory hotplug.  In the medium term the implications of
CXL hotplug vs ACPI SRAT/SLIT/HMAT need to be reconciled. One capability that
seems to be needed is either the dynamic allocation of new memory nodes, or
default initializing extra pgdat instances beyond what is enumerated in ACPI
SRAT to accommodate hot-added CXL memory.

Patches welcome, questions welcome as the development effort on the post v5.12
capabilities proceeds.

## Running in QEMU

The incantation to get CXL support in QEMU [4] is considered unstable at this
time. Future readers of this cover letter should verify if any changes are
needed. For the novice QEMU user, the following can be copy/pasted into a
working QEMU commandline. It is enough to make the simplest topology possible.
The topology would consist of a single memory window, single type3 device,
single root port, and single host bridge.

    +-------------+
    |   CXL PXB   |
    |             |
    |  +-------+  |<----------+
    |  |CXL RP |  |           |
    +--+-------+--+           v
           |            +----------+
           |            | "window" |
           |            +----------+
           v                  ^
    +-------------+           |
    |  CXL Type 3 |           |
    |   Device    |<----------+
    +-------------+

// Memory backend for "window"
-object memory-backend-file,id=cxl-mem1,share,mem-path=cxl-type3,size=512M

// Memory backend for LSA
-object memory-backend-file,id=cxl-mem1-lsa,share,mem-path=cxl-mem1-lsa,size=1K

// Host Bridge
-device pxb-cxl id=cxl.0,bus=pcie.0,bus_nr=52,uid=0 len-window-base=1,window-base[0]=0x4c0000000 memdev[0]=cxl-mem1

// Single root port
-device cxl rp,id=rp0,bus=cxl.0,addr=0.0,chassis=0,slot=0,memdev=cxl-mem1

// Single type3 device
-device cxl-type3,bus=rp0,memdev=cxl-mem1,id=cxl-pmem0,size=256M -device cxl-type3,bus=rp1,memdev=cxl-mem1,id=cxl-pmem1,size=256M,lsa=cxl-mem1-lsa

---

[1]: https://lore.kernel.org/linux-cxl/20210212222541.2123505-1-ben.widawsky@intel.com/
[2]: https://www.computeexpresslink.org/](https://www.computeexpresslink.org/
[3]: https://lore.kernel.org/qemu-devel/20210202005948.241655-1-ben.widawsky@intel.com/
[4]: https://gitlab.com/bwidawsk/qemu/-/tree/cxl-2.0v4
[5]: https://github.com/pmem/ndctl/tree/cxl-2.0v2

Cc: linux-acpi@vger.kernel.org
Cc: linux-kernel@vger.kernel.org
Cc: linux-nvdimm@lists.01.org
Cc: linux-pci@vger.kernel.org
Cc: Bjorn Helgaas <helgaas@kernel.org>
Cc: Chris Browy <cbrowy@avery-design.com>
Cc: Christoph Hellwig <hch@infradead.org>
Cc: Dan Williams <dan.j.williams@intel.com>
Cc: David Hildenbrand <david@redhat.com>
Cc: David Rientjes <rientjes@google.com>
Cc: Ira Weiny <ira.weiny@intel.com>
Cc: Jon Masters <jcm@jonmasters.org>
Cc: Jonathan Cameron <Jonathan.Cameron@Huawei.com>
Cc: Rafael Wysocki <rafael.j.wysocki@intel.com>
Cc: Randy Dunlap <rdunlap@infradead.org>
Cc: Vishal Verma <vishal.l.verma@intel.com>
Cc: "John Groves (jgroves)" <jgroves@micron.com>
Cc: "Kelley, Sean V" <sean.v.kelley@intel.com>

---

Ben Widawsky (7):
  cxl/mem: Find device capabilities
  cxl/mem: Add basic IOCTL interface
  cxl/mem: Add a "RAW" send command
  cxl/mem: Enable commands via CEL
  cxl/mem: Add set of informational commands
  MAINTAINERS: Add maintainers of the CXL driver
  cxl/mem: Add payload dumping for debug

Dan Williams (2):
  cxl/mem: Introduce a driver for CXL-2.0-Type-3 endpoints
  cxl/mem: Register CXL memX devices

 .clang-format                                 |    1 +
 Documentation/ABI/testing/sysfs-bus-cxl       |   26 +
 Documentation/driver-api/cxl/index.rst        |   12 +
 .../driver-api/cxl/memory-devices.rst         |   46 +
 Documentation/driver-api/index.rst            |    1 +
 .../userspace-api/ioctl/ioctl-number.rst      |    1 +
 MAINTAINERS                                   |   11 +
 drivers/Kconfig                               |    1 +
 drivers/Makefile                              |    1 +
 drivers/cxl/Kconfig                           |   66 +
 drivers/cxl/Makefile                          |    7 +
 drivers/cxl/bus.c                             |   29 +
 drivers/cxl/cxl.h                             |   93 +
 drivers/cxl/mem.c                             | 1540 +++++++++++++++++
 drivers/cxl/pci.h                             |   31 +
 include/linux/pci_ids.h                       |    1 +
 include/uapi/linux/cxl_mem.h                  |  170 ++
 17 files changed, 2037 insertions(+)
 create mode 100644 Documentation/ABI/testing/sysfs-bus-cxl
 create mode 100644 Documentation/driver-api/cxl/index.rst
 create mode 100644 Documentation/driver-api/cxl/memory-devices.rst
 create mode 100644 drivers/cxl/Kconfig
 create mode 100644 drivers/cxl/Makefile
 create mode 100644 drivers/cxl/bus.c
 create mode 100644 drivers/cxl/cxl.h
 create mode 100644 drivers/cxl/mem.c
 create mode 100644 drivers/cxl/pci.h
 create mode 100644 include/uapi/linux/cxl_mem.h

Comments

Jonathan Cameron Feb. 16, 2021, 3:30 p.m. UTC | #1
On Mon, 15 Feb 2021 17:45:34 -0800
Ben Widawsky <ben.widawsky@intel.com> wrote:

> The CXL memory device send interface will have a number of supported
> commands. The raw command is not such a command. Raw commands allow
> userspace to send a specified opcode to the underlying hardware and
> bypass all driver checks on the command. The primary use for this
> command is to [begrudgingly] allow undocumented vendor specific hardware
> commands.
> 
> While not the main motivation, it also allows prototyping new hardware
> commands without a driver patch and rebuild.
> 
> While this all sounds very powerful it comes with a couple of caveats:
> 1. Bug reports using raw commands will not get the same level of
>    attention as bug reports using supported commands (via taint).
> 2. Supported commands will be rejected by the RAW command.
> 
> With this comes new debugfs knob to allow full access to your toes with
> your weapon of choice.
> 
> Cc: Ariel Sibley <Ariel.Sibley@microchip.com>
> Signed-off-by: Ben Widawsky <ben.widawsky@intel.com>
> Reviewed-by: Dan Williams <dan.j.williams@intel.com> (v2)

Whilst I'm definitely dubious about introducing this interface
so early in development, I haven't found any problems with 'how' it
has been done.

I guess it's now just up to us to hassle our hardware colleagues into
only using this facility when absolutely necessary...

Reviewed-by: Jonathan Cameron <Jonathan.Cameron@huawei.com>

> ---
>  drivers/cxl/Kconfig          |  18 +++++
>  drivers/cxl/mem.c            | 132 +++++++++++++++++++++++++++++++++++
>  include/uapi/linux/cxl_mem.h |  12 +++-
>  3 files changed, 161 insertions(+), 1 deletion(-)
> 
> diff --git a/drivers/cxl/Kconfig b/drivers/cxl/Kconfig
> index 9e80b311e928..97dc4d751651 100644
> --- a/drivers/cxl/Kconfig
> +++ b/drivers/cxl/Kconfig
> @@ -32,4 +32,22 @@ config CXL_MEM
>  	  Chapter 2.3 Type 3 CXL Device in the CXL 2.0 specification.
>  
>  	  If unsure say 'm'.
> +
> +config CXL_MEM_RAW_COMMANDS
> +	bool "RAW Command Interface for Memory Devices"
> +	depends on CXL_MEM
> +	help
> +	  Enable CXL RAW command interface.
> +
> +	  The CXL driver ioctl interface may assign a kernel ioctl command
> +	  number for each specification defined opcode. At any given point in
> +	  time the number of opcodes that the specification defines and a device
> +	  may implement may exceed the kernel's set of associated ioctl function
> +	  numbers. The mismatch is either by omission, specification is too new,
> +	  or by design. When prototyping new hardware, or developing / debugging
> +	  the driver it is useful to be able to submit any possible command to
> +	  the hardware, even commands that may crash the kernel due to their
> +	  potential impact to memory currently in use by the kernel.
> +
> +	  If developing CXL hardware or the driver say Y, otherwise say N.
>  endif
> diff --git a/drivers/cxl/mem.c b/drivers/cxl/mem.c
> index a4298cb1182d..6b4feb0ce47d 100644
> --- a/drivers/cxl/mem.c
> +++ b/drivers/cxl/mem.c
> @@ -1,6 +1,8 @@
>  // SPDX-License-Identifier: GPL-2.0-only
>  /* Copyright(c) 2020 Intel Corporation. All rights reserved. */
>  #include <uapi/linux/cxl_mem.h>
> +#include <linux/security.h>
> +#include <linux/debugfs.h>
>  #include <linux/module.h>
>  #include <linux/mutex.h>
>  #include <linux/cdev.h>
> @@ -42,7 +44,14 @@
>  
>  enum opcode {
>  	CXL_MBOX_OP_INVALID		= 0x0000,
> +	CXL_MBOX_OP_RAW			= CXL_MBOX_OP_INVALID,
> +	CXL_MBOX_OP_ACTIVATE_FW		= 0x0202,
>  	CXL_MBOX_OP_IDENTIFY		= 0x4000,
> +	CXL_MBOX_OP_SET_PARTITION_INFO	= 0x4101,
> +	CXL_MBOX_OP_SET_LSA		= 0x4103,
> +	CXL_MBOX_OP_SET_SHUTDOWN_STATE	= 0x4204,
> +	CXL_MBOX_OP_SCAN_MEDIA		= 0x4304,
> +	CXL_MBOX_OP_GET_SCAN_MEDIA	= 0x4305,
>  	CXL_MBOX_OP_MAX			= 0x10000
>  };
>  
> @@ -92,6 +101,8 @@ struct cxl_memdev {
>  
>  static int cxl_mem_major;
>  static DEFINE_IDA(cxl_memdev_ida);
> +static struct dentry *cxl_debugfs;
> +static bool cxl_raw_allow_all;
>  
>  /**
>   * struct cxl_mem_command - Driver representation of a memory device command
> @@ -128,6 +139,49 @@ struct cxl_mem_command {
>   */
>  static struct cxl_mem_command mem_commands[] = {
>  	CXL_CMD(IDENTIFY, 0, 0x43),
> +#ifdef CONFIG_CXL_MEM_RAW_COMMANDS
> +	CXL_CMD(RAW, ~0, ~0),
> +#endif
> +};
> +
> +/*
> + * Commands that RAW doesn't permit. The rationale for each:
> + *
> + * CXL_MBOX_OP_ACTIVATE_FW: Firmware activation requires adjustment /
> + * coordination of transaction timeout values at the root bridge level.
> + *
> + * CXL_MBOX_OP_SET_PARTITION_INFO: The device memory map may change live
> + * and needs to be coordinated with HDM updates.
> + *
> + * CXL_MBOX_OP_SET_LSA: The label storage area may be cached by the
> + * driver and any writes from userspace invalidates those contents.
> + *
> + * CXL_MBOX_OP_SET_SHUTDOWN_STATE: Set shutdown state assumes no writes
> + * to the device after it is marked clean, userspace can not make that
> + * assertion.
> + *
> + * CXL_MBOX_OP_[GET_]SCAN_MEDIA: The kernel provides a native error list that
> + * is kept up to date with patrol notifications and error management.
> + */
> +static u16 cxl_disabled_raw_commands[] = {
> +	CXL_MBOX_OP_ACTIVATE_FW,
> +	CXL_MBOX_OP_SET_PARTITION_INFO,
> +	CXL_MBOX_OP_SET_LSA,
> +	CXL_MBOX_OP_SET_SHUTDOWN_STATE,
> +	CXL_MBOX_OP_SCAN_MEDIA,
> +	CXL_MBOX_OP_GET_SCAN_MEDIA,
> +};
> +
> +/*
> + * Command sets that RAW doesn't permit. All opcodes in this set are
> + * disabled because they pass plain text security payloads over the
> + * user/kernel boundary. This functionality is intended to be wrapped
> + * behind the keys ABI which allows for encrypted payloads in the UAPI
> + */
> +static u8 security_command_sets[] = {
> +	0x44, /* Sanitize */
> +	0x45, /* Persistent Memory Data-at-rest Security */
> +	0x46, /* Security Passthrough */
>  };
>  
>  #define cxl_for_each_cmd(cmd)                                                  \
> @@ -158,6 +212,16 @@ static int cxl_mem_wait_for_doorbell(struct cxl_mem *cxlm)
>  	return 0;
>  }
>  
> +static bool cxl_is_security_command(u16 opcode)
> +{
> +	int i;
> +
> +	for (i = 0; i < ARRAY_SIZE(security_command_sets); i++)
> +		if (security_command_sets[i] == (opcode >> 8))
> +			return true;
> +	return false;
> +}
> +
>  static void cxl_mem_mbox_timeout(struct cxl_mem *cxlm,
>  				 struct mbox_cmd *mbox_cmd)
>  {
> @@ -426,6 +490,9 @@ static int handle_mailbox_cmd_from_user(struct cxl_mem *cxlm,
>  		cxl_command_names[cmd->info.id].name, mbox_cmd.opcode,
>  		cmd->info.size_in);
>  
> +	dev_WARN_ONCE(dev, cmd->info.id == CXL_MEM_COMMAND_ID_RAW,
> +		      "raw command path used\n");
> +
>  	rc = __cxl_mem_mbox_send_cmd(cxlm, &mbox_cmd);
>  	cxl_mem_mbox_put(cxlm);
>  	if (rc)
> @@ -457,6 +524,29 @@ static int handle_mailbox_cmd_from_user(struct cxl_mem *cxlm,
>  	return rc;
>  }
>  
> +static bool cxl_mem_raw_command_allowed(u16 opcode)
> +{
> +	int i;
> +
> +	if (!IS_ENABLED(CONFIG_CXL_MEM_RAW_COMMANDS))
> +		return false;
> +
> +	if (security_locked_down(LOCKDOWN_NONE))
> +		return false;
> +
> +	if (cxl_raw_allow_all)
> +		return true;
> +
> +	if (cxl_is_security_command(opcode))
> +		return false;
> +
> +	for (i = 0; i < ARRAY_SIZE(cxl_disabled_raw_commands); i++)
> +		if (cxl_disabled_raw_commands[i] == opcode)
> +			return false;
> +
> +	return true;
> +}
> +
>  /**
>   * cxl_validate_cmd_from_user() - Check fields for CXL_MEM_SEND_COMMAND.
>   * @cxlm: &struct cxl_mem device whose mailbox will be used.
> @@ -468,6 +558,7 @@ static int handle_mailbox_cmd_from_user(struct cxl_mem *cxlm,
>   *  * %-ENOTTY	- Invalid command specified.
>   *  * %-EINVAL	- Reserved fields or invalid values were used.
>   *  * %-ENOMEM	- Input or output buffer wasn't sized properly.
> + *  * %-EPERM	- Attempted to use a protected command.
>   *
>   * The result of this command is a fully validated command in @out_cmd that is
>   * safe to send to the hardware.
> @@ -492,6 +583,40 @@ static int cxl_validate_cmd_from_user(struct cxl_mem *cxlm,
>  	if (send_cmd->in.size > cxlm->payload_size)
>  		return -EINVAL;
>  
> +	/*
> +	 * Checks are bypassed for raw commands but a WARN/taint will occur
> +	 * later in the callchain
> +	 */
> +	if (send_cmd->id == CXL_MEM_COMMAND_ID_RAW) {
> +		const struct cxl_mem_command temp = {
> +			.info = {
> +				.id = CXL_MEM_COMMAND_ID_RAW,
> +				.flags = 0,
> +				.size_in = send_cmd->in.size,
> +				.size_out = send_cmd->out.size,
> +			},
> +			.opcode = send_cmd->raw.opcode
> +		};
> +
> +		if (send_cmd->raw.rsvd)
> +			return -EINVAL;
> +
> +		/*
> +		 * Unlike supported commands, the output size of RAW commands
> +		 * gets passed along without further checking, so it must be
> +		 * validated here.
> +		 */
> +		if (send_cmd->out.size > cxlm->payload_size)
> +			return -EINVAL;
> +
> +		if (!cxl_mem_raw_command_allowed(send_cmd->raw.opcode))
> +			return -EPERM;
> +
> +		memcpy(out_cmd, &temp, sizeof(temp));
> +
> +		return 0;
> +	}
> +
>  	if (send_cmd->flags & ~CXL_MEM_COMMAND_FLAG_MASK)
>  		return -EINVAL;
>  
> @@ -1153,6 +1278,7 @@ static struct pci_driver cxl_mem_driver = {
>  
>  static __init int cxl_mem_init(void)
>  {
> +	struct dentry *mbox_debugfs;
>  	dev_t devt;
>  	int rc;
>  
> @@ -1169,11 +1295,17 @@ static __init int cxl_mem_init(void)
>  		return rc;
>  	}
>  
> +	cxl_debugfs = debugfs_create_dir("cxl", NULL);
> +	mbox_debugfs = debugfs_create_dir("mbox", cxl_debugfs);
> +	debugfs_create_bool("raw_allow_all", 0600, mbox_debugfs,
> +			    &cxl_raw_allow_all);
> +
>  	return 0;
>  }
>  
>  static __exit void cxl_mem_exit(void)
>  {
> +	debugfs_remove_recursive(cxl_debugfs);
>  	pci_unregister_driver(&cxl_mem_driver);
>  	unregister_chrdev_region(MKDEV(cxl_mem_major, 0), CXL_MEM_MAX_DEVS);
>  }
> diff --git a/include/uapi/linux/cxl_mem.h b/include/uapi/linux/cxl_mem.h
> index 18cea908ad0b..8eb669150ecb 100644
> --- a/include/uapi/linux/cxl_mem.h
> +++ b/include/uapi/linux/cxl_mem.h
> @@ -22,6 +22,7 @@
>  #define CXL_CMDS                                                          \
>  	___C(INVALID, "Invalid Command"),                                 \
>  	___C(IDENTIFY, "Identify Command"),                               \
> +	___C(RAW, "Raw device command"),                                  \
>  	___C(MAX, "invalid / last command")
>  
>  #define ___C(a, b) CXL_MEM_COMMAND_ID_##a
> @@ -115,6 +116,9 @@ struct cxl_mem_query_commands {
>   * @id: The command to send to the memory device. This must be one of the
>   *	commands returned by the query command.
>   * @flags: Flags for the command (input).
> + * @raw: Special fields for raw commands
> + * @raw.opcode: Opcode passed to hardware when using the RAW command.
> + * @raw.rsvd: Must be zero.
>   * @rsvd: Must be zero.
>   * @retval: Return value from the memory device (output).
>   * @in.size: Size of the payload to provide to the device (input).
> @@ -135,7 +139,13 @@ struct cxl_mem_query_commands {
>  struct cxl_send_command {
>  	__u32 id;
>  	__u32 flags;
> -	__u32 rsvd;
> +	union {
> +		struct {
> +			__u16 opcode;
> +			__u16 rsvd;
> +		} raw;
> +		__u32 rsvd;
> +	};
>  	__u32 retval;
>  
>  	struct {
Jonathan Cameron Feb. 16, 2021, 3:48 p.m. UTC | #2
On Mon, 15 Feb 2021 17:45:38 -0800
Ben Widawsky <ben.widawsky@intel.com> wrote:

> It's often useful in debug scenarios to see what the hardware has dumped
> out. As it stands today, any device error will result in the payload not
> being copied out, so there is no way to triage commands which weren't
> expected to fail (and sometimes the payload may have that information).
> 
> The functionality is protected by normal kernel security mechanisms as
> well as a CONFIG option in the CXL driver.
> 
> This was extracted from the original version of the CXL enabling patch
> series.
> 
> Signed-off-by: Ben Widawsky <ben.widawsky@intel.com>

My gut feeling here is use a tracepoint rather than spamming the kernel
log.  Alternatively just don't bother merging this patch - it's on the list
now anyway so trivial for anyone doing such debug to pick it up.

Jonathan



> ---
>  drivers/cxl/Kconfig | 13 +++++++++++++
>  drivers/cxl/mem.c   |  8 ++++++++
>  2 files changed, 21 insertions(+)
> 
> diff --git a/drivers/cxl/Kconfig b/drivers/cxl/Kconfig
> index 97dc4d751651..3eec9276e586 100644
> --- a/drivers/cxl/Kconfig
> +++ b/drivers/cxl/Kconfig
> @@ -50,4 +50,17 @@ config CXL_MEM_RAW_COMMANDS
>  	  potential impact to memory currently in use by the kernel.
>  
>  	  If developing CXL hardware or the driver say Y, otherwise say N.
> +
> +config CXL_MEM_INSECURE_DEBUG
> +	bool "CXL.mem debugging"
> +	depends on CXL_MEM
> +	help
> +	  Enable debug of all CXL command payloads.
> +
> +	  Some CXL devices and controllers support encryption and other
> +	  security features. The payloads for the commands that enable
> +	  those features may contain sensitive clear-text security
> +	  material. Disable debug of those command payloads by default.
> +	  If you are a kernel developer actively working on CXL
> +	  security enabling say Y, otherwise say N.
>  endif
> diff --git a/drivers/cxl/mem.c b/drivers/cxl/mem.c
> index dc608bb20a31..237b956f0be0 100644
> --- a/drivers/cxl/mem.c
> +++ b/drivers/cxl/mem.c
> @@ -342,6 +342,14 @@ static int __cxl_mem_mbox_send_cmd(struct cxl_mem *cxlm,
>  
>  	/* #5 */
>  	rc = cxl_mem_wait_for_doorbell(cxlm);
> +
> +	if (!cxl_is_security_command(mbox_cmd->opcode) ||
> +	    IS_ENABLED(CONFIG_CXL_MEM_INSECURE_DEBUG)) {
> +		print_hex_dump_debug("Payload ", DUMP_PREFIX_OFFSET, 16, 1,
> +				     mbox_cmd->payload_in, mbox_cmd->size_in,
> +				     true);
> +	}
> +
>  	if (rc == -ETIMEDOUT) {
>  		cxl_mem_mbox_timeout(cxlm, mbox_cmd);
>  		return rc;
Ben Widawsky Feb. 16, 2021, 4:43 p.m. UTC | #3
On 21-02-16 14:51:48, Jonathan Cameron wrote:
> On Mon, 15 Feb 2021 17:45:31 -0800
> Ben Widawsky <ben.widawsky@intel.com> wrote:
> 
> > Provide enough functionality to utilize the mailbox of a memory device.
> > The mailbox is used to interact with the firmware running on the memory
> > device. The flow is proven with one implemented command, "identify".
> > Because the class code has already told the driver this is a memory
> > device and the identify command is mandatory.
> > 
> > CXL devices contain an array of capabilities that describe the
> > interactions software can have with the device or firmware running on
> > the device. A CXL compliant device must implement the device status and
> > the mailbox capability. Additionally, a CXL compliant memory device must
> > implement the memory device capability. Each of the capabilities can
> > [will] provide an offset within the MMIO region for interacting with the
> > CXL device.
> > 
> > The capabilities tell the driver how to find and map the register space
> > for CXL Memory Devices. The registers are required to utilize the CXL
> > spec defined mailbox interface. The spec outlines two mailboxes, primary
> > and secondary. The secondary mailbox is earmarked for system firmware,
> > and not handled in this driver.
> > 
> > Primary mailboxes are capable of generating an interrupt when submitting
> > a background command. That implementation is saved for a later time.
> > 
> > Link: https://www.computeexpresslink.org/download-the-specification
> > Signed-off-by: Ben Widawsky <ben.widawsky@intel.com>
> > Reviewed-by: Dan Williams <dan.j.williams@intel.com> (v2)
> 
> Looks like an off by one error in the register locator iteration.
> 
> The potential buffer overrun from memcpy_fromio is still there as well
> as far as I can see.
> 
> If the software provides storage for a payload of size n and the hardware
> reports a size of n + d, code will happily write beyond the end of the
> storage provided.
> 
> Obviously, this shouldn't happen, but I'm not that trusting of both
> hardware and software never having bugs.
> 
> Jonathan
> 
> > ---
> >  drivers/cxl/cxl.h |  88 ++++++++
> >  drivers/cxl/mem.c | 543 +++++++++++++++++++++++++++++++++++++++++++++-
> >  drivers/cxl/pci.h |  14 ++
> >  3 files changed, 643 insertions(+), 2 deletions(-)
> >  create mode 100644 drivers/cxl/cxl.h
> > 
> ...
> 
> > +
> > +#endif /* __CXL_H__ */
> > diff --git a/drivers/cxl/mem.c b/drivers/cxl/mem.c
> > index ce33c5ee77c9..b86cda2d299a 100644
> > --- a/drivers/cxl/mem.c
> > +++ b/drivers/cxl/mem.c
> > @@ -3,7 +3,458 @@
> >  #include <linux/module.h>
> >  #include <linux/pci.h>
> >  #include <linux/io.h>
> > +#include <linux/io-64-nonatomic-lo-hi.h>
> >  #include "pci.h"
> > +#include "cxl.h"
> > +
> > +#define cxl_doorbell_busy(cxlm)                                                \
> > +	(readl((cxlm)->mbox_regs + CXLDEV_MBOX_CTRL_OFFSET) &                  \
> > +	 CXLDEV_MBOX_CTRL_DOORBELL)
> > +
> > +/* CXL 2.0 - 8.2.8.4 */
> > +#define CXL_MAILBOX_TIMEOUT_MS (2 * HZ)
> > +
> > +enum opcode {
> > +	CXL_MBOX_OP_IDENTIFY		= 0x4000,
> > +	CXL_MBOX_OP_MAX			= 0x10000
> > +};
> > +
> > +/**
> > + * struct mbox_cmd - A command to be submitted to hardware.
> > + * @opcode: (input) The command set and command submitted to hardware.
> > + * @payload_in: (input) Pointer to the input payload.
> > + * @payload_out: (output) Pointer to the output payload. Must be allocated by
> > + *		 the caller.
> > + * @size_in: (input) Number of bytes to load from @payload.
> > + * @size_out: (output) Number of bytes loaded into @payload.
> > + * @return_code: (output) Error code returned from hardware.
> > + *
> > + * This is the primary mechanism used to send commands to the hardware.
> > + * All the fields except @payload_* correspond exactly to the fields described in
> > + * Command Register section of the CXL 2.0 8.2.8.4.5. @payload_in and
> > + * @payload_out are written to, and read from the Command Payload Registers
> > + * defined in CXL 2.0 8.2.8.4.8.
> > + */
> > +struct mbox_cmd {
> > +	u16 opcode;
> > +	void *payload_in;
> > +	void *payload_out;
> > +	size_t size_in;
> > +	size_t size_out;
> > +	u16 return_code;
> > +#define CXL_MBOX_SUCCESS 0
> > +};
> 
> 
> > +
> > +/**
> > + * __cxl_mem_mbox_send_cmd() - Execute a mailbox command
> > + * @cxlm: The CXL memory device to communicate with.
> > + * @mbox_cmd: Command to send to the memory device.
> > + *
> > + * Context: Any context. Expects mbox_mutex to be held.
> > + * Return: -ETIMEDOUT if timeout occurred waiting for completion. 0 on success.
> > + *         Caller should check the return code in @mbox_cmd to make sure it
> > + *         succeeded.
> > + *
> > + * This is a generic form of the CXL mailbox send command thus only using the
> > + * registers defined by the mailbox capability ID - CXL 2.0 8.2.8.4. Memory
> > + * devices, and perhaps other types of CXL devices may have further information
> > + * available upon error conditions. Driver facilities wishing to send mailbox
> > + * commands should use the wrapper command.
> > + *
> > + * The CXL spec allows for up to two mailboxes. The intention is for the primary
> > + * mailbox to be OS controlled and the secondary mailbox to be used by system
> > + * firmware. This allows the OS and firmware to communicate with the device and
> > + * not need to coordinate with each other. The driver only uses the primary
> > + * mailbox.
> > + */
> > +static int __cxl_mem_mbox_send_cmd(struct cxl_mem *cxlm,
> > +				   struct mbox_cmd *mbox_cmd)
> > +{
> > +	void __iomem *payload = cxlm->mbox_regs + CXLDEV_MBOX_PAYLOAD_OFFSET;
> > +	u64 cmd_reg, status_reg;
> > +	size_t out_len;
> > +	int rc;
> > +
> > +	lockdep_assert_held(&cxlm->mbox_mutex);
> > +
> > +	/*
> > +	 * Here are the steps from 8.2.8.4 of the CXL 2.0 spec.
> > +	 *   1. Caller reads MB Control Register to verify doorbell is clear
> > +	 *   2. Caller writes Command Register
> > +	 *   3. Caller writes Command Payload Registers if input payload is non-empty
> > +	 *   4. Caller writes MB Control Register to set doorbell
> > +	 *   5. Caller either polls for doorbell to be clear or waits for interrupt if configured
> > +	 *   6. Caller reads MB Status Register to fetch Return code
> > +	 *   7. If command successful, Caller reads Command Register to get Payload Length
> > +	 *   8. If output payload is non-empty, host reads Command Payload Registers
> > +	 *
> > +	 * Hardware is free to do whatever it wants before the doorbell is rung,
> > +	 * and isn't allowed to change anything after it clears the doorbell. As
> > +	 * such, steps 2 and 3 can happen in any order, and steps 6, 7, 8 can
> > +	 * also happen in any order (though some orders might not make sense).
> > +	 */
> > +
> > +	/* #1 */
> > +	if (cxl_doorbell_busy(cxlm)) {
> > +		dev_err_ratelimited(&cxlm->pdev->dev,
> > +				    "Mailbox re-busy after acquiring\n");
> > +		return -EBUSY;
> > +	}
> > +
> > +	cmd_reg = FIELD_PREP(CXLDEV_MBOX_CMD_COMMAND_OPCODE_MASK,
> > +			     mbox_cmd->opcode);
> > +	if (mbox_cmd->size_in) {
> > +		if (WARN_ON(!mbox_cmd->payload_in))
> > +			return -EINVAL;
> > +
> > +		cmd_reg |= FIELD_PREP(CXLDEV_MBOX_CMD_PAYLOAD_LENGTH_MASK,
> > +				      mbox_cmd->size_in);
> > +		memcpy_toio(payload, mbox_cmd->payload_in, mbox_cmd->size_in);
> > +	}
> > +
> > +	/* #2, #3 */
> > +	writeq(cmd_reg, cxlm->mbox_regs + CXLDEV_MBOX_CMD_OFFSET);
> > +
> > +	/* #4 */
> > +	dev_dbg(&cxlm->pdev->dev, "Sending command\n");
> > +	writel(CXLDEV_MBOX_CTRL_DOORBELL,
> > +	       cxlm->mbox_regs + CXLDEV_MBOX_CTRL_OFFSET);
> > +
> > +	/* #5 */
> > +	rc = cxl_mem_wait_for_doorbell(cxlm);
> > +	if (rc == -ETIMEDOUT) {
> > +		cxl_mem_mbox_timeout(cxlm, mbox_cmd);
> > +		return rc;
> > +	}
> > +
> > +	/* #6 */
> > +	status_reg = readq(cxlm->mbox_regs + CXLDEV_MBOX_STATUS_OFFSET);
> > +	mbox_cmd->return_code =
> > +		FIELD_GET(CXLDEV_MBOX_STATUS_RET_CODE_MASK, status_reg);
> > +
> > +	if (mbox_cmd->return_code != 0) {
> > +		dev_dbg(&cxlm->pdev->dev, "Mailbox operation had an error\n");
> > +		return 0;
> > +	}
> > +
> > +	/* #7 */
> > +	cmd_reg = readq(cxlm->mbox_regs + CXLDEV_MBOX_CMD_OFFSET);
> > +	out_len = FIELD_GET(CXLDEV_MBOX_CMD_PAYLOAD_LENGTH_MASK, cmd_reg);
> > +
> > +	/* #8 */
> > +	if (out_len && mbox_cmd->payload_out) {
> > +		size_t n = min_t(size_t, cxlm->payload_size, out_len);
> 
> This doesn't protect us from the case where the hardware
> returns a larger payload than the caller is expecting.
> 
> i.e. payload_out is too small.  We need to pass in the size of that buffer as
> well.   This currently clamps to the size of the source buffer but does not
> check if there is enough space at the destination (mbox_cmd->payload_out).
> 

Let me articulate the issue a bit. The userspace call chain should be fine:
cxl_send_cmd() -> ioctl handlers
  cxl_validate_cmd_from_user -> converts to internal command
    handle_mailbox_cmd_from_user -> dispatches mbox command.

cxl_send_cmd():
  if (c.info.size_out < 0)
    c.info.size_out = cxlm->payload_size;

handle_mailbox_cmd_from_user():
  if (cmd->info.size_out) {
     mbox_cmd.payload_out = kvzalloc(cmd->info.size_out, GFP_KERNEL);


The kernel call chain could have issues:
cxl_mem_identify/*() -> kernel caller allocates just enough space
  cxl_mem_mbox_send_cmd() -> internal wrapper we created for v3
    blows up in the spot you mention.

The driver allocates enough space on the stack for all these calls, but yes, if
hardware is out of spec it would be problematic. In previous versions of this
series, there has been a check there. However, the ability to have hardware
return more data than expected is I believe the correct functionality here.

So my proposal is for now, since no real hardware exists, and the command set
here is so benign, we leave fixing this as a TODO.

I can post a patch on top of this series to address this issue in a manner I
believe warrants discussing (kvzalloc max payload size buffers on open() and for
each driver instance).

> > +
> > +		memcpy_fromio(mbox_cmd->payload_out, payload, n);
> > +		mbox_cmd->size_out = n;
> > +	} else {
> > +		mbox_cmd->size_out = 0;
> > +	}
> > +
> > +	return 0;
> > +}
> > +
> 
> ...
> 
> > +
> > +/**
> > + * cxl_mem_mbox_send_cmd() - Send a mailbox command to a memory device.
> > + * @cxlm: The CXL memory device to communicate with.
> > + * @opcode: Opcode for the mailbox command.
> > + * @in: The input payload for the mailbox command.
> > + * @in_size: The length of the input payload
> > + * @out: Caller allocated buffer for the output.
> > + * @out_min_size: Minimum expected size of output.
> > + *
> > + * Context: Any context. Will acquire and release mbox_mutex.
> > + * Return:
> > + *  * %>=0	- Number of bytes returned in @out.
> > + *  * %-E2BIG	- Payload is too large for hardware.
> > + *  * %-EBUSY	- Couldn't acquire exclusive mailbox access.
> > + *  * %-EFAULT	- Hardware error occurred.
> > + *  * %-ENXIO	- Command completed, but device reported an error.
> > + *  * %-ENODATA	- Not enough payload data returned by hardware.
> > + *
> > + * Mailbox commands may execute successfully yet the device itself reported an
> > + * error. While this distinction can be useful for commands from userspace, the
> > + * kernel will only be able to use results when both are successful.
> > + *
> > + * See __cxl_mem_mbox_send_cmd()
> > + */
> > +static int cxl_mem_mbox_send_cmd(struct cxl_mem *cxlm, u16 opcode, void *in,
> > +				 size_t in_size, void *out, size_t out_min_size)
> > +{
> > +	struct mbox_cmd mbox_cmd = {
> > +		.opcode = opcode,
> > +		.payload_in = in,
> > +		.size_in = in_size,
> > +		.payload_out = out,
> > +	};
> > +	int rc;
> > +
> > +	if (out_min_size > cxlm->payload_size)
> > +		return -E2BIG;
> > +
> > +	rc = cxl_mem_mbox_get(cxlm);
> > +	if (rc)
> > +		return rc;
> > +
> > +	rc = __cxl_mem_mbox_send_cmd(cxlm, &mbox_cmd);
> > +	cxl_mem_mbox_put(cxlm);
> > +	if (rc)
> > +		return rc;
> > +
> > +	/* TODO: Map return code to proper kernel style errno */
> > +	if (mbox_cmd.return_code != CXL_MBOX_SUCCESS)
> > +		return -ENXIO;
> > +
> > +	if (mbox_cmd.size_out < out_min_size)
> > +		return -ENODATA;
> > +
> > +	return mbox_cmd.size_out;
> > +}
> > +
> > +/**
> > + * cxl_mem_setup_regs() - Setup necessary MMIO.
> > + * @cxlm: The CXL memory device to communicate with.
> > + *
> > + * Return: 0 if all necessary registers mapped.
> > + *
> > + * A memory device is required by spec to implement a certain set of MMIO
> > + * regions. The purpose of this function is to enumerate and map those
> > + * registers.
> > + */
> > +static int cxl_mem_setup_regs(struct cxl_mem *cxlm)
> > +{
> > +	struct device *dev = &cxlm->pdev->dev;
> > +	int cap, cap_count;
> > +	u64 cap_array;
> > +
> > +	cap_array = readq(cxlm->regs + CXLDEV_CAP_ARRAY_OFFSET);
> > +	if (FIELD_GET(CXLDEV_CAP_ARRAY_ID_MASK, cap_array) !=
> > +	    CXLDEV_CAP_ARRAY_CAP_ID)
> > +		return -ENODEV;
> > +
> > +	cap_count = FIELD_GET(CXLDEV_CAP_ARRAY_COUNT_MASK, cap_array);
> > +
> > +	for (cap = 1; cap <= cap_count; cap++) {
> > +		void __iomem *register_block;
> > +		u32 offset;
> > +		u16 cap_id;
> > +
> > +		cap_id = readl(cxlm->regs + cap * 0x10) & 0xffff;
> 
> Slight preference for FIELD_GET just for consistency.
> 
> > +		offset = readl(cxlm->regs + cap * 0x10 + 0x4);
> > +		register_block = cxlm->regs + offset;
> > +
> > +		switch (cap_id) {
> > +		case CXLDEV_CAP_CAP_ID_DEVICE_STATUS:
> > +			dev_dbg(dev, "found Status capability (0x%x)\n", offset);
> > +			cxlm->status_regs = register_block;
> > +			break;
> > +		case CXLDEV_CAP_CAP_ID_PRIMARY_MAILBOX:
> > +			dev_dbg(dev, "found Mailbox capability (0x%x)\n", offset);
> > +			cxlm->mbox_regs = register_block;
> > +			break;
> > +		case CXLDEV_CAP_CAP_ID_SECONDARY_MAILBOX:
> > +			dev_dbg(dev, "found Secondary Mailbox capability (0x%x)\n", offset);
> > +			break;
> > +		case CXLDEV_CAP_CAP_ID_MEMDEV:
> > +			dev_dbg(dev, "found Memory Device capability (0x%x)\n", offset);
> > +			cxlm->memdev_regs = register_block;
> > +			break;
> > +		default:
> > +			dev_dbg(dev, "Unknown cap ID: %d (0x%x)\n", cap_id, offset);
> > +			break;
> > +		}
> > +	}
> > +
> > +	if (!cxlm->status_regs || !cxlm->mbox_regs || !cxlm->memdev_regs) {
> > +		dev_err(dev, "registers not found: %s%s%s\n",
> > +			!cxlm->status_regs ? "status " : "",
> > +			!cxlm->mbox_regs ? "mbox " : "",
> > +			!cxlm->memdev_regs ? "memdev" : "");
> > +		return -ENXIO;
> > +	}
> > +
> > +	return 0;
> > +}
> > +
> 
> ...
> 
> > +
> > +static struct cxl_mem *cxl_mem_create(struct pci_dev *pdev, u32 reg_lo,
> > +				      u32 reg_hi)
> 
> I'm not really suggesting you change it at this point, but I'd have
> done the splitting of reg_lo up and the building of the offset at the call site
> rather than in here.  I think that would have been slightly easier to follow.
> 

Noted. In future patches this is going to get reworked somewhat to support more
flexibility with register blocks.

> > +{
> > +	struct device *dev = &pdev->dev;
> > +	struct cxl_mem *cxlm;
> > +	void __iomem *regs;
> > +	u64 offset;
> > +	u8 bar;
> > +	int rc;
> > +
> > +	cxlm = devm_kzalloc(&pdev->dev, sizeof(*cxlm), GFP_KERNEL);
> > +	if (!cxlm) {
> > +		dev_err(dev, "No memory available\n");
> > +		return NULL;
> > +	}
> > +
> > +	offset = ((u64)reg_hi << 32) | FIELD_GET(CXL_REGLOC_ADDR_MASK, reg_lo);
> > +	bar = FIELD_GET(CXL_REGLOC_BIR_MASK, reg_lo);
> > +
> > +	/* Basic sanity check that BAR is big enough */
> > +	if (pci_resource_len(pdev, bar) < offset) {
> > +		dev_err(dev, "BAR%d: %pr: too small (offset: %#llx)\n", bar,
> > +			&pdev->resource[bar], (unsigned long long)offset);
> > +		return NULL;
> > +	}
> > +
> > +	rc = pcim_iomap_regions(pdev, BIT(bar), pci_name(pdev));
> > +	if (rc) {
> > +		dev_err(dev, "failed to map registers\n");
> > +		return NULL;
> > +	}
> > +	regs = pcim_iomap_table(pdev)[bar];
> > +
> > +	mutex_init(&cxlm->mbox_mutex);
> > +	cxlm->pdev = pdev;
> > +	cxlm->regs = regs + offset;
> > +
> > +	dev_dbg(dev, "Mapped CXL Memory Device resource\n");
> > +	return cxlm;
> > +}
> >  
> >  static int cxl_mem_dvsec(struct pci_dev *pdev, int dvsec)
> >  {
> > @@ -28,10 +479,65 @@ static int cxl_mem_dvsec(struct pci_dev *pdev, int dvsec)
> >  	return 0;
> >  }
> >  
> > +/**
> > + * cxl_mem_identify() - Send the IDENTIFY command to the device.
> > + * @cxlm: The device to identify.
> > + *
> > + * Return: 0 if identify was executed successfully.
> > + *
> > + * This will dispatch the identify command to the device and on success populate
> > + * structures to be exported to sysfs.
> > + */
> > +static int cxl_mem_identify(struct cxl_mem *cxlm)
> > +{
> > +	struct cxl_mbox_identify {
> > +		char fw_revision[0x10];
> > +		__le64 total_capacity;
> > +		__le64 volatile_capacity;
> > +		__le64 persistent_capacity;
> > +		__le64 partition_align;
> > +		__le16 info_event_log_size;
> > +		__le16 warning_event_log_size;
> > +		__le16 failure_event_log_size;
> > +		__le16 fatal_event_log_size;
> > +		__le32 lsa_size;
> > +		u8 poison_list_max_mer[3];
> > +		__le16 inject_poison_limit;
> > +		u8 poison_caps;
> > +		u8 qos_telemetry_caps;
> > +	} __packed id;
> > +	int rc;
> > +
> > +	rc = cxl_mem_mbox_send_cmd(cxlm, CXL_MBOX_OP_IDENTIFY, NULL, 0, &id,
> > +				   sizeof(id));
> > +	if (rc < 0)
> > +		return rc;
> > +
> > +	/*
> > +	 * TODO: enumerate DPA map, as 'ram' and 'pmem' do not alias.
> > +	 * For now, only the capacity is exported in sysfs
> > +	 */
> > +	cxlm->ram_range.start = 0;
> > +	cxlm->ram_range.end = le64_to_cpu(id.volatile_capacity) - 1;
> > +
> > +	cxlm->pmem_range.start = 0;
> > +	cxlm->pmem_range.end = le64_to_cpu(id.persistent_capacity) - 1;
> > +
> > +	memcpy(cxlm->firmware_version, id.fw_revision, sizeof(id.fw_revision));
> > +
> > +	return 0;
> > +}
> > +
> >  static int cxl_mem_probe(struct pci_dev *pdev, const struct pci_device_id *id)
> >  {
> >  	struct device *dev = &pdev->dev;
> > -	int regloc;
> > +	struct cxl_mem *cxlm = NULL;
> > +	int rc, regloc, i;
> > +	u32 regloc_size;
> > +
> > +	rc = pcim_enable_device(pdev);
> > +	if (rc)
> > +		return rc;
> >  
> >  	regloc = cxl_mem_dvsec(pdev, PCI_DVSEC_ID_CXL_REGLOC_OFFSET);
> >  	if (!regloc) {
> > @@ -39,7 +545,40 @@ static int cxl_mem_probe(struct pci_dev *pdev, const struct pci_device_id *id)
> >  		return -ENXIO;
> >  	}
> >  
> > -	return 0;
> > +	/* Get the size of the Register Locator DVSEC */
> > +	pci_read_config_dword(pdev, regloc + PCI_DVSEC_HEADER1, &regloc_size);
> > +	regloc_size = FIELD_GET(PCI_DVSEC_HEADER1_LENGTH_MASK, regloc_size);
> 
> The size field here is the dvsec length..  Let's say we only have one register block
> entry at +0x0c and +0x10
> From PCI spec :
> 
> "DVSEC Length - This field indicates the number of bytes in the entire DVSEC structure, including the PCI
> Express Extended Capability Header, the DVSEC Header 1, DVSEC Header 2, and DVSEC vendor-specific
> registers."
> 
> So here it would be 0x14
> 
> > +
> > +	regloc += PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET;
> 
> We then shift regloc forward by +0xc
> 
> > +
> > +	for (i = regloc; i < regloc + regloc_size; i += 8) {
> 
> This loop will then index form
> i= +0xc to i < +0c + 0x14 (0x20)
> i = 0xc, 0x14 
> 
> So that's indexing one more entry than is actually present.
> Should be something like
> 
> 	for (i = regloc;
> 	     i < regloc + regloc_size - PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET;
> 	     i++) 
> 
> which will mean the only iteration for this example is the one with i == +0xC
>

Good catch. I think this warrants rewriting a bit, let me know what you think?

regloc += PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET;
regblocks = (regloc_size - PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET) / 8;

for (i = 0; i < regblocks; i++, regloc+=8) {
	pci_read_config_dword(pdev, regloc, &reg_lo);
	pci_read_config_dword(pdev, regloc + 4, &reg_hi);

	...
}

> > +		u32 reg_lo, reg_hi;
> > +		u8 reg_type;
> > +
> > +		/* "register low and high" contain other bits */
> > +		pci_read_config_dword(pdev, i, &reg_lo);
> > +		pci_read_config_dword(pdev, i + 4, &reg_hi);
> > +
> > +		reg_type = FIELD_GET(CXL_REGLOC_RBI_MASK, reg_lo);
> > +
> > +		if (reg_type == CXL_REGLOC_RBI_MEMDEV) {
> > +			cxlm = cxl_mem_create(pdev, reg_lo, reg_hi);
> > +			break;
> > +		}
> > +	}
> > +
> > +	if (!cxlm)
> > +		return -ENODEV;
> > +
> > +	rc = cxl_mem_setup_regs(cxlm);
> > +	if (rc)
> > +		return rc;
> > +
> > +	rc = cxl_mem_setup_mailbox(cxlm);
> > +	if (rc)
> > +		return rc;
> > +
> > +	return cxl_mem_identify(cxlm);
> >  }
> >  
> >  static const struct pci_device_id cxl_mem_pci_tbl[] = {
> > diff --git a/drivers/cxl/pci.h b/drivers/cxl/pci.h
> > index e464bea3f4d3..af3ec078cf6c 100644
> > --- a/drivers/cxl/pci.h
> > +++ b/drivers/cxl/pci.h
> > @@ -9,9 +9,23 @@
> >   * See section 8.1 Configuration Space Registers in the CXL 2.0
> >   * Specification
> >   */
> > +#define PCI_DVSEC_HEADER1_LENGTH_MASK	GENMASK(31, 20)
> >  #define PCI_DVSEC_VENDOR_ID_CXL		0x1E98
> >  #define PCI_DVSEC_ID_CXL		0x0
> >  
> >  #define PCI_DVSEC_ID_CXL_REGLOC_OFFSET		0x8
> > +#define PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET	0xC
> > +
> > +/* BAR Indicator Register (BIR) */
> > +#define CXL_REGLOC_BIR_MASK GENMASK(2, 0)
> > +
> > +/* Register Block Identifier (RBI) */
> > +#define CXL_REGLOC_RBI_MASK GENMASK(15, 8)
> > +#define CXL_REGLOC_RBI_EMPTY 0
> > +#define CXL_REGLOC_RBI_COMPONENT 1
> > +#define CXL_REGLOC_RBI_VIRT 2
> > +#define CXL_REGLOC_RBI_MEMDEV 3
> > +
> > +#define CXL_REGLOC_ADDR_MASK GENMASK(31, 16)
> >  
> >  #endif /* __CXL_PCI_H__ */
>
Jonathan Cameron Feb. 16, 2021, 5:20 p.m. UTC | #4
On Tue, 16 Feb 2021 08:43:03 -0800
Ben Widawsky <ben.widawsky@intel.com> wrote:

> On 21-02-16 14:51:48, Jonathan Cameron wrote:
> > On Mon, 15 Feb 2021 17:45:31 -0800
> > Ben Widawsky <ben.widawsky@intel.com> wrote:
> >   
> > > Provide enough functionality to utilize the mailbox of a memory device.
> > > The mailbox is used to interact with the firmware running on the memory
> > > device. The flow is proven with one implemented command, "identify".
> > > Because the class code has already told the driver this is a memory
> > > device and the identify command is mandatory.
> > > 
> > > CXL devices contain an array of capabilities that describe the
> > > interactions software can have with the device or firmware running on
> > > the device. A CXL compliant device must implement the device status and
> > > the mailbox capability. Additionally, a CXL compliant memory device must
> > > implement the memory device capability. Each of the capabilities can
> > > [will] provide an offset within the MMIO region for interacting with the
> > > CXL device.
> > > 
> > > The capabilities tell the driver how to find and map the register space
> > > for CXL Memory Devices. The registers are required to utilize the CXL
> > > spec defined mailbox interface. The spec outlines two mailboxes, primary
> > > and secondary. The secondary mailbox is earmarked for system firmware,
> > > and not handled in this driver.
> > > 
> > > Primary mailboxes are capable of generating an interrupt when submitting
> > > a background command. That implementation is saved for a later time.
> > > 
> > > Link: https://www.computeexpresslink.org/download-the-specification
> > > Signed-off-by: Ben Widawsky <ben.widawsky@intel.com>
> > > Reviewed-by: Dan Williams <dan.j.williams@intel.com> (v2)  
> > 
> > Looks like an off by one error in the register locator iteration.
> > 
> > The potential buffer overrun from memcpy_fromio is still there as well
> > as far as I can see.
> > 
> > If the software provides storage for a payload of size n and the hardware
> > reports a size of n + d, code will happily write beyond the end of the
> > storage provided.
> > 
> > Obviously, this shouldn't happen, but I'm not that trusting of both
> > hardware and software never having bugs.
> > 
> > Jonathan
> >   
> > > ---
> > >  drivers/cxl/cxl.h |  88 ++++++++
> > >  drivers/cxl/mem.c | 543 +++++++++++++++++++++++++++++++++++++++++++++-
> > >  drivers/cxl/pci.h |  14 ++
> > >  3 files changed, 643 insertions(+), 2 deletions(-)
> > >  create mode 100644 drivers/cxl/cxl.h
> > >   
> > ...
> >   
> > > +
> > > +#endif /* __CXL_H__ */
> > > diff --git a/drivers/cxl/mem.c b/drivers/cxl/mem.c
> > > index ce33c5ee77c9..b86cda2d299a 100644
> > > --- a/drivers/cxl/mem.c
> > > +++ b/drivers/cxl/mem.c
> > > @@ -3,7 +3,458 @@
> > >  #include <linux/module.h>
> > >  #include <linux/pci.h>
> > >  #include <linux/io.h>
> > > +#include <linux/io-64-nonatomic-lo-hi.h>
> > >  #include "pci.h"
> > > +#include "cxl.h"
> > > +
> > > +#define cxl_doorbell_busy(cxlm)                                                \
> > > +	(readl((cxlm)->mbox_regs + CXLDEV_MBOX_CTRL_OFFSET) &                  \
> > > +	 CXLDEV_MBOX_CTRL_DOORBELL)
> > > +
> > > +/* CXL 2.0 - 8.2.8.4 */
> > > +#define CXL_MAILBOX_TIMEOUT_MS (2 * HZ)
> > > +
> > > +enum opcode {
> > > +	CXL_MBOX_OP_IDENTIFY		= 0x4000,
> > > +	CXL_MBOX_OP_MAX			= 0x10000
> > > +};
> > > +
> > > +/**
> > > + * struct mbox_cmd - A command to be submitted to hardware.
> > > + * @opcode: (input) The command set and command submitted to hardware.
> > > + * @payload_in: (input) Pointer to the input payload.
> > > + * @payload_out: (output) Pointer to the output payload. Must be allocated by
> > > + *		 the caller.
> > > + * @size_in: (input) Number of bytes to load from @payload.
> > > + * @size_out: (output) Number of bytes loaded into @payload.
> > > + * @return_code: (output) Error code returned from hardware.
> > > + *
> > > + * This is the primary mechanism used to send commands to the hardware.
> > > + * All the fields except @payload_* correspond exactly to the fields described in
> > > + * Command Register section of the CXL 2.0 8.2.8.4.5. @payload_in and
> > > + * @payload_out are written to, and read from the Command Payload Registers
> > > + * defined in CXL 2.0 8.2.8.4.8.
> > > + */
> > > +struct mbox_cmd {
> > > +	u16 opcode;
> > > +	void *payload_in;
> > > +	void *payload_out;
> > > +	size_t size_in;
> > > +	size_t size_out;
> > > +	u16 return_code;
> > > +#define CXL_MBOX_SUCCESS 0
> > > +};  
> > 
> >   
> > > +
> > > +/**
> > > + * __cxl_mem_mbox_send_cmd() - Execute a mailbox command
> > > + * @cxlm: The CXL memory device to communicate with.
> > > + * @mbox_cmd: Command to send to the memory device.
> > > + *
> > > + * Context: Any context. Expects mbox_mutex to be held.
> > > + * Return: -ETIMEDOUT if timeout occurred waiting for completion. 0 on success.
> > > + *         Caller should check the return code in @mbox_cmd to make sure it
> > > + *         succeeded.
> > > + *
> > > + * This is a generic form of the CXL mailbox send command thus only using the
> > > + * registers defined by the mailbox capability ID - CXL 2.0 8.2.8.4. Memory
> > > + * devices, and perhaps other types of CXL devices may have further information
> > > + * available upon error conditions. Driver facilities wishing to send mailbox
> > > + * commands should use the wrapper command.
> > > + *
> > > + * The CXL spec allows for up to two mailboxes. The intention is for the primary
> > > + * mailbox to be OS controlled and the secondary mailbox to be used by system
> > > + * firmware. This allows the OS and firmware to communicate with the device and
> > > + * not need to coordinate with each other. The driver only uses the primary
> > > + * mailbox.
> > > + */
> > > +static int __cxl_mem_mbox_send_cmd(struct cxl_mem *cxlm,
> > > +				   struct mbox_cmd *mbox_cmd)
> > > +{
> > > +	void __iomem *payload = cxlm->mbox_regs + CXLDEV_MBOX_PAYLOAD_OFFSET;
> > > +	u64 cmd_reg, status_reg;
> > > +	size_t out_len;
> > > +	int rc;
> > > +
> > > +	lockdep_assert_held(&cxlm->mbox_mutex);
> > > +
> > > +	/*
> > > +	 * Here are the steps from 8.2.8.4 of the CXL 2.0 spec.
> > > +	 *   1. Caller reads MB Control Register to verify doorbell is clear
> > > +	 *   2. Caller writes Command Register
> > > +	 *   3. Caller writes Command Payload Registers if input payload is non-empty
> > > +	 *   4. Caller writes MB Control Register to set doorbell
> > > +	 *   5. Caller either polls for doorbell to be clear or waits for interrupt if configured
> > > +	 *   6. Caller reads MB Status Register to fetch Return code
> > > +	 *   7. If command successful, Caller reads Command Register to get Payload Length
> > > +	 *   8. If output payload is non-empty, host reads Command Payload Registers
> > > +	 *
> > > +	 * Hardware is free to do whatever it wants before the doorbell is rung,
> > > +	 * and isn't allowed to change anything after it clears the doorbell. As
> > > +	 * such, steps 2 and 3 can happen in any order, and steps 6, 7, 8 can
> > > +	 * also happen in any order (though some orders might not make sense).
> > > +	 */
> > > +
> > > +	/* #1 */
> > > +	if (cxl_doorbell_busy(cxlm)) {
> > > +		dev_err_ratelimited(&cxlm->pdev->dev,
> > > +				    "Mailbox re-busy after acquiring\n");
> > > +		return -EBUSY;
> > > +	}
> > > +
> > > +	cmd_reg = FIELD_PREP(CXLDEV_MBOX_CMD_COMMAND_OPCODE_MASK,
> > > +			     mbox_cmd->opcode);
> > > +	if (mbox_cmd->size_in) {
> > > +		if (WARN_ON(!mbox_cmd->payload_in))
> > > +			return -EINVAL;
> > > +
> > > +		cmd_reg |= FIELD_PREP(CXLDEV_MBOX_CMD_PAYLOAD_LENGTH_MASK,
> > > +				      mbox_cmd->size_in);
> > > +		memcpy_toio(payload, mbox_cmd->payload_in, mbox_cmd->size_in);
> > > +	}
> > > +
> > > +	/* #2, #3 */
> > > +	writeq(cmd_reg, cxlm->mbox_regs + CXLDEV_MBOX_CMD_OFFSET);
> > > +
> > > +	/* #4 */
> > > +	dev_dbg(&cxlm->pdev->dev, "Sending command\n");
> > > +	writel(CXLDEV_MBOX_CTRL_DOORBELL,
> > > +	       cxlm->mbox_regs + CXLDEV_MBOX_CTRL_OFFSET);
> > > +
> > > +	/* #5 */
> > > +	rc = cxl_mem_wait_for_doorbell(cxlm);
> > > +	if (rc == -ETIMEDOUT) {
> > > +		cxl_mem_mbox_timeout(cxlm, mbox_cmd);
> > > +		return rc;
> > > +	}
> > > +
> > > +	/* #6 */
> > > +	status_reg = readq(cxlm->mbox_regs + CXLDEV_MBOX_STATUS_OFFSET);
> > > +	mbox_cmd->return_code =
> > > +		FIELD_GET(CXLDEV_MBOX_STATUS_RET_CODE_MASK, status_reg);
> > > +
> > > +	if (mbox_cmd->return_code != 0) {
> > > +		dev_dbg(&cxlm->pdev->dev, "Mailbox operation had an error\n");
> > > +		return 0;
> > > +	}
> > > +
> > > +	/* #7 */
> > > +	cmd_reg = readq(cxlm->mbox_regs + CXLDEV_MBOX_CMD_OFFSET);
> > > +	out_len = FIELD_GET(CXLDEV_MBOX_CMD_PAYLOAD_LENGTH_MASK, cmd_reg);
> > > +
> > > +	/* #8 */
> > > +	if (out_len && mbox_cmd->payload_out) {
> > > +		size_t n = min_t(size_t, cxlm->payload_size, out_len);  
> > 
> > This doesn't protect us from the case where the hardware
> > returns a larger payload than the caller is expecting.
> > 
> > i.e. payload_out is too small.  We need to pass in the size of that buffer as
> > well.   This currently clamps to the size of the source buffer but does not
> > check if there is enough space at the destination (mbox_cmd->payload_out).
> >   
> 
> Let me articulate the issue a bit. The userspace call chain should be fine:
> cxl_send_cmd() -> ioctl handlers
>   cxl_validate_cmd_from_user -> converts to internal command
>     handle_mailbox_cmd_from_user -> dispatches mbox command.

There is a sanity check in there against info->size_out, that will return
an error if the buffer isn't big enough.   However, that test passes
for a variable length command.  It is then followed by

out_cmd->info.size_out = send_cmd->out.size;
(perhaps that is meant to be = info->size_out so as to pick up the -1?)

handle_mailbox_cmd_from_user() then uses that size in
		mbox_cmd.payload_out = kvzalloc(cmd->info.size_out, GFP_KERNEL);

> 
> cxl_send_cmd():
>   if (c.info.size_out < 0)
>     c.info.size_out = cxlm->payload_size;
> 
(c == out_cmd above)
So this doesn't apply because c.info.size_out is whatever userspace set it to.

> handle_mailbox_cmd_from_user():
>   if (cmd->info.size_out) {
>      mbox_cmd.payload_out = kvzalloc(cmd->info.size_out, GFP_KERNEL);

__cxl_mem_mbox_send_cmd() called with that payload size and blindly
copies whatever size of data the hardware receives into the the buffer we allocated
above.  If it's not big enough you now have a userspace triggered buffer overflow in
the kernel.
All userspace needs to do is issue an ioctl for a raw command with the out.size
set too small but not set to -1.

> 
> 
> The kernel call chain could have issues:
> cxl_mem_identify/*() -> kernel caller allocates just enough space
>   cxl_mem_mbox_send_cmd() -> internal wrapper we created for v3
>     blows up in the spot you mention.
> 
> The driver allocates enough space on the stack for all these calls, but yes, if
> hardware is out of spec it would be problematic. In previous versions of this
> series, there has been a check there. However, the ability to have hardware
> return more data than expected is I believe the correct functionality here.

It's absolutely fine to return more data, but we shouldn't copy it from the mailbox
into memory that isn't big enough.  We should be extremely paranoid about that.



> 
> So my proposal is for now, since no real hardware exists, and the command set
> here is so benign, we leave fixing this as a TODO.
> 
> I can post a patch on top of this series to address this issue in a manner I
> believe warrants discussing (kvzalloc max payload size buffers on open() and for
> each driver instance).

Or just sanity check the size against available buffer size before using it
in mempcy_fromio.

> 
> > > +
> > > +		memcpy_fromio(mbox_cmd->payload_out, payload, n);
> > > +		mbox_cmd->size_out = n;
> > > +	} else {
> > > +		mbox_cmd->size_out = 0;
> > > +	}
> > > +
> > > +	return 0;
> > > +}
> > > +  
> > 
> > ...
> >   
> > > +
> > > +/**
> > > + * cxl_mem_mbox_send_cmd() - Send a mailbox command to a memory device.
> > > + * @cxlm: The CXL memory device to communicate with.
> > > + * @opcode: Opcode for the mailbox command.
> > > + * @in: The input payload for the mailbox command.
> > > + * @in_size: The length of the input payload
> > > + * @out: Caller allocated buffer for the output.
> > > + * @out_min_size: Minimum expected size of output.
> > > + *
> > > + * Context: Any context. Will acquire and release mbox_mutex.
> > > + * Return:
> > > + *  * %>=0	- Number of bytes returned in @out.
> > > + *  * %-E2BIG	- Payload is too large for hardware.
> > > + *  * %-EBUSY	- Couldn't acquire exclusive mailbox access.
> > > + *  * %-EFAULT	- Hardware error occurred.
> > > + *  * %-ENXIO	- Command completed, but device reported an error.
> > > + *  * %-ENODATA	- Not enough payload data returned by hardware.
> > > + *
> > > + * Mailbox commands may execute successfully yet the device itself reported an
> > > + * error. While this distinction can be useful for commands from userspace, the
> > > + * kernel will only be able to use results when both are successful.
> > > + *
> > > + * See __cxl_mem_mbox_send_cmd()
> > > + */
> > > +static int cxl_mem_mbox_send_cmd(struct cxl_mem *cxlm, u16 opcode, void *in,
> > > +				 size_t in_size, void *out, size_t out_min_size)
> > > +{
> > > +	struct mbox_cmd mbox_cmd = {
> > > +		.opcode = opcode,
> > > +		.payload_in = in,
> > > +		.size_in = in_size,
> > > +		.payload_out = out,
> > > +	};
> > > +	int rc;
> > > +
> > > +	if (out_min_size > cxlm->payload_size)
> > > +		return -E2BIG;
> > > +
> > > +	rc = cxl_mem_mbox_get(cxlm);
> > > +	if (rc)
> > > +		return rc;
> > > +
> > > +	rc = __cxl_mem_mbox_send_cmd(cxlm, &mbox_cmd);
> > > +	cxl_mem_mbox_put(cxlm);
> > > +	if (rc)
> > > +		return rc;
> > > +
> > > +	/* TODO: Map return code to proper kernel style errno */
> > > +	if (mbox_cmd.return_code != CXL_MBOX_SUCCESS)
> > > +		return -ENXIO;
> > > +
> > > +	if (mbox_cmd.size_out < out_min_size)
> > > +		return -ENODATA;
> > > +
> > > +	return mbox_cmd.size_out;
> > > +}
> > > +
> > > +/**
> > > + * cxl_mem_setup_regs() - Setup necessary MMIO.
> > > + * @cxlm: The CXL memory device to communicate with.
> > > + *
> > > + * Return: 0 if all necessary registers mapped.
> > > + *
> > > + * A memory device is required by spec to implement a certain set of MMIO
> > > + * regions. The purpose of this function is to enumerate and map those
> > > + * registers.
> > > + */
> > > +static int cxl_mem_setup_regs(struct cxl_mem *cxlm)
> > > +{
> > > +	struct device *dev = &cxlm->pdev->dev;
> > > +	int cap, cap_count;
> > > +	u64 cap_array;
> > > +
> > > +	cap_array = readq(cxlm->regs + CXLDEV_CAP_ARRAY_OFFSET);
> > > +	if (FIELD_GET(CXLDEV_CAP_ARRAY_ID_MASK, cap_array) !=
> > > +	    CXLDEV_CAP_ARRAY_CAP_ID)
> > > +		return -ENODEV;
> > > +
> > > +	cap_count = FIELD_GET(CXLDEV_CAP_ARRAY_COUNT_MASK, cap_array);
> > > +
> > > +	for (cap = 1; cap <= cap_count; cap++) {
> > > +		void __iomem *register_block;
> > > +		u32 offset;
> > > +		u16 cap_id;
> > > +
> > > +		cap_id = readl(cxlm->regs + cap * 0x10) & 0xffff;  
> > 
> > Slight preference for FIELD_GET just for consistency.
> >   
> > > +		offset = readl(cxlm->regs + cap * 0x10 + 0x4);
> > > +		register_block = cxlm->regs + offset;
> > > +
> > > +		switch (cap_id) {
> > > +		case CXLDEV_CAP_CAP_ID_DEVICE_STATUS:
> > > +			dev_dbg(dev, "found Status capability (0x%x)\n", offset);
> > > +			cxlm->status_regs = register_block;
> > > +			break;
> > > +		case CXLDEV_CAP_CAP_ID_PRIMARY_MAILBOX:
> > > +			dev_dbg(dev, "found Mailbox capability (0x%x)\n", offset);
> > > +			cxlm->mbox_regs = register_block;
> > > +			break;
> > > +		case CXLDEV_CAP_CAP_ID_SECONDARY_MAILBOX:
> > > +			dev_dbg(dev, "found Secondary Mailbox capability (0x%x)\n", offset);
> > > +			break;
> > > +		case CXLDEV_CAP_CAP_ID_MEMDEV:
> > > +			dev_dbg(dev, "found Memory Device capability (0x%x)\n", offset);
> > > +			cxlm->memdev_regs = register_block;
> > > +			break;
> > > +		default:
> > > +			dev_dbg(dev, "Unknown cap ID: %d (0x%x)\n", cap_id, offset);
> > > +			break;
> > > +		}
> > > +	}
> > > +
> > > +	if (!cxlm->status_regs || !cxlm->mbox_regs || !cxlm->memdev_regs) {
> > > +		dev_err(dev, "registers not found: %s%s%s\n",
> > > +			!cxlm->status_regs ? "status " : "",
> > > +			!cxlm->mbox_regs ? "mbox " : "",
> > > +			!cxlm->memdev_regs ? "memdev" : "");
> > > +		return -ENXIO;
> > > +	}
> > > +
> > > +	return 0;
> > > +}
> > > +  
> > 
> > ...
> >   
> > > +
> > > +static struct cxl_mem *cxl_mem_create(struct pci_dev *pdev, u32 reg_lo,
> > > +				      u32 reg_hi)  
> > 
> > I'm not really suggesting you change it at this point, but I'd have
> > done the splitting of reg_lo up and the building of the offset at the call site
> > rather than in here.  I think that would have been slightly easier to follow.
> >   
> 
> Noted. In future patches this is going to get reworked somewhat to support more
> flexibility with register blocks.
> 
> > > +{
> > > +	struct device *dev = &pdev->dev;
> > > +	struct cxl_mem *cxlm;
> > > +	void __iomem *regs;
> > > +	u64 offset;
> > > +	u8 bar;
> > > +	int rc;
> > > +
> > > +	cxlm = devm_kzalloc(&pdev->dev, sizeof(*cxlm), GFP_KERNEL);
> > > +	if (!cxlm) {
> > > +		dev_err(dev, "No memory available\n");
> > > +		return NULL;
> > > +	}
> > > +
> > > +	offset = ((u64)reg_hi << 32) | FIELD_GET(CXL_REGLOC_ADDR_MASK, reg_lo);
> > > +	bar = FIELD_GET(CXL_REGLOC_BIR_MASK, reg_lo);
> > > +
> > > +	/* Basic sanity check that BAR is big enough */
> > > +	if (pci_resource_len(pdev, bar) < offset) {
> > > +		dev_err(dev, "BAR%d: %pr: too small (offset: %#llx)\n", bar,
> > > +			&pdev->resource[bar], (unsigned long long)offset);
> > > +		return NULL;
> > > +	}
> > > +
> > > +	rc = pcim_iomap_regions(pdev, BIT(bar), pci_name(pdev));
> > > +	if (rc) {
> > > +		dev_err(dev, "failed to map registers\n");
> > > +		return NULL;
> > > +	}
> > > +	regs = pcim_iomap_table(pdev)[bar];
> > > +
> > > +	mutex_init(&cxlm->mbox_mutex);
> > > +	cxlm->pdev = pdev;
> > > +	cxlm->regs = regs + offset;
> > > +
> > > +	dev_dbg(dev, "Mapped CXL Memory Device resource\n");
> > > +	return cxlm;
> > > +}
> > >  
> > >  static int cxl_mem_dvsec(struct pci_dev *pdev, int dvsec)
> > >  {
> > > @@ -28,10 +479,65 @@ static int cxl_mem_dvsec(struct pci_dev *pdev, int dvsec)
> > >  	return 0;
> > >  }
> > >  
> > > +/**
> > > + * cxl_mem_identify() - Send the IDENTIFY command to the device.
> > > + * @cxlm: The device to identify.
> > > + *
> > > + * Return: 0 if identify was executed successfully.
> > > + *
> > > + * This will dispatch the identify command to the device and on success populate
> > > + * structures to be exported to sysfs.
> > > + */
> > > +static int cxl_mem_identify(struct cxl_mem *cxlm)
> > > +{
> > > +	struct cxl_mbox_identify {
> > > +		char fw_revision[0x10];
> > > +		__le64 total_capacity;
> > > +		__le64 volatile_capacity;
> > > +		__le64 persistent_capacity;
> > > +		__le64 partition_align;
> > > +		__le16 info_event_log_size;
> > > +		__le16 warning_event_log_size;
> > > +		__le16 failure_event_log_size;
> > > +		__le16 fatal_event_log_size;
> > > +		__le32 lsa_size;
> > > +		u8 poison_list_max_mer[3];
> > > +		__le16 inject_poison_limit;
> > > +		u8 poison_caps;
> > > +		u8 qos_telemetry_caps;
> > > +	} __packed id;
> > > +	int rc;
> > > +
> > > +	rc = cxl_mem_mbox_send_cmd(cxlm, CXL_MBOX_OP_IDENTIFY, NULL, 0, &id,
> > > +				   sizeof(id));
> > > +	if (rc < 0)
> > > +		return rc;
> > > +
> > > +	/*
> > > +	 * TODO: enumerate DPA map, as 'ram' and 'pmem' do not alias.
> > > +	 * For now, only the capacity is exported in sysfs
> > > +	 */
> > > +	cxlm->ram_range.start = 0;
> > > +	cxlm->ram_range.end = le64_to_cpu(id.volatile_capacity) - 1;
> > > +
> > > +	cxlm->pmem_range.start = 0;
> > > +	cxlm->pmem_range.end = le64_to_cpu(id.persistent_capacity) - 1;
> > > +
> > > +	memcpy(cxlm->firmware_version, id.fw_revision, sizeof(id.fw_revision));
> > > +
> > > +	return 0;
> > > +}
> > > +
> > >  static int cxl_mem_probe(struct pci_dev *pdev, const struct pci_device_id *id)
> > >  {
> > >  	struct device *dev = &pdev->dev;
> > > -	int regloc;
> > > +	struct cxl_mem *cxlm = NULL;
> > > +	int rc, regloc, i;
> > > +	u32 regloc_size;
> > > +
> > > +	rc = pcim_enable_device(pdev);
> > > +	if (rc)
> > > +		return rc;
> > >  
> > >  	regloc = cxl_mem_dvsec(pdev, PCI_DVSEC_ID_CXL_REGLOC_OFFSET);
> > >  	if (!regloc) {
> > > @@ -39,7 +545,40 @@ static int cxl_mem_probe(struct pci_dev *pdev, const struct pci_device_id *id)
> > >  		return -ENXIO;
> > >  	}
> > >  
> > > -	return 0;
> > > +	/* Get the size of the Register Locator DVSEC */
> > > +	pci_read_config_dword(pdev, regloc + PCI_DVSEC_HEADER1, &regloc_size);
> > > +	regloc_size = FIELD_GET(PCI_DVSEC_HEADER1_LENGTH_MASK, regloc_size);  
> > 
> > The size field here is the dvsec length..  Let's say we only have one register block
> > entry at +0x0c and +0x10
> > From PCI spec :
> > 
> > "DVSEC Length - This field indicates the number of bytes in the entire DVSEC structure, including the PCI
> > Express Extended Capability Header, the DVSEC Header 1, DVSEC Header 2, and DVSEC vendor-specific
> > registers."
> > 
> > So here it would be 0x14
> >   
> > > +
> > > +	regloc += PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET;  
> > 
> > We then shift regloc forward by +0xc
> >   
> > > +
> > > +	for (i = regloc; i < regloc + regloc_size; i += 8) {  
> > 
> > This loop will then index form
> > i= +0xc to i < +0c + 0x14 (0x20)
> > i = 0xc, 0x14 
> > 
> > So that's indexing one more entry than is actually present.
> > Should be something like
> > 
> > 	for (i = regloc;
> > 	     i < regloc + regloc_size - PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET;
> > 	     i++) 
> > 
> > which will mean the only iteration for this example is the one with i == +0xC
> >  
> 
> Good catch. I think this warrants rewriting a bit, let me know what you think?
> 
> regloc += PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET;
> regblocks = (regloc_size - PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET) / 8;
> 
> for (i = 0; i < regblocks; i++, regloc+=8) {
> 	pci_read_config_dword(pdev, regloc, &reg_lo);
> 	pci_read_config_dword(pdev, regloc + 4, &reg_hi);
> 
> 	...
> }

That's fine.
Ben Widawsky Feb. 16, 2021, 5:56 p.m. UTC | #5
On 21-02-16 17:20:01, Jonathan Cameron wrote:
> On Tue, 16 Feb 2021 08:43:03 -0800
> Ben Widawsky <ben.widawsky@intel.com> wrote:
> 
> > On 21-02-16 14:51:48, Jonathan Cameron wrote:
> > > On Mon, 15 Feb 2021 17:45:31 -0800
> > > Ben Widawsky <ben.widawsky@intel.com> wrote:
> > >   
> > > > Provide enough functionality to utilize the mailbox of a memory device.
> > > > The mailbox is used to interact with the firmware running on the memory
> > > > device. The flow is proven with one implemented command, "identify".
> > > > Because the class code has already told the driver this is a memory
> > > > device and the identify command is mandatory.
> > > > 
> > > > CXL devices contain an array of capabilities that describe the
> > > > interactions software can have with the device or firmware running on
> > > > the device. A CXL compliant device must implement the device status and
> > > > the mailbox capability. Additionally, a CXL compliant memory device must
> > > > implement the memory device capability. Each of the capabilities can
> > > > [will] provide an offset within the MMIO region for interacting with the
> > > > CXL device.
> > > > 
> > > > The capabilities tell the driver how to find and map the register space
> > > > for CXL Memory Devices. The registers are required to utilize the CXL
> > > > spec defined mailbox interface. The spec outlines two mailboxes, primary
> > > > and secondary. The secondary mailbox is earmarked for system firmware,
> > > > and not handled in this driver.
> > > > 
> > > > Primary mailboxes are capable of generating an interrupt when submitting
> > > > a background command. That implementation is saved for a later time.
> > > > 
> > > > Link: https://www.computeexpresslink.org/download-the-specification
> > > > Signed-off-by: Ben Widawsky <ben.widawsky@intel.com>
> > > > Reviewed-by: Dan Williams <dan.j.williams@intel.com> (v2)  
> > > 
> > > Looks like an off by one error in the register locator iteration.
> > > 
> > > The potential buffer overrun from memcpy_fromio is still there as well
> > > as far as I can see.
> > > 
> > > If the software provides storage for a payload of size n and the hardware
> > > reports a size of n + d, code will happily write beyond the end of the
> > > storage provided.
> > > 
> > > Obviously, this shouldn't happen, but I'm not that trusting of both
> > > hardware and software never having bugs.
> > > 
> > > Jonathan
> > >   
> > > > ---
> > > >  drivers/cxl/cxl.h |  88 ++++++++
> > > >  drivers/cxl/mem.c | 543 +++++++++++++++++++++++++++++++++++++++++++++-
> > > >  drivers/cxl/pci.h |  14 ++
> > > >  3 files changed, 643 insertions(+), 2 deletions(-)
> > > >  create mode 100644 drivers/cxl/cxl.h
> > > >   
> > > ...
> > >   
> > > > +
> > > > +#endif /* __CXL_H__ */
> > > > diff --git a/drivers/cxl/mem.c b/drivers/cxl/mem.c
> > > > index ce33c5ee77c9..b86cda2d299a 100644
> > > > --- a/drivers/cxl/mem.c
> > > > +++ b/drivers/cxl/mem.c
> > > > @@ -3,7 +3,458 @@
> > > >  #include <linux/module.h>
> > > >  #include <linux/pci.h>
> > > >  #include <linux/io.h>
> > > > +#include <linux/io-64-nonatomic-lo-hi.h>
> > > >  #include "pci.h"
> > > > +#include "cxl.h"
> > > > +
> > > > +#define cxl_doorbell_busy(cxlm)                                                \
> > > > +	(readl((cxlm)->mbox_regs + CXLDEV_MBOX_CTRL_OFFSET) &                  \
> > > > +	 CXLDEV_MBOX_CTRL_DOORBELL)
> > > > +
> > > > +/* CXL 2.0 - 8.2.8.4 */
> > > > +#define CXL_MAILBOX_TIMEOUT_MS (2 * HZ)
> > > > +
> > > > +enum opcode {
> > > > +	CXL_MBOX_OP_IDENTIFY		= 0x4000,
> > > > +	CXL_MBOX_OP_MAX			= 0x10000
> > > > +};
> > > > +
> > > > +/**
> > > > + * struct mbox_cmd - A command to be submitted to hardware.
> > > > + * @opcode: (input) The command set and command submitted to hardware.
> > > > + * @payload_in: (input) Pointer to the input payload.
> > > > + * @payload_out: (output) Pointer to the output payload. Must be allocated by
> > > > + *		 the caller.
> > > > + * @size_in: (input) Number of bytes to load from @payload.
> > > > + * @size_out: (output) Number of bytes loaded into @payload.
> > > > + * @return_code: (output) Error code returned from hardware.
> > > > + *
> > > > + * This is the primary mechanism used to send commands to the hardware.
> > > > + * All the fields except @payload_* correspond exactly to the fields described in
> > > > + * Command Register section of the CXL 2.0 8.2.8.4.5. @payload_in and
> > > > + * @payload_out are written to, and read from the Command Payload Registers
> > > > + * defined in CXL 2.0 8.2.8.4.8.
> > > > + */
> > > > +struct mbox_cmd {
> > > > +	u16 opcode;
> > > > +	void *payload_in;
> > > > +	void *payload_out;
> > > > +	size_t size_in;
> > > > +	size_t size_out;
> > > > +	u16 return_code;
> > > > +#define CXL_MBOX_SUCCESS 0
> > > > +};  
> > > 
> > >   
> > > > +
> > > > +/**
> > > > + * __cxl_mem_mbox_send_cmd() - Execute a mailbox command
> > > > + * @cxlm: The CXL memory device to communicate with.
> > > > + * @mbox_cmd: Command to send to the memory device.
> > > > + *
> > > > + * Context: Any context. Expects mbox_mutex to be held.
> > > > + * Return: -ETIMEDOUT if timeout occurred waiting for completion. 0 on success.
> > > > + *         Caller should check the return code in @mbox_cmd to make sure it
> > > > + *         succeeded.
> > > > + *
> > > > + * This is a generic form of the CXL mailbox send command thus only using the
> > > > + * registers defined by the mailbox capability ID - CXL 2.0 8.2.8.4. Memory
> > > > + * devices, and perhaps other types of CXL devices may have further information
> > > > + * available upon error conditions. Driver facilities wishing to send mailbox
> > > > + * commands should use the wrapper command.
> > > > + *
> > > > + * The CXL spec allows for up to two mailboxes. The intention is for the primary
> > > > + * mailbox to be OS controlled and the secondary mailbox to be used by system
> > > > + * firmware. This allows the OS and firmware to communicate with the device and
> > > > + * not need to coordinate with each other. The driver only uses the primary
> > > > + * mailbox.
> > > > + */
> > > > +static int __cxl_mem_mbox_send_cmd(struct cxl_mem *cxlm,
> > > > +				   struct mbox_cmd *mbox_cmd)
> > > > +{
> > > > +	void __iomem *payload = cxlm->mbox_regs + CXLDEV_MBOX_PAYLOAD_OFFSET;
> > > > +	u64 cmd_reg, status_reg;
> > > > +	size_t out_len;
> > > > +	int rc;
> > > > +
> > > > +	lockdep_assert_held(&cxlm->mbox_mutex);
> > > > +
> > > > +	/*
> > > > +	 * Here are the steps from 8.2.8.4 of the CXL 2.0 spec.
> > > > +	 *   1. Caller reads MB Control Register to verify doorbell is clear
> > > > +	 *   2. Caller writes Command Register
> > > > +	 *   3. Caller writes Command Payload Registers if input payload is non-empty
> > > > +	 *   4. Caller writes MB Control Register to set doorbell
> > > > +	 *   5. Caller either polls for doorbell to be clear or waits for interrupt if configured
> > > > +	 *   6. Caller reads MB Status Register to fetch Return code
> > > > +	 *   7. If command successful, Caller reads Command Register to get Payload Length
> > > > +	 *   8. If output payload is non-empty, host reads Command Payload Registers
> > > > +	 *
> > > > +	 * Hardware is free to do whatever it wants before the doorbell is rung,
> > > > +	 * and isn't allowed to change anything after it clears the doorbell. As
> > > > +	 * such, steps 2 and 3 can happen in any order, and steps 6, 7, 8 can
> > > > +	 * also happen in any order (though some orders might not make sense).
> > > > +	 */
> > > > +
> > > > +	/* #1 */
> > > > +	if (cxl_doorbell_busy(cxlm)) {
> > > > +		dev_err_ratelimited(&cxlm->pdev->dev,
> > > > +				    "Mailbox re-busy after acquiring\n");
> > > > +		return -EBUSY;
> > > > +	}
> > > > +
> > > > +	cmd_reg = FIELD_PREP(CXLDEV_MBOX_CMD_COMMAND_OPCODE_MASK,
> > > > +			     mbox_cmd->opcode);
> > > > +	if (mbox_cmd->size_in) {
> > > > +		if (WARN_ON(!mbox_cmd->payload_in))
> > > > +			return -EINVAL;
> > > > +
> > > > +		cmd_reg |= FIELD_PREP(CXLDEV_MBOX_CMD_PAYLOAD_LENGTH_MASK,
> > > > +				      mbox_cmd->size_in);
> > > > +		memcpy_toio(payload, mbox_cmd->payload_in, mbox_cmd->size_in);
> > > > +	}
> > > > +
> > > > +	/* #2, #3 */
> > > > +	writeq(cmd_reg, cxlm->mbox_regs + CXLDEV_MBOX_CMD_OFFSET);
> > > > +
> > > > +	/* #4 */
> > > > +	dev_dbg(&cxlm->pdev->dev, "Sending command\n");
> > > > +	writel(CXLDEV_MBOX_CTRL_DOORBELL,
> > > > +	       cxlm->mbox_regs + CXLDEV_MBOX_CTRL_OFFSET);
> > > > +
> > > > +	/* #5 */
> > > > +	rc = cxl_mem_wait_for_doorbell(cxlm);
> > > > +	if (rc == -ETIMEDOUT) {
> > > > +		cxl_mem_mbox_timeout(cxlm, mbox_cmd);
> > > > +		return rc;
> > > > +	}
> > > > +
> > > > +	/* #6 */
> > > > +	status_reg = readq(cxlm->mbox_regs + CXLDEV_MBOX_STATUS_OFFSET);
> > > > +	mbox_cmd->return_code =
> > > > +		FIELD_GET(CXLDEV_MBOX_STATUS_RET_CODE_MASK, status_reg);
> > > > +
> > > > +	if (mbox_cmd->return_code != 0) {
> > > > +		dev_dbg(&cxlm->pdev->dev, "Mailbox operation had an error\n");
> > > > +		return 0;
> > > > +	}
> > > > +
> > > > +	/* #7 */
> > > > +	cmd_reg = readq(cxlm->mbox_regs + CXLDEV_MBOX_CMD_OFFSET);
> > > > +	out_len = FIELD_GET(CXLDEV_MBOX_CMD_PAYLOAD_LENGTH_MASK, cmd_reg);
> > > > +
> > > > +	/* #8 */
> > > > +	if (out_len && mbox_cmd->payload_out) {
> > > > +		size_t n = min_t(size_t, cxlm->payload_size, out_len);  
> > > 
> > > This doesn't protect us from the case where the hardware
> > > returns a larger payload than the caller is expecting.
> > > 
> > > i.e. payload_out is too small.  We need to pass in the size of that buffer as
> > > well.   This currently clamps to the size of the source buffer but does not
> > > check if there is enough space at the destination (mbox_cmd->payload_out).
> > >   
> > 
> > Let me articulate the issue a bit. The userspace call chain should be fine:
> > cxl_send_cmd() -> ioctl handlers
> >   cxl_validate_cmd_from_user -> converts to internal command
> >     handle_mailbox_cmd_from_user -> dispatches mbox command.
> 
> There is a sanity check in there against info->size_out, that will return
> an error if the buffer isn't big enough.   However, that test passes
> for a variable length command.  It is then followed by
> 
> out_cmd->info.size_out = send_cmd->out.size;
> (perhaps that is meant to be = info->size_out so as to pick up the -1?)
> 
> handle_mailbox_cmd_from_user() then uses that size in
> 		mbox_cmd.payload_out = kvzalloc(cmd->info.size_out, GFP_KERNEL);
> 
> > 
> > cxl_send_cmd():
> >   if (c.info.size_out < 0)
> >     c.info.size_out = cxlm->payload_size;
> > 
> (c == out_cmd above)
> So this doesn't apply because c.info.size_out is whatever userspace set it to.
> 
> > handle_mailbox_cmd_from_user():
> >   if (cmd->info.size_out) {
> >      mbox_cmd.payload_out = kvzalloc(cmd->info.size_out, GFP_KERNEL);
> 
> __cxl_mem_mbox_send_cmd() called with that payload size and blindly
> copies whatever size of data the hardware receives into the the buffer we allocated
> above.  If it's not big enough you now have a userspace triggered buffer overflow in
> the kernel.
> All userspace needs to do is issue an ioctl for a raw command with the out.size
> set too small but not set to -1.

You're right.. See my email just now in 4/9. I didn't understand when I read
this earlier, and I shouldn't have brought up the userspace side in this patch
review anyway.

> 
> > 
> > 
> > The kernel call chain could have issues:
> > cxl_mem_identify/*() -> kernel caller allocates just enough space
> >   cxl_mem_mbox_send_cmd() -> internal wrapper we created for v3
> >     blows up in the spot you mention.
> > 
> > The driver allocates enough space on the stack for all these calls, but yes, if
> > hardware is out of spec it would be problematic. In previous versions of this
> > series, there has been a check there. However, the ability to have hardware
> > return more data than expected is I believe the correct functionality here.
> 
> It's absolutely fine to return more data, but we shouldn't copy it from the mailbox
> into memory that isn't big enough.  We should be extremely paranoid about that.
> 
> 
> 
> > 
> > So my proposal is for now, since no real hardware exists, and the command set
> > here is so benign, we leave fixing this as a TODO.
> > 
> > I can post a patch on top of this series to address this issue in a manner I
> > believe warrants discussing (kvzalloc max payload size buffers on open() and for
> > each driver instance).
> 
> Or just sanity check the size against available buffer size before using it
> in mempcy_fromio.

I'll rework this...

> 
> > 
> > > > +
> > > > +		memcpy_fromio(mbox_cmd->payload_out, payload, n);
> > > > +		mbox_cmd->size_out = n;
> > > > +	} else {
> > > > +		mbox_cmd->size_out = 0;
> > > > +	}
> > > > +
> > > > +	return 0;
> > > > +}
> > > > +  
> > > 
> > > ...
> > >   
> > > > +
> > > > +/**
> > > > + * cxl_mem_mbox_send_cmd() - Send a mailbox command to a memory device.
> > > > + * @cxlm: The CXL memory device to communicate with.
> > > > + * @opcode: Opcode for the mailbox command.
> > > > + * @in: The input payload for the mailbox command.
> > > > + * @in_size: The length of the input payload
> > > > + * @out: Caller allocated buffer for the output.
> > > > + * @out_min_size: Minimum expected size of output.
> > > > + *
> > > > + * Context: Any context. Will acquire and release mbox_mutex.
> > > > + * Return:
> > > > + *  * %>=0	- Number of bytes returned in @out.
> > > > + *  * %-E2BIG	- Payload is too large for hardware.
> > > > + *  * %-EBUSY	- Couldn't acquire exclusive mailbox access.
> > > > + *  * %-EFAULT	- Hardware error occurred.
> > > > + *  * %-ENXIO	- Command completed, but device reported an error.
> > > > + *  * %-ENODATA	- Not enough payload data returned by hardware.
> > > > + *
> > > > + * Mailbox commands may execute successfully yet the device itself reported an
> > > > + * error. While this distinction can be useful for commands from userspace, the
> > > > + * kernel will only be able to use results when both are successful.
> > > > + *
> > > > + * See __cxl_mem_mbox_send_cmd()
> > > > + */
> > > > +static int cxl_mem_mbox_send_cmd(struct cxl_mem *cxlm, u16 opcode, void *in,
> > > > +				 size_t in_size, void *out, size_t out_min_size)
> > > > +{
> > > > +	struct mbox_cmd mbox_cmd = {
> > > > +		.opcode = opcode,
> > > > +		.payload_in = in,
> > > > +		.size_in = in_size,
> > > > +		.payload_out = out,
> > > > +	};
> > > > +	int rc;
> > > > +
> > > > +	if (out_min_size > cxlm->payload_size)
> > > > +		return -E2BIG;
> > > > +
> > > > +	rc = cxl_mem_mbox_get(cxlm);
> > > > +	if (rc)
> > > > +		return rc;
> > > > +
> > > > +	rc = __cxl_mem_mbox_send_cmd(cxlm, &mbox_cmd);
> > > > +	cxl_mem_mbox_put(cxlm);
> > > > +	if (rc)
> > > > +		return rc;
> > > > +
> > > > +	/* TODO: Map return code to proper kernel style errno */
> > > > +	if (mbox_cmd.return_code != CXL_MBOX_SUCCESS)
> > > > +		return -ENXIO;
> > > > +
> > > > +	if (mbox_cmd.size_out < out_min_size)
> > > > +		return -ENODATA;
> > > > +
> > > > +	return mbox_cmd.size_out;
> > > > +}
> > > > +
> > > > +/**
> > > > + * cxl_mem_setup_regs() - Setup necessary MMIO.
> > > > + * @cxlm: The CXL memory device to communicate with.
> > > > + *
> > > > + * Return: 0 if all necessary registers mapped.
> > > > + *
> > > > + * A memory device is required by spec to implement a certain set of MMIO
> > > > + * regions. The purpose of this function is to enumerate and map those
> > > > + * registers.
> > > > + */
> > > > +static int cxl_mem_setup_regs(struct cxl_mem *cxlm)
> > > > +{
> > > > +	struct device *dev = &cxlm->pdev->dev;
> > > > +	int cap, cap_count;
> > > > +	u64 cap_array;
> > > > +
> > > > +	cap_array = readq(cxlm->regs + CXLDEV_CAP_ARRAY_OFFSET);
> > > > +	if (FIELD_GET(CXLDEV_CAP_ARRAY_ID_MASK, cap_array) !=
> > > > +	    CXLDEV_CAP_ARRAY_CAP_ID)
> > > > +		return -ENODEV;
> > > > +
> > > > +	cap_count = FIELD_GET(CXLDEV_CAP_ARRAY_COUNT_MASK, cap_array);
> > > > +
> > > > +	for (cap = 1; cap <= cap_count; cap++) {
> > > > +		void __iomem *register_block;
> > > > +		u32 offset;
> > > > +		u16 cap_id;
> > > > +
> > > > +		cap_id = readl(cxlm->regs + cap * 0x10) & 0xffff;  
> > > 
> > > Slight preference for FIELD_GET just for consistency.
> > >   
> > > > +		offset = readl(cxlm->regs + cap * 0x10 + 0x4);
> > > > +		register_block = cxlm->regs + offset;
> > > > +
> > > > +		switch (cap_id) {
> > > > +		case CXLDEV_CAP_CAP_ID_DEVICE_STATUS:
> > > > +			dev_dbg(dev, "found Status capability (0x%x)\n", offset);
> > > > +			cxlm->status_regs = register_block;
> > > > +			break;
> > > > +		case CXLDEV_CAP_CAP_ID_PRIMARY_MAILBOX:
> > > > +			dev_dbg(dev, "found Mailbox capability (0x%x)\n", offset);
> > > > +			cxlm->mbox_regs = register_block;
> > > > +			break;
> > > > +		case CXLDEV_CAP_CAP_ID_SECONDARY_MAILBOX:
> > > > +			dev_dbg(dev, "found Secondary Mailbox capability (0x%x)\n", offset);
> > > > +			break;
> > > > +		case CXLDEV_CAP_CAP_ID_MEMDEV:
> > > > +			dev_dbg(dev, "found Memory Device capability (0x%x)\n", offset);
> > > > +			cxlm->memdev_regs = register_block;
> > > > +			break;
> > > > +		default:
> > > > +			dev_dbg(dev, "Unknown cap ID: %d (0x%x)\n", cap_id, offset);
> > > > +			break;
> > > > +		}
> > > > +	}
> > > > +
> > > > +	if (!cxlm->status_regs || !cxlm->mbox_regs || !cxlm->memdev_regs) {
> > > > +		dev_err(dev, "registers not found: %s%s%s\n",
> > > > +			!cxlm->status_regs ? "status " : "",
> > > > +			!cxlm->mbox_regs ? "mbox " : "",
> > > > +			!cxlm->memdev_regs ? "memdev" : "");
> > > > +		return -ENXIO;
> > > > +	}
> > > > +
> > > > +	return 0;
> > > > +}
> > > > +  
> > > 
> > > ...
> > >   
> > > > +
> > > > +static struct cxl_mem *cxl_mem_create(struct pci_dev *pdev, u32 reg_lo,
> > > > +				      u32 reg_hi)  
> > > 
> > > I'm not really suggesting you change it at this point, but I'd have
> > > done the splitting of reg_lo up and the building of the offset at the call site
> > > rather than in here.  I think that would have been slightly easier to follow.
> > >   
> > 
> > Noted. In future patches this is going to get reworked somewhat to support more
> > flexibility with register blocks.
> > 
> > > > +{
> > > > +	struct device *dev = &pdev->dev;
> > > > +	struct cxl_mem *cxlm;
> > > > +	void __iomem *regs;
> > > > +	u64 offset;
> > > > +	u8 bar;
> > > > +	int rc;
> > > > +
> > > > +	cxlm = devm_kzalloc(&pdev->dev, sizeof(*cxlm), GFP_KERNEL);
> > > > +	if (!cxlm) {
> > > > +		dev_err(dev, "No memory available\n");
> > > > +		return NULL;
> > > > +	}
> > > > +
> > > > +	offset = ((u64)reg_hi << 32) | FIELD_GET(CXL_REGLOC_ADDR_MASK, reg_lo);
> > > > +	bar = FIELD_GET(CXL_REGLOC_BIR_MASK, reg_lo);
> > > > +
> > > > +	/* Basic sanity check that BAR is big enough */
> > > > +	if (pci_resource_len(pdev, bar) < offset) {
> > > > +		dev_err(dev, "BAR%d: %pr: too small (offset: %#llx)\n", bar,
> > > > +			&pdev->resource[bar], (unsigned long long)offset);
> > > > +		return NULL;
> > > > +	}
> > > > +
> > > > +	rc = pcim_iomap_regions(pdev, BIT(bar), pci_name(pdev));
> > > > +	if (rc) {
> > > > +		dev_err(dev, "failed to map registers\n");
> > > > +		return NULL;
> > > > +	}
> > > > +	regs = pcim_iomap_table(pdev)[bar];
> > > > +
> > > > +	mutex_init(&cxlm->mbox_mutex);
> > > > +	cxlm->pdev = pdev;
> > > > +	cxlm->regs = regs + offset;
> > > > +
> > > > +	dev_dbg(dev, "Mapped CXL Memory Device resource\n");
> > > > +	return cxlm;
> > > > +}
> > > >  
> > > >  static int cxl_mem_dvsec(struct pci_dev *pdev, int dvsec)
> > > >  {
> > > > @@ -28,10 +479,65 @@ static int cxl_mem_dvsec(struct pci_dev *pdev, int dvsec)
> > > >  	return 0;
> > > >  }
> > > >  
> > > > +/**
> > > > + * cxl_mem_identify() - Send the IDENTIFY command to the device.
> > > > + * @cxlm: The device to identify.
> > > > + *
> > > > + * Return: 0 if identify was executed successfully.
> > > > + *
> > > > + * This will dispatch the identify command to the device and on success populate
> > > > + * structures to be exported to sysfs.
> > > > + */
> > > > +static int cxl_mem_identify(struct cxl_mem *cxlm)
> > > > +{
> > > > +	struct cxl_mbox_identify {
> > > > +		char fw_revision[0x10];
> > > > +		__le64 total_capacity;
> > > > +		__le64 volatile_capacity;
> > > > +		__le64 persistent_capacity;
> > > > +		__le64 partition_align;
> > > > +		__le16 info_event_log_size;
> > > > +		__le16 warning_event_log_size;
> > > > +		__le16 failure_event_log_size;
> > > > +		__le16 fatal_event_log_size;
> > > > +		__le32 lsa_size;
> > > > +		u8 poison_list_max_mer[3];
> > > > +		__le16 inject_poison_limit;
> > > > +		u8 poison_caps;
> > > > +		u8 qos_telemetry_caps;
> > > > +	} __packed id;
> > > > +	int rc;
> > > > +
> > > > +	rc = cxl_mem_mbox_send_cmd(cxlm, CXL_MBOX_OP_IDENTIFY, NULL, 0, &id,
> > > > +				   sizeof(id));
> > > > +	if (rc < 0)
> > > > +		return rc;
> > > > +
> > > > +	/*
> > > > +	 * TODO: enumerate DPA map, as 'ram' and 'pmem' do not alias.
> > > > +	 * For now, only the capacity is exported in sysfs
> > > > +	 */
> > > > +	cxlm->ram_range.start = 0;
> > > > +	cxlm->ram_range.end = le64_to_cpu(id.volatile_capacity) - 1;
> > > > +
> > > > +	cxlm->pmem_range.start = 0;
> > > > +	cxlm->pmem_range.end = le64_to_cpu(id.persistent_capacity) - 1;
> > > > +
> > > > +	memcpy(cxlm->firmware_version, id.fw_revision, sizeof(id.fw_revision));
> > > > +
> > > > +	return 0;
> > > > +}
> > > > +
> > > >  static int cxl_mem_probe(struct pci_dev *pdev, const struct pci_device_id *id)
> > > >  {
> > > >  	struct device *dev = &pdev->dev;
> > > > -	int regloc;
> > > > +	struct cxl_mem *cxlm = NULL;
> > > > +	int rc, regloc, i;
> > > > +	u32 regloc_size;
> > > > +
> > > > +	rc = pcim_enable_device(pdev);
> > > > +	if (rc)
> > > > +		return rc;
> > > >  
> > > >  	regloc = cxl_mem_dvsec(pdev, PCI_DVSEC_ID_CXL_REGLOC_OFFSET);
> > > >  	if (!regloc) {
> > > > @@ -39,7 +545,40 @@ static int cxl_mem_probe(struct pci_dev *pdev, const struct pci_device_id *id)
> > > >  		return -ENXIO;
> > > >  	}
> > > >  
> > > > -	return 0;
> > > > +	/* Get the size of the Register Locator DVSEC */
> > > > +	pci_read_config_dword(pdev, regloc + PCI_DVSEC_HEADER1, &regloc_size);
> > > > +	regloc_size = FIELD_GET(PCI_DVSEC_HEADER1_LENGTH_MASK, regloc_size);  
> > > 
> > > The size field here is the dvsec length..  Let's say we only have one register block
> > > entry at +0x0c and +0x10
> > > From PCI spec :
> > > 
> > > "DVSEC Length - This field indicates the number of bytes in the entire DVSEC structure, including the PCI
> > > Express Extended Capability Header, the DVSEC Header 1, DVSEC Header 2, and DVSEC vendor-specific
> > > registers."
> > > 
> > > So here it would be 0x14
> > >   
> > > > +
> > > > +	regloc += PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET;  
> > > 
> > > We then shift regloc forward by +0xc
> > >   
> > > > +
> > > > +	for (i = regloc; i < regloc + regloc_size; i += 8) {  
> > > 
> > > This loop will then index form
> > > i= +0xc to i < +0c + 0x14 (0x20)
> > > i = 0xc, 0x14 
> > > 
> > > So that's indexing one more entry than is actually present.
> > > Should be something like
> > > 
> > > 	for (i = regloc;
> > > 	     i < regloc + regloc_size - PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET;
> > > 	     i++) 
> > > 
> > > which will mean the only iteration for this example is the one with i == +0xC
> > >  
> > 
> > Good catch. I think this warrants rewriting a bit, let me know what you think?
> > 
> > regloc += PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET;
> > regblocks = (regloc_size - PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET) / 8;
> > 
> > for (i = 0; i < regblocks; i++, regloc+=8) {
> > 	pci_read_config_dword(pdev, regloc, &reg_lo);
> > 	pci_read_config_dword(pdev, regloc + 4, &reg_hi);
> > 
> > 	...
> > }
> 
> That's fine.
> 
>
Al Viro Feb. 16, 2021, 6:12 p.m. UTC | #6
On Mon, Feb 15, 2021 at 05:45:33PM -0800, Ben Widawsky wrote:
> +	if (cmd->info.size_in) {
> +		mbox_cmd.payload_in = kvzalloc(cmd->info.size_in, GFP_KERNEL);
> +		if (!mbox_cmd.payload_in) {
> +			rc = -ENOMEM;
> +			goto out;
> +		}
> +
> +		if (copy_from_user(mbox_cmd.payload_in,
> +				   u64_to_user_ptr(in_payload),
> +				   cmd->info.size_in)) {
> +			rc = -EFAULT;
> +			goto out;
> +		}

Umm...  Do you need to open-code vmemdup_user()?  The only difference is
GFP_KERNEL allocation instead of GFP_USER one, and the latter is arguably
saner here...  Zeroing is definitely pointless - you either overwrite
the entire buffer with copy_from_user(), or you fail and free the damn
thing.
Ben Widawsky Feb. 16, 2021, 6:22 p.m. UTC | #7
On 21-02-16 18:12:05, Al Viro wrote:
> On Mon, Feb 15, 2021 at 05:45:33PM -0800, Ben Widawsky wrote:
> > +	if (cmd->info.size_in) {
> > +		mbox_cmd.payload_in = kvzalloc(cmd->info.size_in, GFP_KERNEL);
> > +		if (!mbox_cmd.payload_in) {
> > +			rc = -ENOMEM;
> > +			goto out;
> > +		}
> > +
> > +		if (copy_from_user(mbox_cmd.payload_in,
> > +				   u64_to_user_ptr(in_payload),
> > +				   cmd->info.size_in)) {
> > +			rc = -EFAULT;
> > +			goto out;
> > +		}
> 
> Umm...  Do you need to open-code vmemdup_user()?  The only difference is
> GFP_KERNEL allocation instead of GFP_USER one, and the latter is arguably
> saner here...  Zeroing is definitely pointless - you either overwrite
> the entire buffer with copy_from_user(), or you fail and free the damn
> thing.

mea culpa. In fact it was previously memdup_user and Dan suggested I switch to
vmemdup_user.
https://lore.kernel.org/linux-cxl/CAPcyv4j+ixVgEo5q2OhV4kdkBZbnohZj3KDovReQJjPBsREugw@mail.gmail.com/


Will fix for the next version.

Thanks.
Jonathan Cameron Feb. 16, 2021, 6:28 p.m. UTC | #8
On Tue, 16 Feb 2021 09:53:14 -0800
Ben Widawsky <ben.widawsky@intel.com> wrote:

> On 21-02-16 15:22:23, Jonathan Cameron wrote:
> > On Mon, 15 Feb 2021 17:45:33 -0800
> > Ben Widawsky <ben.widawsky@intel.com> wrote:
> >   
> > > Add a straightforward IOCTL that provides a mechanism for userspace to
> > > query the supported memory device commands. CXL commands as they appear
> > > to userspace are described as part of the UAPI kerneldoc. The command
> > > list returned via this IOCTL will contain the full set of commands that
> > > the driver supports, however, some of those commands may not be
> > > available for use by userspace.
> > > 
> > > Memory device commands first appear in the CXL 2.0 specification. They
> > > are submitted through a mailbox mechanism specified in the CXL 2.0
> > > specification.
> > > 
> > > The send command allows userspace to issue mailbox commands directly to
> > > the hardware. The list of available commands to send are the output of
> > > the query command. The driver verifies basic properties of the command
> > > and possibly inspect the input (or output) payload to determine whether
> > > or not the command is allowed (or might taint the kernel).
> > > 
> > > Reported-by: kernel test robot <lkp@intel.com> # bug in earlier revision
> > > Signed-off-by: Ben Widawsky <ben.widawsky@intel.com>
> > > Reviewed-by: Dan Williams <dan.j.williams@intel.com> (v2)  
> > 
> > I may be missreading this but I think the logic to ensure commands
> > using a variable sized buffer have enough space is broken.
> > 
> > Jonathan
> >   
> > > ---
> > >  .clang-format                                 |   1 +
> > >  .../userspace-api/ioctl/ioctl-number.rst      |   1 +
> > >  drivers/cxl/mem.c                             | 288 +++++++++++++++++-
> > >  include/uapi/linux/cxl_mem.h                  | 154 ++++++++++
> > >  4 files changed, 443 insertions(+), 1 deletion(-)
> > >  create mode 100644 include/uapi/linux/cxl_mem.h
> > > 
> > > diff --git a/.clang-format b/.clang-format
> > > index 10dc5a9a61b3..3f11c8901b43 100644
> > > --- a/.clang-format
> > > +++ b/.clang-format
> > > @@ -109,6 +109,7 @@ ForEachMacros:
> > >    - 'css_for_each_child'
> > >    - 'css_for_each_descendant_post'
> > >    - 'css_for_each_descendant_pre'
> > > +  - 'cxl_for_each_cmd'
> > >    - 'device_for_each_child_node'
> > >    - 'dma_fence_chain_for_each'
> > >    - 'do_for_each_ftrace_op'
> > > diff --git a/Documentation/userspace-api/ioctl/ioctl-number.rst b/Documentation/userspace-api/ioctl/ioctl-number.rst
> > > index a4c75a28c839..6eb8e634664d 100644
> > > --- a/Documentation/userspace-api/ioctl/ioctl-number.rst
> > > +++ b/Documentation/userspace-api/ioctl/ioctl-number.rst
> > > @@ -352,6 +352,7 @@ Code  Seq#    Include File                                           Comments
> > >                                                                       <mailto:michael.klein@puffin.lb.shuttle.de>
> > >  0xCC  00-0F  drivers/misc/ibmvmc.h                                   pseries VMC driver
> > >  0xCD  01     linux/reiserfs_fs.h
> > > +0xCE  01-02  uapi/linux/cxl_mem.h                                    Compute Express Link Memory Devices
> > >  0xCF  02     fs/cifs/ioctl.c
> > >  0xDB  00-0F  drivers/char/mwave/mwavepub.h
> > >  0xDD  00-3F                                                          ZFCP device driver see drivers/s390/scsi/
> > > diff --git a/drivers/cxl/mem.c b/drivers/cxl/mem.c
> > > index 410adb1bdffc..a4298cb1182d 100644
> > > --- a/drivers/cxl/mem.c
> > > +++ b/drivers/cxl/mem.c
> > > @@ -1,5 +1,6 @@
> > >  // SPDX-License-Identifier: GPL-2.0-only
> > >  /* Copyright(c) 2020 Intel Corporation. All rights reserved. */
> > > +#include <uapi/linux/cxl_mem.h>
> > >  #include <linux/module.h>
> > >  #include <linux/mutex.h>
> > >  #include <linux/cdev.h>
> > > @@ -40,6 +41,7 @@
> > >  #define CXL_MAILBOX_TIMEOUT_MS (2 * HZ)
> > >  
> > >  enum opcode {
> > > +	CXL_MBOX_OP_INVALID		= 0x0000,
> > >  	CXL_MBOX_OP_IDENTIFY		= 0x4000,
> > >  	CXL_MBOX_OP_MAX			= 0x10000
> > >  };
> > > @@ -91,6 +93,49 @@ struct cxl_memdev {
> > >  static int cxl_mem_major;
> > >  static DEFINE_IDA(cxl_memdev_ida);
> > >  
> > > +/**
> > > + * struct cxl_mem_command - Driver representation of a memory device command
> > > + * @info: Command information as it exists for the UAPI
> > > + * @opcode: The actual bits used for the mailbox protocol
> > > + *
> > > + * The cxl_mem_command is the driver's internal representation of commands that
> > > + * are supported by the driver. Some of these commands may not be supported by
> > > + * the hardware. The driver will use @info to validate the fields passed in by
> > > + * the user then submit the @opcode to the hardware.
> > > + *
> > > + * See struct cxl_command_info.
> > > + */
> > > +struct cxl_mem_command {
> > > +	struct cxl_command_info info;
> > > +	enum opcode opcode;
> > > +};
> > > +
> > > +#define CXL_CMD(_id, sin, sout)                                                \
> > > +	[CXL_MEM_COMMAND_ID_##_id] = {                                         \
> > > +	.info =	{                                                              \
> > > +			.id = CXL_MEM_COMMAND_ID_##_id,                        \
> > > +			.size_in = sin,                                        \
> > > +			.size_out = sout,                                      \
> > > +		},                                                             \
> > > +	.opcode = CXL_MBOX_OP_##_id,                                           \
> > > +	}
> > > +
> > > +/*
> > > + * This table defines the supported mailbox commands for the driver. This table
> > > + * is made up of a UAPI structure. Non-negative values as parameters in the
> > > + * table will be validated against the user's input. For example, if size_in is
> > > + * 0, and the user passed in 1, it is an error.
> > > + */
> > > +static struct cxl_mem_command mem_commands[] = {
> > > +	CXL_CMD(IDENTIFY, 0, 0x43),
> > > +};
> > > +
> > > +#define cxl_for_each_cmd(cmd)                                                  \
> > > +	for ((cmd) = &mem_commands[0];                                         \
> > > +	     ((cmd) - mem_commands) < ARRAY_SIZE(mem_commands); (cmd)++)
> > > +
> > > +#define cxl_cmd_count ARRAY_SIZE(mem_commands)
> > > +
> > >  static int cxl_mem_wait_for_doorbell(struct cxl_mem *cxlm)
> > >  {
> > >  	const unsigned long start = jiffies;
> > > @@ -312,6 +357,247 @@ static void cxl_mem_mbox_put(struct cxl_mem *cxlm)
> > >  	mutex_unlock(&cxlm->mbox_mutex);
> > >  }
> > >  
> > > +/**
> > > + * handle_mailbox_cmd_from_user() - Dispatch a mailbox command for userspace.
> > > + * @cxlm: The CXL memory device to communicate with.
> > > + * @cmd: The validated command.
> > > + * @in_payload: Pointer to userspace's input payload.
> > > + * @out_payload: Pointer to userspace's output payload.
> > > + * @size_out: (Input) Max payload size to copy out.
> > > + *            (Output) Payload size hardware generated.
> > > + * @retval: Hardware generated return code from the operation.
> > > + *
> > > + * Return:
> > > + *  * %0	- Mailbox transaction succeeded. This implies the mailbox
> > > + *  		  protocol completed successfully not that the operation itself
> > > + *  		  was successful.
> > > + *  * %-ENOMEM  - Couldn't allocate a bounce buffer.
> > > + *  * %-EFAULT	- Something happened with copy_to/from_user.
> > > + *  * %-EINTR	- Mailbox acquisition interrupted.
> > > + *  * %-*	- Transaction level failures.
> > > + *
> > > + * Creates the appropriate mailbox command and dispatches it on behalf of a
> > > + * userspace request. The input and output payloads are copied between
> > > + * userspace.
> > > + *
> > > + * See cxl_send_cmd().
> > > + */
> > > +static int handle_mailbox_cmd_from_user(struct cxl_mem *cxlm,
> > > +					const struct cxl_mem_command *cmd,
> > > +					u64 in_payload, u64 out_payload,
> > > +					s32 *size_out, u32 *retval)
> > > +{
> > > +	struct device *dev = &cxlm->pdev->dev;
> > > +	struct mbox_cmd mbox_cmd = {
> > > +		.opcode = cmd->opcode,
> > > +		.size_in = cmd->info.size_in,
> > > +	};
> > > +	int rc;
> > > +
> > > +	if (cmd->info.size_out) {
> > > +		mbox_cmd.payload_out = kvzalloc(cmd->info.size_out, GFP_KERNEL);
> > > +		if (!mbox_cmd.payload_out)
> > > +			return -ENOMEM;
> > > +	}
> > > +
> > > +	if (cmd->info.size_in) {
> > > +		mbox_cmd.payload_in = kvzalloc(cmd->info.size_in, GFP_KERNEL);
> > > +		if (!mbox_cmd.payload_in) {
> > > +			rc = -ENOMEM;
> > > +			goto out;
> > > +		}
> > > +
> > > +		if (copy_from_user(mbox_cmd.payload_in,
> > > +				   u64_to_user_ptr(in_payload),
> > > +				   cmd->info.size_in)) {
> > > +			rc = -EFAULT;
> > > +			goto out;
> > > +		}
> > > +	}
> > > +
> > > +	rc = cxl_mem_mbox_get(cxlm);
> > > +	if (rc)
> > > +		goto out;
> > > +
> > > +	dev_dbg(dev,
> > > +		"Submitting %s command for user\n"
> > > +		"\topcode: %x\n"
> > > +		"\tsize: %ub\n",
> > > +		cxl_command_names[cmd->info.id].name, mbox_cmd.opcode,
> > > +		cmd->info.size_in);
> > > +
> > > +	rc = __cxl_mem_mbox_send_cmd(cxlm, &mbox_cmd);
> > > +	cxl_mem_mbox_put(cxlm);
> > > +	if (rc)
> > > +		goto out;
> > > +
> > > +	/*
> > > +	 * @size_out contains the max size that's allowed to be written back out
> > > +	 * to userspace. While the payload may have written more output than
> > > +	 * this it will have to be ignored.
> > > +	 */  
> > 
> > See below for why I don't think this works. The size of mbox_cmd.payload_out
> > seems to always be the size userspace specified, never the 1MB this code
> > is assuming.  So if the hardware returns more than userspace asks for you
> > have a buffer overrun.
> > 
> >   
> > > +	if (mbox_cmd.size_out) {
> > > +		if (copy_to_user(u64_to_user_ptr(out_payload),
> > > +				 mbox_cmd.payload_out, *size_out)) {
> > > +			rc = -EFAULT;
> > > +			goto out;
> > > +		}
> > > +	}
> > > +
> > > +	/*
> > > +	 * Reporting the actual size, even if it was greater than @size_out
> > > +	 * allows userspace to try the command again with a bigger buffer.
> > > +	 */
> > > +	*size_out = mbox_cmd.size_out;
> > > +	*retval = mbox_cmd.return_code;
> > > +
> > > +out:
> > > +	kvfree(mbox_cmd.payload_in);
> > > +	kvfree(mbox_cmd.payload_out);
> > > +	return rc;
> > > +}
> > > +
> > > +/**
> > > + * cxl_validate_cmd_from_user() - Check fields for CXL_MEM_SEND_COMMAND.
> > > + * @cxlm: &struct cxl_mem device whose mailbox will be used.
> > > + * @send_cmd: &struct cxl_send_command copied in from userspace.
> > > + * @out_cmd: Sanitized and populated &struct cxl_mem_command.
> > > + *
> > > + * Return:
> > > + *  * %0	- @out_cmd is ready to send.
> > > + *  * %-ENOTTY	- Invalid command specified.
> > > + *  * %-EINVAL	- Reserved fields or invalid values were used.
> > > + *  * %-ENOMEM	- Input or output buffer wasn't sized properly.
> > > + *
> > > + * The result of this command is a fully validated command in @out_cmd that is
> > > + * safe to send to the hardware.
> > > + *
> > > + * See handle_mailbox_cmd_from_user()
> > > + */
> > > +static int cxl_validate_cmd_from_user(struct cxl_mem *cxlm,
> > > +				      const struct cxl_send_command *send_cmd,
> > > +				      struct cxl_mem_command *out_cmd)
> > > +{
> > > +	const struct cxl_command_info *info;
> > > +	struct cxl_mem_command *c;
> > > +
> > > +	if (send_cmd->id == 0 || send_cmd->id >= CXL_MEM_COMMAND_ID_MAX)
> > > +		return -ENOTTY;
> > > +
> > > +	/*
> > > +	 * The user can never specify an input payload larger than what hardware
> > > +	 * supports, but output can be arbitrarily large (simply write out as
> > > +	 * much data as the hardware provides).
> > > +	 */
> > > +	if (send_cmd->in.size > cxlm->payload_size)
> > > +		return -EINVAL;
> > > +
> > > +	if (send_cmd->flags & ~CXL_MEM_COMMAND_FLAG_MASK)
> > > +		return -EINVAL;
> > > +
> > > +	if (send_cmd->rsvd)
> > > +		return -EINVAL;
> > > +
> > > +	if (send_cmd->in.rsvd || send_cmd->out.rsvd)
> > > +		return -EINVAL;
> > > +
> > > +	/* Convert user's command into the internal representation */
> > > +	c = &mem_commands[send_cmd->id];
> > > +	info = &c->info;
> > > +
> > > +	/* Check the input buffer is the expected size */
> > > +	if (info->size_in >= 0 && info->size_in != send_cmd->in.size)
> > > +		return -ENOMEM;
> > > +
> > > +	/* Check the output buffer is at least large enough */
> > > +	if (info->size_out >= 0 && send_cmd->out.size < info->size_out)
> > > +		return -ENOMEM;
> > > +
> > > +	memcpy(out_cmd, c, sizeof(*c));
> > > +	out_cmd->info.size_in = send_cmd->in.size;
> > > +	out_cmd->info.size_out = send_cmd->out.size;
> > > +
> > > +	return 0;
> > > +}
> > > +
> > > +static int cxl_query_cmd(struct cxl_memdev *cxlmd,
> > > +			 struct cxl_mem_query_commands __user *q)
> > > +{
> > > +	struct device *dev = &cxlmd->dev;
> > > +	struct cxl_mem_command *cmd;
> > > +	u32 n_commands;
> > > +	int j = 0;
> > > +
> > > +	dev_dbg(dev, "Query IOCTL\n");
> > > +
> > > +	if (get_user(n_commands, &q->n_commands))
> > > +		return -EFAULT;
> > > +
> > > +	/* returns the total number if 0 elements are requested. */
> > > +	if (n_commands == 0)
> > > +		return put_user(cxl_cmd_count, &q->n_commands);
> > > +
> > > +	/*
> > > +	 * otherwise, return max(n_commands, total commands) cxl_command_info
> > > +	 * structures.
> > > +	 */
> > > +	cxl_for_each_cmd(cmd) {
> > > +		const struct cxl_command_info *info = &cmd->info;
> > > +
> > > +		if (copy_to_user(&q->commands[j++], info, sizeof(*info)))
> > > +			return -EFAULT;
> > > +
> > > +		if (j == n_commands)
> > > +			break;
> > > +	}
> > > +
> > > +	return 0;
> > > +}
> > > +
> > > +static int cxl_send_cmd(struct cxl_memdev *cxlmd,
> > > +			struct cxl_send_command __user *s)
> > > +{
> > > +	struct cxl_mem *cxlm = cxlmd->cxlm;
> > > +	struct device *dev = &cxlmd->dev;
> > > +	struct cxl_send_command send;
> > > +	struct cxl_mem_command c;
> > > +	int rc;
> > > +
> > > +	dev_dbg(dev, "Send IOCTL\n");
> > > +
> > > +	if (copy_from_user(&send, s, sizeof(send)))
> > > +		return -EFAULT;
> > > +
> > > +	rc = cxl_validate_cmd_from_user(cxlmd->cxlm, &send, &c);
> > > +	if (rc)
> > > +		return rc;  
> > 
> > Userspace will pass in send.out set to the size of it's available buffer.
> > Then cxl_validate_cmd_from_user() will fill
> > c.info.size_out with send.out.size
> >   
> > > +
> > > +	/* Prepare to handle a full payload for variable sized output */
> > > +	if (c.info.size_out < 0)  
> > 
> > So this check only works if userspace set the command to have variable size.
> > That's not what the docs below suggest should happen.
> >   
> 
> Another good catch. This bug was introduced after the last change was made. I
> still don't want to have a size_out as part of the mailbox command.
> 
> Validate should not alter the size_out field except in the case of RAW commands.
> 
> I believe this is the right fix, handle_mailbox_cmd_from_user() already will
> only copy_to the right number of byte, but your eyes on it are appreciated.
> 
> diff --git a/drivers/cxl/mem.c b/drivers/cxl/mem.c
> index 237b956f0be0..4ca4f5afd9d2 100644
> --- a/drivers/cxl/mem.c
> +++ b/drivers/cxl/mem.c
> @@ -686,7 +686,11 @@ static int cxl_validate_cmd_from_user(struct cxl_mem *cxlm,
> 
>         memcpy(out_cmd, c, sizeof(*c));
>         out_cmd->info.size_in = send_cmd->in.size;
> -       out_cmd->info.size_out = send_cmd->out.size;
> +       /*
> +        * XXX: out_cmd->info.size_out will be controlled by the driver, and the
> +        * specified number of bytes @send_cmd->out.size will be copied back out
> +        * to userspace.
> +        */
> 
>         return 0;
>  }

This deals with the buffer overflow being triggered from userspace.

I'm still nervous.  I really don't like assuming hardware will do the right
thing and never send us more data than we expect.

Given the check that it will fit in the target buffer is simple,
I'd prefer to harden it and know we can't have a problem.

Jonathan


> 
> > > +		c.info.size_out = cxlm->payload_size;
> > > +
> > > +	rc = handle_mailbox_cmd_from_user(cxlm, &c, send.in.payload,
> > > +					  send.out.payload, &send.out.size,
> > > +					  &send.retval);
> > > +	if (rc)
> > > +		return rc;
> > > +
> > > +	return copy_to_user(s, &send, sizeof(send));
> > > +}
> > > +
> > > +static long __cxl_memdev_ioctl(struct cxl_memdev *cxlmd, unsigned int cmd,
> > > +			       unsigned long arg)
> > > +{
> > > +	switch (cmd) {
> > > +	case CXL_MEM_QUERY_COMMANDS:
> > > +		return cxl_query_cmd(cxlmd, (void __user *)arg);
> > > +	case CXL_MEM_SEND_COMMAND:
> > > +		return cxl_send_cmd(cxlmd, (void __user *)arg);
> > > +	default:
> > > +		return -ENOTTY;
> > > +	}
> > > +}
> > > +
> > >  static long cxl_memdev_ioctl(struct file *file, unsigned int cmd,
> > >  			     unsigned long arg)
> > >  {
> > > @@ -325,7 +611,7 @@ static long cxl_memdev_ioctl(struct file *file, unsigned int cmd,
> > >  	if (!percpu_ref_tryget_live(&cxlmd->ops_active))
> > >  		return -ENXIO;
> > >  
> > > -	/* TODO: ioctl body */
> > > +	rc = __cxl_memdev_ioctl(cxlmd, cmd, arg);
> > >  
> > >  	percpu_ref_put(&cxlmd->ops_active);
> > >  
> > > diff --git a/include/uapi/linux/cxl_mem.h b/include/uapi/linux/cxl_mem.h
> > > new file mode 100644
> > > index 000000000000..18cea908ad0b
> > > --- /dev/null
> > > +++ b/include/uapi/linux/cxl_mem.h
> > > @@ -0,0 +1,154 @@
> > > +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
> > > +/*
> > > + * CXL IOCTLs for Memory Devices
> > > + */
> > > +
> > > +#ifndef _UAPI_CXL_MEM_H_
> > > +#define _UAPI_CXL_MEM_H_
> > > +
> > > +#include <linux/types.h>
> > > +
> > > +/**
> > > + * DOC: UAPI
> > > + *
> > > + * Not all of all commands that the driver supports are always available for use
> > > + * by userspace. Userspace must check the results from the QUERY command in
> > > + * order to determine the live set of commands.
> > > + */
> > > +
> > > +#define CXL_MEM_QUERY_COMMANDS _IOR(0xCE, 1, struct cxl_mem_query_commands)
> > > +#define CXL_MEM_SEND_COMMAND _IOWR(0xCE, 2, struct cxl_send_command)
> > > +
> > > +#define CXL_CMDS                                                          \
> > > +	___C(INVALID, "Invalid Command"),                                 \
> > > +	___C(IDENTIFY, "Identify Command"),                               \
> > > +	___C(MAX, "invalid / last command")
> > > +
> > > +#define ___C(a, b) CXL_MEM_COMMAND_ID_##a
> > > +enum { CXL_CMDS };
> > > +
> > > +#undef ___C
> > > +#define ___C(a, b) { b }
> > > +static const struct {
> > > +	const char *name;
> > > +} cxl_command_names[] = { CXL_CMDS };
> > > +
> > > +/*
> > > + * Here's how this actually breaks out:
> > > + * cxl_command_names[] = {
> > > + *	[CXL_MEM_COMMAND_ID_INVALID] = { "Invalid Command" },
> > > + *	[CXL_MEM_COMMAND_ID_IDENTIFY] = { "Identify Command" },
> > > + *	...
> > > + *	[CXL_MEM_COMMAND_ID_MAX] = { "invalid / last command" },
> > > + * };
> > > + */  
> > 
> > Thanks, this is great.
> >   
> > > +
> > > +#undef ___C
> > > +
> > > +/**
> > > + * struct cxl_command_info - Command information returned from a query.
> > > + * @id: ID number for the command.
> > > + * @flags: Flags that specify command behavior.
> > > + * @size_in: Expected input size, or -1 if variable length.
> > > + * @size_out: Expected output size, or -1 if variable length.
> > > + *
> > > + * Represents a single command that is supported by both the driver and the
> > > + * hardware. This is returned as part of an array from the query ioctl. The
> > > + * following would be a command that takes a variable length input and returns 0
> > > + * bytes of output.
> > > + *
> > > + *  - @id = 10
> > > + *  - @flags = 0
> > > + *  - @size_in = -1
> > > + *  - @size_out = 0
> > > + *
> > > + * See struct cxl_mem_query_commands.
> > > + */
> > > +struct cxl_command_info {
> > > +	__u32 id;
> > > +
> > > +	__u32 flags;
> > > +#define CXL_MEM_COMMAND_FLAG_MASK GENMASK(0, 0)
> > > +
> > > +	__s32 size_in;
> > > +	__s32 size_out;
> > > +};
> > > +
> > > +/**
> > > + * struct cxl_mem_query_commands - Query supported commands.
> > > + * @n_commands: In/out parameter. When @n_commands is > 0, the driver will
> > > + *		return min(num_support_commands, n_commands). When @n_commands
> > > + *		is 0, driver will return the number of total supported commands.
> > > + * @rsvd: Reserved for future use.
> > > + * @commands: Output array of supported commands. This array must be allocated
> > > + *            by userspace to be at least min(num_support_commands, @n_commands)
> > > + *
> > > + * Allow userspace to query the available commands supported by both the driver,
> > > + * and the hardware. Commands that aren't supported by either the driver, or the
> > > + * hardware are not returned in the query.
> > > + *
> > > + * Examples:
> > > + *
> > > + *  - { .n_commands = 0 } // Get number of supported commands
> > > + *  - { .n_commands = 15, .commands = buf } // Return first 15 (or less)
> > > + *    supported commands
> > > + *
> > > + *  See struct cxl_command_info.
> > > + */
> > > +struct cxl_mem_query_commands {
> > > +	/*
> > > +	 * Input: Number of commands to return (space allocated by user)
> > > +	 * Output: Number of commands supported by the driver/hardware
> > > +	 *
> > > +	 * If n_commands is 0, kernel will only return number of commands and
> > > +	 * not try to populate commands[], thus allowing userspace to know how
> > > +	 * much space to allocate
> > > +	 */  
> > 
> > This is fairly well described in the docs above the structure.
> > Perhaps combine the two.
> >   
> > > +	__u32 n_commands;
> > > +	__u32 rsvd;
> > > +
> > > +	struct cxl_command_info __user commands[]; /* out: supported commands */
> > > +};
> > > +
> > > +/**
> > > + * struct cxl_send_command - Send a command to a memory device.
> > > + * @id: The command to send to the memory device. This must be one of the
> > > + *	commands returned by the query command.
> > > + * @flags: Flags for the command (input).
> > > + * @rsvd: Must be zero.
> > > + * @retval: Return value from the memory device (output).
> > > + * @in.size: Size of the payload to provide to the device (input).
> > > + * @in.rsvd: Must be zero.
> > > + * @in.payload: Pointer to memory for payload input, payload is little endian.
> > > + * @out.size: Size of the payload received from the device (input/output). This
> > > + *	      field is filled in by userspace to let the driver know how much
> > > + *	      space was allocated for output. It is populated by the driver to
> > > + *	      let userspace know how large the output payload actually was.
> > > + * @out.rsvd: Must be zero.
> > > + * @out.payload: Pointer to memory for payload output, payload is little endian.
> > > + *
> > > + * Mechanism for userspace to send a command to the hardware for processing. The
> > > + * driver will do basic validation on the command sizes. In some cases even the
> > > + * payload may be introspected. Userspace is required to allocate large enough
> > > + * buffers for size_out which can be variable length in certain situations.
> > > + */
> > > +struct cxl_send_command {
> > > +	__u32 id;
> > > +	__u32 flags;
> > > +	__u32 rsvd;
> > > +	__u32 retval;
> > > +
> > > +	struct {
> > > +		__s32 size;
> > > +		__u32 rsvd;
> > > +		__u64 payload;
> > > +	} in;
> > > +
> > > +	struct {
> > > +		__s32 size;
> > > +		__u32 rsvd;
> > > +		__u64 payload;
> > > +	} out;
> > > +};
> > > +
> > > +#endif  
> >
Jonathan Cameron Feb. 17, 2021, 9:55 a.m. UTC | #9
On Tue, 16 Feb 2021 10:34:32 -0800
Ben Widawsky <ben.widawsky@intel.com> wrote:

...

> > > diff --git a/drivers/cxl/mem.c b/drivers/cxl/mem.c

> > > index 237b956f0be0..4ca4f5afd9d2 100644

> > > --- a/drivers/cxl/mem.c

> > > +++ b/drivers/cxl/mem.c

> > > @@ -686,7 +686,11 @@ static int cxl_validate_cmd_from_user(struct cxl_mem *cxlm,

> > > 

> > >         memcpy(out_cmd, c, sizeof(*c));

> > >         out_cmd->info.size_in = send_cmd->in.size;

> > > -       out_cmd->info.size_out = send_cmd->out.size;

> > > +       /*

> > > +        * XXX: out_cmd->info.size_out will be controlled by the driver, and the

> > > +        * specified number of bytes @send_cmd->out.size will be copied back out

> > > +        * to userspace.

> > > +        */

> > > 

> > >         return 0;

> > >  }  

> > 

> > This deals with the buffer overflow being triggered from userspace.

> > 

> > I'm still nervous.  I really don't like assuming hardware will do the right

> > thing and never send us more data than we expect.

> > 

> > Given the check that it will fit in the target buffer is simple,

> > I'd prefer to harden it and know we can't have a problem.

> > 

> > Jonathan  

> 

> I'm working on hardening __cxl_mem_mbox_send_cmd now per your request. With

> that, I think this solves the issue, right?


Should do.  Thanks,

Jonathan