/* SPDX-License-Identifier: GPL-2.0-only */
/* Copyright(c) 2024 Intel Corporation. */
#ifndef __CXL_MBOX_H__
#define __CXL_MBOX_H__
#include <linux/rcuwait.h>
#include <cxl/features.h>
#include <uapi/linux/cxl_mem.h>

/**
 * struct cxl_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_in.
 * @size_out: (input) Max number of bytes loaded into @payload_out.
 *            (output) Number of bytes generated by the device. For fixed size
 *            outputs commands this is always expected to be deterministic. For
 *            variable sized output commands, it tells the exact number of bytes
 *            written.
 * @min_out: (input) internal command output payload size validation
 * @poll_count: (input) Number of timeouts to attempt.
 * @poll_interval_ms: (input) Time between mailbox background command polling
 *                    interval timeouts.
 * @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 cxl_mbox_cmd {
	u16 opcode;
	void *payload_in;
	void *payload_out;
	size_t size_in;
	size_t size_out;
	size_t min_out;
	int poll_count;
	int poll_interval_ms;
	u16 return_code;
};

/**
 * struct cxl_mailbox - context for CXL mailbox operations
 * @host: device that hosts the mailbox
 * @enabled_cmds: mailbox commands that are enabled by the driver
 * @exclusive_cmds: mailbox commands that are exclusive to the kernel
 * @payload_size: Size of space for payload
 *                (CXL 3.1 8.2.8.4.3 Mailbox Capabilities Register)
 * @mbox_mutex: mutex protects device mailbox and firmware
 * @mbox_wait: rcuwait for mailbox
 * @mbox_send: @dev specific transport for transmitting mailbox commands
 * @feat_cap: Features capability
 */
struct cxl_mailbox {
	struct device *host;
	DECLARE_BITMAP(enabled_cmds, CXL_MEM_COMMAND_ID_MAX);
	DECLARE_BITMAP(exclusive_cmds, CXL_MEM_COMMAND_ID_MAX);
	size_t payload_size;
	struct mutex mbox_mutex; /* lock to protect mailbox context */
	struct rcuwait mbox_wait;
	int (*mbox_send)(struct cxl_mailbox *cxl_mbox, struct cxl_mbox_cmd *cmd);
	enum cxl_features_capability feat_cap;
};

int cxl_mailbox_init(struct cxl_mailbox *cxl_mbox, struct device *host);

#endif
