Skip to contentSkip to conversation

Habana Labs kernel driver

PATCH Superseded Oded Gabbay 17 participants 103 messages Jan 23, 2019 – Feb 24, 2019 Page 2 of 3

Subsystems (7)

v1 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#33 lore raw

Re: [PATCH 07/15] habanalabs: add h/w queues module

In reply to Oded Gabbay
Quoted 151 lines · Oded Gabbay

This patch adds the H/W queues module and the code to initialize Goya's various compute and DMA engines and their queues.

Goya has 5 DMA channels, 8 TPC engines and a single MME engine. For each channel/engine, there is a H/W queue logic which is used to pass commands from the user to the H/W. That logic is called QMAN.

There are two types of QMANs: external and internal. The DMA QMANs are considered external while the TPC and MME QMANs are considered internal. For each external queue there is a completion queue, which is located on the Host memory.

The differences between external and internal QMANs are:

1. The location of the queue's memory. External QMANs are located on the Host memory while internal QMANs are located on the on-chip memory.

2. The external QMAN write an entry to a completion queue and sends an MSI-X interrupt upon completion of a command buffer that was given to it. The internal QMAN doesn't do that.

---
 drivers/misc/habanalabs/Makefile              |    2 +-
 drivers/misc/habanalabs/device.c              |   74 +-
 drivers/misc/habanalabs/goya/goya.c           | 1518 +++++++++++++++--
 drivers/misc/habanalabs/goya/goyaP.h          |    6 +
 drivers/misc/habanalabs/habanalabs.h          |  176 +-
 drivers/misc/habanalabs/habanalabs_drv.c      |    6 +
 drivers/misc/habanalabs/hw_queue.c            |  404 +++++
 .../habanalabs/include/goya/goya_packets.h    |  234 +++
 .../habanalabs/include/habanalabs_device_if.h |  272 +++
 drivers/misc/habanalabs/irq.c                 |  150 ++
 10 files changed, 2721 insertions(+), 121 deletions(-)
 create mode 100644 drivers/misc/habanalabs/hw_queue.c
 create mode 100644 drivers/misc/habanalabs/include/goya/goya_packets.h
 create mode 100644 drivers/misc/habanalabs/irq.c
drivers/misc/habanalabs/Makefile +1 -1
index 2530c9b78ca4..c07f3ccb57dc 100644
@@ -5,7 +5,7 @@
 obj-m	:= habanalabs.o
 
 habanalabs-y := habanalabs_drv.o device.o context.o asid.o habanalabs_ioctl.o \
-		command_buffer.o
+		command_buffer.o hw_queue.o irq.o
 
 include $(src)/goya/Makefile
 habanalabs-y += $(HL_GOYA_FILES)
drivers/misc/habanalabs/device.c +51 -2
index 9fc7218a973c..98220628a467 100644
@@ -170,13 +170,22 @@ static int device_early_init(struct hl_device *hdev)
 	if (rc)
 		goto early_fini;
 
+	hdev->cq_wq = alloc_workqueue("hl-free-jobs", WQ_UNBOUND, 0);
+	if (hdev->cq_wq == NULL) {
+		dev_err(hdev->dev, "Failed to allocate CQ workqueue\n");
+		goto asid_fini;
+	}
+
 	hl_cb_mgr_init(&hdev->kernel_cb_mgr);
 
 	mutex_init(&hdev->device_open);
+	mutex_init(&hdev->send_cpu_message_lock);
 	atomic_set(&hdev->fd_open_cnt, 0);
 
 	return 0;
 
+asid_fini:
+	hl_asid_fini(hdev);
 early_fini:
 	if (hdev->asic_funcs->early_fini)
 		hdev->asic_funcs->early_fini(hdev);
@@ -192,9 +201,12 @@ static int device_early_init(struct hl_device *hdev)
  */
 static void device_early_fini(struct hl_device *hdev)
 {
+	mutex_destroy(&hdev->send_cpu_message_lock);
 
 	hl_cb_mgr_fini(hdev, &hdev->kernel_cb_mgr);
 
+	destroy_workqueue(hdev->cq_wq);
+
 	hl_asid_fini(hdev);
 
 	if (hdev->asic_funcs->early_fini)
@@ -273,7 +285,7 @@ int hl_device_resume(struct hl_device *hdev)
  */
 int hl_device_init(struct hl_device *hdev, struct class *hclass)
 {
-	int rc;
+	int i, rc, cq_ready_cnt;
 
 	/* Create device */
 	rc = device_setup_cdev(hdev, hclass, hdev->id, &hl_ops);
@@ -294,11 +306,48 @@ int hl_device_init(struct hl_device *hdev, struct class *hclass)
 	if (rc)
 		goto early_fini;
 
+	/*
+	 * Initialize the H/W queues. Must be done before hw_init, because
+	 * there the addresses of the kernel queue are being written to the
+	 * registers of the device
+	 */
+	rc = hl_hw_queues_create(hdev);
+	if (rc) {
+		dev_err(hdev->dev, "failed to initialize kernel queues\n");
+		goto sw_fini;
+	}
+
+	/*
+	 * Initialize the completion queues. Must be done before hw_init,
+	 * because there the addresses of the completion queues are being
+	 * passed as arguments to request_irq
+	 */
+	hdev->completion_queue =
+			kcalloc(hdev->asic_prop.completion_queues_count,
+				sizeof(*hdev->completion_queue), GFP_KERNEL);
+
+	if (!hdev->completion_queue) {
+		dev_err(hdev->dev, "failed to allocate completion queues\n");
+		rc = -ENOMEM;
+		goto hw_queues_destroy;
+	}
+
+	for (i = 0, cq_ready_cnt = 0;
+			i < hdev->asic_prop.completion_queues_count;
+			i++, cq_ready_cnt++) {
+		rc = hl_cq_init(hdev, &hdev->completion_queue[i], i);
+		if (rc) {
+			dev_err(hdev->dev,
+				"failed to initialize completion queue\n");
+			goto cq_fini;
+		}
+	}
+
 	/* Allocate the kernel context */
 	hdev->kernel_ctx = kzalloc(sizeof(*hdev->kernel_ctx), GFP_KERNEL);
 	if (!hdev->kernel_ctx) {
 		rc = -ENOMEM;
-		goto sw_fini;
+		goto cq_fini;
 	}
 
 	hdev->user_ctx = NULL;

drivers/misc/habanalabs/device.c int hl_device_init(struct hl_device *hdev, struct class *hclass) · line 380

Quoted 8 lines
drivers/misc/habanalabs/device.c +5 -0
@@ -324,6 +373,14 @@ int hl_device_init(struct hl_device *hdev, struct class *hclass)
 
 	hdev->disabled = false;
 
+	/* Check that the communication with the device is working */
+	rc = hdev->asic_funcs->test_queues(hdev);
+	if (rc) {
+		dev_err(hdev->dev, "Failed to detect if device is alive\n");
+		rc = 0;

Why rc is 0 here?

Quoted 242 lines
drivers/misc/habanalabs/device.c +16 -0
+		goto out_disabled;
+	}
+
 	dev_notice(hdev->dev,
 		"Successfully added device to habanalabs driver\n");
 
@@ -335,6 +392,12 @@ int hl_device_init(struct hl_device *hdev, struct class *hclass)
 			"kernel ctx is still alive on initialization failure\n");
 free_ctx:
 	kfree(hdev->kernel_ctx);
+cq_fini:
+	for (i = 0 ; i < cq_ready_cnt ; i++)
+		hl_cq_fini(hdev, &hdev->completion_queue[i]);
+	kfree(hdev->completion_queue);
+hw_queues_destroy:
+	hl_hw_queues_destroy(hdev);
 sw_fini:
 	hdev->asic_funcs->sw_fini(hdev);
 early_fini:
@@ -364,6 +427,7 @@ int hl_device_init(struct hl_device *hdev, struct class *hclass)
  */
 void hl_device_fini(struct hl_device *hdev)
 {
+	int i;
 	dev_info(hdev->dev, "Removing device\n");
 
 	/* Mark device as disabled */
@@ -378,6 +442,12 @@ void hl_device_fini(struct hl_device *hdev)
 	/* Reset the H/W. It will be in idle state after this returns */
 	hdev->asic_funcs->hw_fini(hdev, true);
 
+	for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
+		hl_cq_fini(hdev, &hdev->completion_queue[i]);
+	kfree(hdev->completion_queue);
+
+	hl_hw_queues_destroy(hdev);
+
 	/* Call ASIC S/W finalize function */
 	hdev->asic_funcs->sw_fini(hdev);
 
drivers/misc/habanalabs/goya/goya.c +173 -0
index f715e01838b3..08d5227eaf1d 100644
@@ -98,6 +98,26 @@
 static void goya_get_fixed_properties(struct hl_device *hdev)
 {
 	struct asic_fixed_properties *prop = &hdev->asic_prop;
+	int i;
+
+	for (i = 0 ; i < NUMBER_OF_EXT_HW_QUEUES ; i++) {
+		prop->hw_queues_props[i].type = QUEUE_TYPE_EXT;
+		prop->hw_queues_props[i].kmd_only = 0;
+	}
+
+	for (; i < NUMBER_OF_EXT_HW_QUEUES + NUMBER_OF_CPU_HW_QUEUES ; i++) {
+		prop->hw_queues_props[i].type = QUEUE_TYPE_CPU;
+		prop->hw_queues_props[i].kmd_only = 1;
+	}
+
+	for (; i < NUMBER_OF_EXT_HW_QUEUES + NUMBER_OF_CPU_HW_QUEUES +
+			NUMBER_OF_INT_HW_QUEUES; i++) {
+		prop->hw_queues_props[i].type = QUEUE_TYPE_INT;
+		prop->hw_queues_props[i].kmd_only = 0;
+	}
+
+	for (; i < HL_MAX_QUEUES; i++)
+		prop->hw_queues_props[i].type = QUEUE_TYPE_NA;
 
 	prop->completion_queues_count = NUMBER_OF_CMPLT_QUEUES;
 
@@ -126,6 +146,18 @@ static void goya_get_fixed_properties(struct hl_device *hdev)
 	prop->high_pll = PLL_HIGH_DEFAULT;
 }
 
+int goya_send_pci_access_msg(struct hl_device *hdev, u32 opcode)
+{
+	struct armcp_packet pkt;
+
+	memset(&pkt, 0, sizeof(pkt));
+
+	pkt.opcode = opcode;
+
+	return hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &pkt,
+			sizeof(pkt), HL_DEVICE_TIMEOUT_USEC, NULL);
+}
+
 /**
  * goya_pci_bars_map - Map PCI BARS of Goya device
  *
@@ -509,6 +541,8 @@ static int goya_sw_init(struct hl_device *hdev)
 	if (!goya)
 		return -ENOMEM;
 
+	goya->test_cpu_queue = goya_test_cpu_queue;
+
 	/* according to goya_init_iatu */
 	goya->ddr_bar_cur_addr = DRAM_PHYS_BASE;
 	hdev->asic_specific = goya;
@@ -595,6 +629,299 @@ int goya_sw_fini(struct hl_device *hdev)
 	return 0;
 }
 
+static void goya_init_dma_qman(struct hl_device *hdev, int dma_id,
+		dma_addr_t bus_address)
+{
+	struct goya_device *goya = hdev->asic_specific;
+	u32 mtr_base_lo, mtr_base_hi;
+	u32 so_base_lo, so_base_hi;
+	u32 gic_base_lo, gic_base_hi;
+	u32 reg_off = dma_id * (mmDMA_QM_1_PQ_PI - mmDMA_QM_0_PQ_PI);
+
+	mtr_base_lo = lower_32_bits(CFG_BASE + mmSYNC_MNGR_MON_PAY_ADDRL_0);
+	mtr_base_hi = upper_32_bits(CFG_BASE + mmSYNC_MNGR_MON_PAY_ADDRL_0);
+	so_base_lo = lower_32_bits(CFG_BASE + mmSYNC_MNGR_SOB_OBJ_0);
+	so_base_hi = upper_32_bits(CFG_BASE + mmSYNC_MNGR_SOB_OBJ_0);
+
+	gic_base_lo =
+		lower_32_bits(CFG_BASE + mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR);
+	gic_base_hi =
+		upper_32_bits(CFG_BASE + mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR);
+
+	WREG32(mmDMA_QM_0_PQ_BASE_LO + reg_off, lower_32_bits(bus_address));
+	WREG32(mmDMA_QM_0_PQ_BASE_HI + reg_off, upper_32_bits(bus_address));
+
+	WREG32(mmDMA_QM_0_PQ_SIZE + reg_off, ilog2(HL_QUEUE_LENGTH));
+	WREG32(mmDMA_QM_0_PQ_PI + reg_off, 0);
+	WREG32(mmDMA_QM_0_PQ_CI + reg_off, 0);
+
+	WREG32(mmDMA_QM_0_CP_MSG_BASE0_ADDR_LO + reg_off, mtr_base_lo);
+	WREG32(mmDMA_QM_0_CP_MSG_BASE0_ADDR_HI + reg_off, mtr_base_hi);
+	WREG32(mmDMA_QM_0_CP_MSG_BASE1_ADDR_LO + reg_off, so_base_lo);
+	WREG32(mmDMA_QM_0_CP_MSG_BASE1_ADDR_HI + reg_off, so_base_hi);
+	WREG32(mmDMA_QM_0_GLBL_ERR_ADDR_LO + reg_off, gic_base_lo);
+	WREG32(mmDMA_QM_0_GLBL_ERR_ADDR_HI + reg_off, gic_base_hi);
+	WREG32(mmDMA_QM_0_GLBL_ERR_WDATA + reg_off,
+			GOYA_ASYNC_EVENT_ID_DMA0_QM + dma_id);
+
+	/* PQ has buffer of 2 cache lines, while CQ has 8 lines */
+	WREG32(mmDMA_QM_0_PQ_CFG1 + reg_off, 0x00020002);
+	WREG32(mmDMA_QM_0_CQ_CFG1 + reg_off, 0x00080008);
+
+	if (dma_id == 0)
+		WREG32(mmDMA_QM_0_GLBL_PROT + reg_off, QMAN_DMA_FULLY_TRUSTED);
+	else
+		if (goya->hw_cap_initialized & HW_CAP_MMU)
+			WREG32(mmDMA_QM_0_GLBL_PROT + reg_off,
+					QMAN_DMA_PARTLY_TRUSTED);
+		else
+			WREG32(mmDMA_QM_0_GLBL_PROT + reg_off,
+					QMAN_DMA_FULLY_TRUSTED);
+
+	WREG32(mmDMA_QM_0_GLBL_ERR_CFG + reg_off, QMAN_DMA_ERR_MSG_EN);
+	WREG32(mmDMA_QM_0_GLBL_CFG0 + reg_off, QMAN_DMA_ENABLE);
+}
+
+static void goya_init_dma_ch(struct hl_device *hdev, int dma_id)
+{
+	u32 gic_base_lo, gic_base_hi;
+	u64 sob_addr;
+	u32 reg_off = dma_id * (mmDMA_CH_1_CFG1 - mmDMA_CH_0_CFG1);
+
+	gic_base_lo =
+		lower_32_bits(CFG_BASE + mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR);
+	gic_base_hi =
+		upper_32_bits(CFG_BASE + mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR);
+
+	WREG32(mmDMA_CH_0_ERRMSG_ADDR_LO + reg_off, gic_base_lo);
+	WREG32(mmDMA_CH_0_ERRMSG_ADDR_HI + reg_off, gic_base_hi);
+	WREG32(mmDMA_CH_0_ERRMSG_WDATA + reg_off,
+			GOYA_ASYNC_EVENT_ID_DMA0_CH + dma_id);
+
+	if (dma_id) {
+		sob_addr = CFG_BASE + mmSYNC_MNGR_SOB_OBJ_1000 +
+				(dma_id - 1) * 4;
+		WREG32(mmDMA_CH_0_WR_COMP_ADDR_LO + reg_off,
+				lower_32_bits(sob_addr));
+		WREG32(mmDMA_CH_0_WR_COMP_ADDR_HI + reg_off,
+				upper_32_bits(sob_addr));
+		WREG32(mmDMA_CH_0_WR_COMP_WDATA + reg_off, 0x80000001);
+	}
+}
+
+/**
+ * goya_init_dma_qmans - Initialize QMAN DMA registers
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ * Initialize the H/W registers of the QMAN DMA channels
+ *
+ */
+static void goya_init_dma_qmans(struct hl_device *hdev)
+{
+	struct goya_device *goya = hdev->asic_specific;
+	struct hl_hw_queue *q;
+	dma_addr_t bus_address;
+	int i;
+
+	if (goya->hw_cap_initialized & HW_CAP_DMA)
+		return;
+
+	q = &hdev->kernel_queues[0];
+
+	for (i = 0 ; i < NUMBER_OF_EXT_HW_QUEUES ; i++, q++) {
+		bus_address = q->bus_address +
+				hdev->asic_prop.host_phys_base_address;
+
+		goya_init_dma_qman(hdev, i, bus_address);
+		goya_init_dma_ch(hdev, i);
+	}
+
+	goya->hw_cap_initialized |= HW_CAP_DMA;
+}
+
+/**
+ * goya_disable_external_queues - Disable external queues
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ */
+static void goya_disable_external_queues(struct hl_device *hdev)
+{
+	WREG32(mmDMA_QM_0_GLBL_CFG0, 0);
+	WREG32(mmDMA_QM_1_GLBL_CFG0, 0);
+	WREG32(mmDMA_QM_2_GLBL_CFG0, 0);
+	WREG32(mmDMA_QM_3_GLBL_CFG0, 0);
+	WREG32(mmDMA_QM_4_GLBL_CFG0, 0);
+}
+
+static int goya_stop_queue(struct hl_device *hdev, u32 cfg_reg,
+				u32 cp_sts_reg, u32 glbl_sts0_reg)
+{
+	int rc;
+	u32 status;
+
+	/* use the values of TPC0 as they are all the same*/
+
+	WREG32(cfg_reg, 1 << TPC0_QM_GLBL_CFG1_CP_STOP_SHIFT);
+
+	status = RREG32(cp_sts_reg);
+	if (status & TPC0_QM_CP_STS_FENCE_IN_PROGRESS_MASK) {
+		rc = hl_poll_timeout(

drivers/misc/habanalabs/goya/goya.c int goya_sw_fini(struct hl_device *hdev) · line 780

Quoted 10 lines
drivers/misc/habanalabs/goya/goya.c +10 -0
+			hdev,
+			cp_sts_reg,
+			status,
+			!(status & TPC0_QM_CP_STS_FENCE_IN_PROGRESS_MASK),
+			1000,
+			QMAN_FENCE_TIMEOUT_USEC);
+
+		/* if QMAN is stuck in fence no need to check for stop */
+		if (rc)
+			return 0;

Isn't it an error?

Quoted 554 lines
drivers/misc/habanalabs/goya/goya.c +401 -113
+	}
+
+	rc = hl_poll_timeout(
+		hdev,
+		glbl_sts0_reg,
+		status,
+		(status & TPC0_QM_GLBL_STS0_CP_IS_STOP_MASK),
+		1000,
+		QMAN_STOP_TIMEOUT_USEC);
+
+	if (rc) {
+		dev_err(hdev->dev,
+			"Timeout while waiting for QMAN to stop\n");
+		return -EINVAL;
+	}
+
+	return 0;
+}
+
+/**
+ * goya_stop_external_queues - Stop external queues
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ * Returns 0 on success
+ *
+ */
+static int goya_stop_external_queues(struct hl_device *hdev)
+{
+	int rc = goya_stop_queue(hdev,
+			mmDMA_QM_0_GLBL_CFG1,
+			mmDMA_QM_0_CP_STS,
+			mmDMA_QM_0_GLBL_STS0);
+
+	if (rc)
+		dev_err(hdev->dev, "failed to stop DMA QMAN 0\n");
+
+	rc = goya_stop_queue(hdev,
+			mmDMA_QM_1_GLBL_CFG1,
+			mmDMA_QM_1_CP_STS,
+			mmDMA_QM_1_GLBL_STS0);
+
+	if (rc)
+		dev_err(hdev->dev, "failed to stop DMA QMAN 1\n");
+
+	rc = goya_stop_queue(hdev,
+			mmDMA_QM_2_GLBL_CFG1,
+			mmDMA_QM_2_CP_STS,
+			mmDMA_QM_2_GLBL_STS0);
+
+	if (rc)
+		dev_err(hdev->dev, "failed to stop DMA QMAN 2\n");
+
+	rc = goya_stop_queue(hdev,
+			mmDMA_QM_3_GLBL_CFG1,
+			mmDMA_QM_3_CP_STS,
+			mmDMA_QM_3_GLBL_STS0);
+
+	if (rc)
+		dev_err(hdev->dev, "failed to stop DMA QMAN 3\n");
+
+	rc = goya_stop_queue(hdev,
+			mmDMA_QM_4_GLBL_CFG1,
+			mmDMA_QM_4_CP_STS,
+			mmDMA_QM_4_GLBL_STS0);
+
+	if (rc)
+		dev_err(hdev->dev, "failed to stop DMA QMAN 4\n");
+
+	return rc;
+}
+
+static void goya_resume_external_queues(struct hl_device *hdev)
+{
+	WREG32(mmDMA_QM_0_GLBL_CFG1, 0);
+	WREG32(mmDMA_QM_1_GLBL_CFG1, 0);
+	WREG32(mmDMA_QM_2_GLBL_CFG1, 0);
+	WREG32(mmDMA_QM_3_GLBL_CFG1, 0);
+	WREG32(mmDMA_QM_4_GLBL_CFG1, 0);
+}
+
+/**
+ * goya_init_cpu_queues - Initialize PQ/CQ/EQ of CPU
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ * Returns 0 on success
+ *
+ */
+int goya_init_cpu_queues(struct hl_device *hdev)
+{
+	struct goya_device *goya = hdev->asic_specific;
+	dma_addr_t bus_address;
+	u32 status;
+	struct hl_hw_queue *cpu_pq = &hdev->kernel_queues[GOYA_QUEUE_ID_CPU_PQ];
+	int err;
+
+	if (!hdev->cpu_queues_enable)
+		return 0;
+
+	if (goya->hw_cap_initialized & HW_CAP_CPU_Q)
+		return 0;
+
+	bus_address = cpu_pq->bus_address +
+			hdev->asic_prop.host_phys_base_address;
+	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_0, lower_32_bits(bus_address));
+	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_1, upper_32_bits(bus_address));
+
+	bus_address = hdev->cpu_accessible_dma_address +
+			hdev->asic_prop.host_phys_base_address;
+	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_8, lower_32_bits(bus_address));
+	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_9, upper_32_bits(bus_address));
+
+	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_5, HL_QUEUE_SIZE_IN_BYTES);
+	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_10, CPU_ACCESSIBLE_MEM_SIZE);
+
+	/* Used for EQ CI */
+	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_6, 0);
+
+	WREG32(mmCPU_IF_PF_PQ_PI, 0);
+
+	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_7, PQ_INIT_STATUS_READY_FOR_CP);
+
+	WREG32(mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR,
+			GOYA_ASYNC_EVENT_ID_PI_UPDATE);
+
+	err = hl_poll_timeout(
+		hdev,
+		mmPSOC_GLOBAL_CONF_SCRATCHPAD_7,
+		status,
+		(status == PQ_INIT_STATUS_READY_FOR_HOST),
+		1000,
+		GOYA_CPU_TIMEOUT_USEC);
+
+	if (err) {
+		dev_err(hdev->dev,
+			"Failed to communicate with ARM CPU (ArmCP timeout)\n");
+		return -EIO;
+	}
+
+	goya->hw_cap_initialized |= HW_CAP_CPU_Q;
+	return 0;
+}
+
 /**
  * goya_init_pll - Initialize pll registers
  *
@@ -1960,152 +2287,646 @@ static void goya_init_golden_registers(struct hl_device *hdev)
 	goya->hw_cap_initialized |= HW_CAP_GOLDEN;
 }
 
-
-/**
- * goya_push_uboot_to_device - Push u-boot FW code to device
- *
- * @hdev: pointer to hl_device structure
- *
- * Copy u-boot fw code from firmware file to SRAM BAR.
- * Returns 0 on success
- *
- */
-static int goya_push_uboot_to_device(struct hl_device *hdev)
+static void goya_init_mme_qman(struct hl_device *hdev)
 {
-	char fw_name[200];
-	const u64 *fw_data;
-	void __iomem *dst;
-	size_t fw_size, i;
-	int rc;
+	u32 mtr_base_lo, mtr_base_hi;
+	u32 so_base_lo, so_base_hi;
+	u32 gic_base_lo, gic_base_hi;
+	u64 qman_base_addr;
 
-	snprintf(fw_name, sizeof(fw_name), "habanalabs/goya/goya-u-boot.bin");
+	mtr_base_lo = lower_32_bits(CFG_BASE + mmSYNC_MNGR_MON_PAY_ADDRL_0);
+	mtr_base_hi = upper_32_bits(CFG_BASE + mmSYNC_MNGR_MON_PAY_ADDRL_0);
+	so_base_lo = lower_32_bits(CFG_BASE + mmSYNC_MNGR_SOB_OBJ_0);
+	so_base_hi = upper_32_bits(CFG_BASE + mmSYNC_MNGR_SOB_OBJ_0);
 
-	rc = request_firmware(&hdev->spl_fw, fw_name, hdev->dev);
+	gic_base_lo =
+		lower_32_bits(CFG_BASE + mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR);
+	gic_base_hi =
+		upper_32_bits(CFG_BASE + mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR);
 
-	if (rc) {
-		dev_err(hdev->dev, "Failed to request u-boot fw image\n");
-		goto out;
-	}
+	qman_base_addr = hdev->asic_prop.sram_base_address +
+				MME_QMAN_BASE_OFFSET;
 
-	fw_size = hdev->spl_fw->size;
-	if ((fw_size % 4) != 0) {
-		dev_err(hdev->dev, "illegal u-boot firmware size %lu\n",
-			fw_size);
-		rc = -EINVAL;
-		goto out;
-	}
+	WREG32(mmMME_QM_PQ_BASE_LO, lower_32_bits(qman_base_addr));
+	WREG32(mmMME_QM_PQ_BASE_HI, upper_32_bits(qman_base_addr));
+	WREG32(mmMME_QM_PQ_SIZE, ilog2(MME_QMAN_LENGTH));
+	WREG32(mmMME_QM_PQ_PI, 0);
+	WREG32(mmMME_QM_PQ_CI, 0);
+	WREG32(mmMME_QM_CP_LDMA_SRC_BASE_LO_OFFSET, 0x10C0);
+	WREG32(mmMME_QM_CP_LDMA_SRC_BASE_HI_OFFSET, 0x10C4);
+	WREG32(mmMME_QM_CP_LDMA_TSIZE_OFFSET, 0x10C8);
+	WREG32(mmMME_QM_CP_LDMA_COMMIT_OFFSET, 0x10CC);
 
-	dev_dbg(hdev->dev, "u-boot firmware size == %lu\n", fw_size);
+	WREG32(mmMME_QM_CP_MSG_BASE0_ADDR_LO, mtr_base_lo);
+	WREG32(mmMME_QM_CP_MSG_BASE0_ADDR_HI, mtr_base_hi);
+	WREG32(mmMME_QM_CP_MSG_BASE1_ADDR_LO, so_base_lo);
+	WREG32(mmMME_QM_CP_MSG_BASE1_ADDR_HI, so_base_hi);
 
-	fw_data = (const u64 *) hdev->spl_fw->data;
-	dst = hdev->pcie_bar[SRAM_CFG_BAR_ID] + UBOOT_FW_OFFSET;
+	/* QMAN CQ has 8 cache lines */
+	WREG32(mmMME_QM_CQ_CFG1, 0x00080008);
 
-	if ((hdev->spl_fw->size % 8) != 0)
-		fw_size -= 8;
+	WREG32(mmMME_QM_GLBL_ERR_ADDR_LO, gic_base_lo);
+	WREG32(mmMME_QM_GLBL_ERR_ADDR_HI, gic_base_hi);
 
-	for (i = 0 ; i < fw_size ; i += 8, fw_data++, dst += 8) {
-		if (!(i & (0x80000 - 1)))
-			dev_dbg(hdev->dev,
-				"u-boot copied so far %lu out of %lu",
-				i, fw_size);
+	WREG32(mmMME_QM_GLBL_ERR_WDATA, GOYA_ASYNC_EVENT_ID_MME_QM);
 
-		writeq(*fw_data, dst);
-	}
+	WREG32(mmMME_QM_GLBL_ERR_CFG, QMAN_MME_ERR_MSG_EN);
 
-	if ((hdev->spl_fw->size % 8) != 0)
-		writel(*(const u32 *) fw_data, dst);
+	WREG32(mmMME_QM_GLBL_PROT, QMAN_MME_ERR_PROT);
 
-out:
-	release_firmware(hdev->spl_fw);
-	return rc;
+	WREG32(mmMME_QM_GLBL_CFG0, QMAN_MME_ENABLE);
 }
 
-/**
- * goya_push_linux_to_device - Push LINUX FW code to device
- *
- * @hdev: pointer to hl_device structure
- *
- * Copy LINXU fw code from firmware file to DDR BAR.
- * Returns 0 on success
- *
- */
-static int goya_push_linux_to_device(struct hl_device *hdev)
+static void goya_init_mme_cmdq(struct hl_device *hdev)
 {
-	char fw_name[200];
-	const u64 *fw_data;
-	void __iomem *dst;
-	size_t fw_size, i;
-	int rc;
+	u32 mtr_base_lo, mtr_base_hi;
+	u32 so_base_lo, so_base_hi;
+	u32 gic_base_lo, gic_base_hi;
+	u64 qman_base_addr;
 
-	snprintf(fw_name, sizeof(fw_name), "habanalabs/goya/goya-fit.itb");
+	mtr_base_lo = lower_32_bits(CFG_BASE + mmSYNC_MNGR_MON_PAY_ADDRL_0);
+	mtr_base_hi = upper_32_bits(CFG_BASE + mmSYNC_MNGR_MON_PAY_ADDRL_0);
+	so_base_lo = lower_32_bits(CFG_BASE + mmSYNC_MNGR_SOB_OBJ_0);
+	so_base_hi = upper_32_bits(CFG_BASE + mmSYNC_MNGR_SOB_OBJ_0);
 
-	rc = request_firmware(&hdev->spl_fw, fw_name, hdev->dev);
+	gic_base_lo =
+		lower_32_bits(CFG_BASE + mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR);
+	gic_base_hi =
+		upper_32_bits(CFG_BASE + mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR);
 
-	if (rc) {
-		dev_err(hdev->dev, "Failed to request Linux fw image\n");
-		goto out;
-	}
+	qman_base_addr = hdev->asic_prop.sram_base_address +
+				MME_QMAN_BASE_OFFSET;
 
-	fw_size = hdev->spl_fw->size;
-	if ((fw_size % 4) != 0) {
-		dev_err(hdev->dev, "illegal Linux firmware size %lu\n",
-			fw_size);
-		rc = -EINVAL;
-		goto out;
-	}
+	WREG32(mmMME_CMDQ_CP_MSG_BASE0_ADDR_LO, mtr_base_lo);
+	WREG32(mmMME_CMDQ_CP_MSG_BASE0_ADDR_HI, mtr_base_hi);
+	WREG32(mmMME_CMDQ_CP_MSG_BASE1_ADDR_LO,	so_base_lo);
+	WREG32(mmMME_CMDQ_CP_MSG_BASE1_ADDR_HI, so_base_hi);
 
-	dev_dbg(hdev->dev, "Linux firmware size == %lu\n", fw_size);
+	/* CMDQ CQ has 20 cache lines */
+	WREG32(mmMME_CMDQ_CQ_CFG1, 0x00140014);
 
-	fw_data = (const u64 *) hdev->spl_fw->data;
-	dst = hdev->pcie_bar[DDR_BAR_ID] + LINUX_FW_OFFSET;
+	WREG32(mmMME_CMDQ_GLBL_ERR_ADDR_LO, gic_base_lo);
+	WREG32(mmMME_CMDQ_GLBL_ERR_ADDR_HI, gic_base_hi);
 
-	if ((hdev->spl_fw->size % 8) != 0)
-		fw_size -= 8;
+	WREG32(mmMME_CMDQ_GLBL_ERR_WDATA, GOYA_ASYNC_EVENT_ID_MME_CMDQ);
 
-	for (i = 0 ; i < fw_size ; i += 8, fw_data++, dst += 8) {
-		if (!(i & (0x80000 - 1))) {
-			dev_dbg(hdev->dev,
-				"Linux copied so far %lu out of %lu",
-				i, fw_size);
-			usleep_range(20, 100);
-		}
-		writeq(*fw_data, dst);
-	}
+	WREG32(mmMME_CMDQ_GLBL_ERR_CFG, CMDQ_MME_ERR_MSG_EN);
 
-	if ((hdev->spl_fw->size % 8) != 0)
-		writel(*(const u32 *) fw_data, dst);
+	WREG32(mmMME_CMDQ_GLBL_PROT, CMDQ_MME_ERR_PROT);
 
-out:
-	release_firmware(hdev->spl_fw);
-	return rc;
+	WREG32(mmMME_CMDQ_GLBL_CFG0, CMDQ_MME_ENABLE);
 }
 
-static int goya_pldm_init_cpu(struct hl_device *hdev)
+static void goya_init_mme_qmans(struct hl_device *hdev)
 {
-	u32 val, unit_rst_val;
-	int rc;
+	struct goya_device *goya = hdev->asic_specific;
+	u32 so_base_lo, so_base_hi;
 
-	/* Must initialize SRAM scrambler before pushing u-boot to SRAM */
-	goya_init_golden_registers(hdev);
+	if (goya->hw_cap_initialized & HW_CAP_MME)
+		return;
 
-	/* Put ARM cores into reset */
-	WREG32(mmCPU_CA53_CFG_ARM_RST_CONTROL, CPU_RESET_ASSERT);
-	val = RREG32(mmCPU_CA53_CFG_ARM_RST_CONTROL);
+	so_base_lo = lower_32_bits(CFG_BASE + mmSYNC_MNGR_SOB_OBJ_0);
+	so_base_hi = upper_32_bits(CFG_BASE + mmSYNC_MNGR_SOB_OBJ_0);
 
-	/* Reset the CA53 MACRO */
-	unit_rst_val = RREG32(mmPSOC_GLOBAL_CONF_UNIT_RST_N);
-	WREG32(mmPSOC_GLOBAL_CONF_UNIT_RST_N, CA53_RESET);
-	val = RREG32(mmPSOC_GLOBAL_CONF_UNIT_RST_N);
-	WREG32(mmPSOC_GLOBAL_CONF_UNIT_RST_N, unit_rst_val);
-	val = RREG32(mmPSOC_GLOBAL_CONF_UNIT_RST_N);
+	WREG32(mmMME_SM_BASE_ADDRESS_LOW, so_base_lo);
+	WREG32(mmMME_SM_BASE_ADDRESS_HIGH, so_base_hi);
 
-	rc = goya_push_uboot_to_device(hdev);
-	if (rc)
-		return rc;
+	goya_init_mme_qman(hdev);
+	goya_init_mme_cmdq(hdev);
 
-	rc = goya_push_linux_to_device(hdev);
-	if (rc)
-		return rc;
+	goya->hw_cap_initialized |= HW_CAP_MME;
+}
+
+static void goya_init_tpc_qman(struct hl_device *hdev, u32 base_off, int tpc_id)
+{
+	u32 mtr_base_lo, mtr_base_hi;
+	u32 so_base_lo, so_base_hi;
+	u32 gic_base_lo, gic_base_hi;
+	u64 qman_base_addr;
+	u32 reg_off = tpc_id * (mmTPC1_QM_PQ_PI - mmTPC0_QM_PQ_PI);
+
+	mtr_base_lo = lower_32_bits(CFG_BASE + mmSYNC_MNGR_MON_PAY_ADDRL_0);
+	mtr_base_hi = upper_32_bits(CFG_BASE + mmSYNC_MNGR_MON_PAY_ADDRL_0);
+	so_base_lo = lower_32_bits(CFG_BASE + mmSYNC_MNGR_SOB_OBJ_0);
+	so_base_hi = upper_32_bits(CFG_BASE + mmSYNC_MNGR_SOB_OBJ_0);
+
+	gic_base_lo =
+		lower_32_bits(CFG_BASE + mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR);
+	gic_base_hi =
+		upper_32_bits(CFG_BASE + mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR);
+
+	qman_base_addr = hdev->asic_prop.sram_base_address + base_off;
+
+	WREG32(mmTPC0_QM_PQ_BASE_LO + reg_off, lower_32_bits(qman_base_addr));
+	WREG32(mmTPC0_QM_PQ_BASE_HI + reg_off, upper_32_bits(qman_base_addr));
+	WREG32(mmTPC0_QM_PQ_SIZE + reg_off, ilog2(TPC_QMAN_LENGTH));
+	WREG32(mmTPC0_QM_PQ_PI + reg_off, 0);
+	WREG32(mmTPC0_QM_PQ_CI + reg_off, 0);
+	WREG32(mmTPC0_QM_CP_LDMA_SRC_BASE_LO_OFFSET + reg_off, 0x10C0);
+	WREG32(mmTPC0_QM_CP_LDMA_SRC_BASE_HI_OFFSET + reg_off, 0x10C4);
+	WREG32(mmTPC0_QM_CP_LDMA_TSIZE_OFFSET + reg_off, 0x10C8);
+	WREG32(mmTPC0_QM_CP_LDMA_COMMIT_OFFSET + reg_off, 0x10CC);
+
+	WREG32(mmTPC0_QM_CP_MSG_BASE0_ADDR_LO + reg_off, mtr_base_lo);
+	WREG32(mmTPC0_QM_CP_MSG_BASE0_ADDR_HI + reg_off, mtr_base_hi);
+	WREG32(mmTPC0_QM_CP_MSG_BASE1_ADDR_LO + reg_off, so_base_lo);
+	WREG32(mmTPC0_QM_CP_MSG_BASE1_ADDR_HI + reg_off, so_base_hi);
+
+	WREG32(mmTPC0_QM_CQ_CFG1 + reg_off, 0x00080008);
+
+	WREG32(mmTPC0_QM_GLBL_ERR_ADDR_LO + reg_off, gic_base_lo);
+	WREG32(mmTPC0_QM_GLBL_ERR_ADDR_HI + reg_off, gic_base_hi);
+
+	WREG32(mmTPC0_QM_GLBL_ERR_WDATA + reg_off,
+			GOYA_ASYNC_EVENT_ID_TPC0_QM + tpc_id);
+
+	WREG32(mmTPC0_QM_GLBL_ERR_CFG + reg_off, QMAN_TPC_ERR_MSG_EN);
+
+	WREG32(mmTPC0_QM_GLBL_PROT + reg_off, QMAN_TPC_ERR_PROT);
+
+	WREG32(mmTPC0_QM_GLBL_CFG0 + reg_off, QMAN_TPC_ENABLE);
+}
+
+static void goya_init_tpc_cmdq(struct hl_device *hdev, int tpc_id)
+{
+	u32 mtr_base_lo, mtr_base_hi;
+	u32 so_base_lo, so_base_hi;
+	u32 gic_base_lo, gic_base_hi;
+	u32 reg_off = tpc_id * (mmTPC1_CMDQ_CQ_CFG1 - mmTPC0_CMDQ_CQ_CFG1);
+
+	mtr_base_lo = lower_32_bits(CFG_BASE + mmSYNC_MNGR_MON_PAY_ADDRL_0);
+	mtr_base_hi = upper_32_bits(CFG_BASE + mmSYNC_MNGR_MON_PAY_ADDRL_0);
+	so_base_lo = lower_32_bits(CFG_BASE + mmSYNC_MNGR_SOB_OBJ_0);
+	so_base_hi = upper_32_bits(CFG_BASE + mmSYNC_MNGR_SOB_OBJ_0);
+
+	gic_base_lo =
+		lower_32_bits(CFG_BASE + mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR);
+	gic_base_hi =
+		upper_32_bits(CFG_BASE + mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR);
+
+	WREG32(mmTPC0_CMDQ_CP_MSG_BASE0_ADDR_LO + reg_off, mtr_base_lo);
+	WREG32(mmTPC0_CMDQ_CP_MSG_BASE0_ADDR_HI + reg_off, mtr_base_hi);
+	WREG32(mmTPC0_CMDQ_CP_MSG_BASE1_ADDR_LO + reg_off, so_base_lo);
+	WREG32(mmTPC0_CMDQ_CP_MSG_BASE1_ADDR_HI + reg_off, so_base_hi);
+
+	WREG32(mmTPC0_CMDQ_CQ_CFG1 + reg_off, 0x00140014);
+
+	WREG32(mmTPC0_CMDQ_GLBL_ERR_ADDR_LO + reg_off, gic_base_lo);
+	WREG32(mmTPC0_CMDQ_GLBL_ERR_ADDR_HI + reg_off, gic_base_hi);
+
+	WREG32(mmTPC0_CMDQ_GLBL_ERR_WDATA + reg_off,
+			GOYA_ASYNC_EVENT_ID_TPC0_CMDQ + tpc_id);
+
+	WREG32(mmTPC0_CMDQ_GLBL_ERR_CFG + reg_off, CMDQ_TPC_ERR_MSG_EN);
+
+	WREG32(mmTPC0_CMDQ_GLBL_PROT + reg_off, CMDQ_TPC_ERR_PROT);
+
+	WREG32(mmTPC0_CMDQ_GLBL_CFG0 + reg_off, CMDQ_TPC_ENABLE);
+}
+
+static void goya_init_tpc_qmans(struct hl_device *hdev)
+{
+	struct goya_device *goya = hdev->asic_specific;
+	u32 so_base_lo, so_base_hi;
+	u32 cfg_off = mmTPC1_CFG_SM_BASE_ADDRESS_LOW -
+			mmTPC0_CFG_SM_BASE_ADDRESS_LOW;
+	int i;
+
+	if (goya->hw_cap_initialized & HW_CAP_TPC)
+		return;
+
+	so_base_lo = lower_32_bits(CFG_BASE + mmSYNC_MNGR_SOB_OBJ_0);
+	so_base_hi = upper_32_bits(CFG_BASE + mmSYNC_MNGR_SOB_OBJ_0);
+
+	for (i = 0 ; i < TPC_MAX_NUM ; i++) {
+		WREG32(mmTPC0_CFG_SM_BASE_ADDRESS_LOW + i * cfg_off,
+				so_base_lo);
+		WREG32(mmTPC0_CFG_SM_BASE_ADDRESS_HIGH + i * cfg_off,
+				so_base_hi);
+	}
+
+	goya_init_tpc_qman(hdev, TPC0_QMAN_BASE_OFFSET, 0);
+	goya_init_tpc_qman(hdev, TPC1_QMAN_BASE_OFFSET, 1);
+	goya_init_tpc_qman(hdev, TPC2_QMAN_BASE_OFFSET, 2);
+	goya_init_tpc_qman(hdev, TPC3_QMAN_BASE_OFFSET, 3);
+	goya_init_tpc_qman(hdev, TPC4_QMAN_BASE_OFFSET, 4);
+	goya_init_tpc_qman(hdev, TPC5_QMAN_BASE_OFFSET, 5);
+	goya_init_tpc_qman(hdev, TPC6_QMAN_BASE_OFFSET, 6);
+	goya_init_tpc_qman(hdev, TPC7_QMAN_BASE_OFFSET, 7);
+
+	for (i = 0 ; i < TPC_MAX_NUM ; i++)
+		goya_init_tpc_cmdq(hdev, i);
+
+	goya->hw_cap_initialized |= HW_CAP_TPC;
+}
+
+/**
+ * goya_disable_internal_queues - Disable internal queues
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ */
+static void goya_disable_internal_queues(struct hl_device *hdev)
+{
+	WREG32(mmMME_QM_GLBL_CFG0, 0);
+	WREG32(mmMME_CMDQ_GLBL_CFG0, 0);
+
+	WREG32(mmTPC0_QM_GLBL_CFG0, 0);
+	WREG32(mmTPC0_CMDQ_GLBL_CFG0, 0);
+
+	WREG32(mmTPC1_QM_GLBL_CFG0, 0);
+	WREG32(mmTPC1_CMDQ_GLBL_CFG0, 0);
+
+	WREG32(mmTPC2_QM_GLBL_CFG0, 0);
+	WREG32(mmTPC2_CMDQ_GLBL_CFG0, 0);
+
+	WREG32(mmTPC3_QM_GLBL_CFG0, 0);
+	WREG32(mmTPC3_CMDQ_GLBL_CFG0, 0);
+
+	WREG32(mmTPC4_QM_GLBL_CFG0, 0);
+	WREG32(mmTPC4_CMDQ_GLBL_CFG0, 0);
+
+	WREG32(mmTPC5_QM_GLBL_CFG0, 0);
+	WREG32(mmTPC5_CMDQ_GLBL_CFG0, 0);
+
+	WREG32(mmTPC6_QM_GLBL_CFG0, 0);
+	WREG32(mmTPC6_CMDQ_GLBL_CFG0, 0);
+
+	WREG32(mmTPC7_QM_GLBL_CFG0, 0);
+	WREG32(mmTPC7_CMDQ_GLBL_CFG0, 0);
+}
+
+/**
+ * goya_stop_internal_queues - Stop internal queues
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ * Returns 0 on success
+ *
+ */
+static int goya_stop_internal_queues(struct hl_device *hdev)
+{
+	int rc, retval = 0;
+
+	rc = goya_stop_queue(hdev,
+			mmMME_QM_GLBL_CFG1,
+			mmMME_QM_CP_STS,
+			mmMME_QM_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop MME QMAN\n");
+		retval = -EIO;
+	}

drivers/misc/habanalabs/goya/goya.c static void goya_init_golden_registers(struct hl_device *hdev) · line 2589

Quoted 10 lines
drivers/misc/habanalabs/goya/goya.c +10 -0
+
+	rc = goya_stop_queue(hdev,
+			mmMME_CMDQ_GLBL_CFG1,
+			mmMME_CMDQ_CP_STS,
+			mmMME_CMDQ_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop MME CMDQ\n");
+		retval = -EIO;
+	}

If I understand correctly, the queues can be and should be stopped independently and failure to stop one of them wouldn't prevent stopping the others.
If that's the case a comment explaining that would be nice.

Quoted 656 lines
drivers/misc/habanalabs/goya/goya.c +599 -4
+	rc = goya_stop_queue(hdev,
+			mmTPC0_QM_GLBL_CFG1,
+			mmTPC0_QM_CP_STS,
+			mmTPC0_QM_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 0 QMAN\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC0_CMDQ_GLBL_CFG1,
+			mmTPC0_CMDQ_CP_STS,
+			mmTPC0_CMDQ_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 0 CMDQ\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC1_QM_GLBL_CFG1,
+			mmTPC1_QM_CP_STS,
+			mmTPC1_QM_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 1 QMAN\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC1_CMDQ_GLBL_CFG1,
+			mmTPC1_CMDQ_CP_STS,
+			mmTPC1_CMDQ_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 1 CMDQ\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC2_QM_GLBL_CFG1,
+			mmTPC2_QM_CP_STS,
+			mmTPC2_QM_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 2 QMAN\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC2_CMDQ_GLBL_CFG1,
+			mmTPC2_CMDQ_CP_STS,
+			mmTPC2_CMDQ_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 2 CMDQ\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC3_QM_GLBL_CFG1,
+			mmTPC3_QM_CP_STS,
+			mmTPC3_QM_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 3 QMAN\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC3_CMDQ_GLBL_CFG1,
+			mmTPC3_CMDQ_CP_STS,
+			mmTPC3_CMDQ_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 3 CMDQ\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC4_QM_GLBL_CFG1,
+			mmTPC4_QM_CP_STS,
+			mmTPC4_QM_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 4 QMAN\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC4_CMDQ_GLBL_CFG1,
+			mmTPC4_CMDQ_CP_STS,
+			mmTPC4_CMDQ_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 4 CMDQ\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC5_QM_GLBL_CFG1,
+			mmTPC5_QM_CP_STS,
+			mmTPC5_QM_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 5 QMAN\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC5_CMDQ_GLBL_CFG1,
+			mmTPC5_CMDQ_CP_STS,
+			mmTPC5_CMDQ_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 5 CMDQ\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC6_QM_GLBL_CFG1,
+			mmTPC6_QM_CP_STS,
+			mmTPC6_QM_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 6 QMAN\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC6_CMDQ_GLBL_CFG1,
+			mmTPC6_CMDQ_CP_STS,
+			mmTPC6_CMDQ_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 6 CMDQ\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC7_QM_GLBL_CFG1,
+			mmTPC7_QM_CP_STS,
+			mmTPC7_QM_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 7 QMAN\n");
+		retval = -EIO;
+	}
+
+	rc = goya_stop_queue(hdev,
+			mmTPC7_CMDQ_GLBL_CFG1,
+			mmTPC7_CMDQ_CP_STS,
+			mmTPC7_CMDQ_GLBL_STS0);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop TPC 7 CMDQ\n");
+		retval = -EIO;
+	}
+
+	return rc;
+}
+
+static void goya_resume_internal_queues(struct hl_device *hdev)
+{
+	WREG32(mmMME_QM_GLBL_CFG1, 0);
+	WREG32(mmMME_CMDQ_GLBL_CFG1, 0);
+
+	WREG32(mmTPC0_QM_GLBL_CFG1, 0);
+	WREG32(mmTPC0_CMDQ_GLBL_CFG1, 0);
+
+	WREG32(mmTPC1_QM_GLBL_CFG1, 0);
+	WREG32(mmTPC1_CMDQ_GLBL_CFG1, 0);
+
+	WREG32(mmTPC2_QM_GLBL_CFG1, 0);
+	WREG32(mmTPC2_CMDQ_GLBL_CFG1, 0);
+
+	WREG32(mmTPC3_QM_GLBL_CFG1, 0);
+	WREG32(mmTPC3_CMDQ_GLBL_CFG1, 0);
+
+	WREG32(mmTPC4_QM_GLBL_CFG1, 0);
+	WREG32(mmTPC4_CMDQ_GLBL_CFG1, 0);
+
+	WREG32(mmTPC5_QM_GLBL_CFG1, 0);
+	WREG32(mmTPC5_CMDQ_GLBL_CFG1, 0);
+
+	WREG32(mmTPC6_QM_GLBL_CFG1, 0);
+	WREG32(mmTPC6_CMDQ_GLBL_CFG1, 0);
+
+	WREG32(mmTPC7_QM_GLBL_CFG1, 0);
+	WREG32(mmTPC7_CMDQ_GLBL_CFG1, 0);
+}
+
+
+/**
+ * goya_push_uboot_to_device - Push u-boot FW code to device
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ * Copy u-boot fw code from firmware file to SRAM BAR.
+ * Returns 0 on success
+ *
+ */
+static int goya_push_uboot_to_device(struct hl_device *hdev)
+{
+	char fw_name[200];
+	const u64 *fw_data;
+	void __iomem *dst;
+	size_t fw_size, i;
+	int rc;
+
+	snprintf(fw_name, sizeof(fw_name), "habanalabs/goya/goya-u-boot.bin");
+
+	rc = request_firmware(&hdev->spl_fw, fw_name, hdev->dev);
+
+	if (rc) {
+		dev_err(hdev->dev, "Failed to request u-boot fw image\n");
+		goto out;
+	}
+
+	fw_size = hdev->spl_fw->size;
+	if ((fw_size % 4) != 0) {
+		dev_err(hdev->dev, "illegal u-boot firmware size %lu\n",
+			fw_size);
+		rc = -EINVAL;
+		goto out;
+	}
+
+	dev_dbg(hdev->dev, "u-boot firmware size == %lu\n", fw_size);
+
+	fw_data = (const u64 *) hdev->spl_fw->data;
+	dst = hdev->pcie_bar[SRAM_CFG_BAR_ID] + UBOOT_FW_OFFSET;
+
+	if ((hdev->spl_fw->size % 8) != 0)
+		fw_size -= 8;
+
+	for (i = 0 ; i < fw_size ; i += 8, fw_data++, dst += 8) {
+		if (!(i & (0x80000 - 1)))
+			dev_dbg(hdev->dev,
+				"u-boot copied so far %lu out of %lu",
+				i, fw_size);
+
+		writeq(*fw_data, dst);
+	}
+
+	if ((hdev->spl_fw->size % 8) != 0)
+		writel(*(const u32 *) fw_data, dst);
+
+out:
+	release_firmware(hdev->spl_fw);
+	return rc;
+}
+
+/**
+ * goya_push_linux_to_device - Push LINUX FW code to device
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ * Copy LINXU fw code from firmware file to DDR BAR.
+ * Returns 0 on success
+ *
+ */
+static int goya_push_linux_to_device(struct hl_device *hdev)
+{
+	char fw_name[200];
+	const u64 *fw_data;
+	void __iomem *dst;
+	size_t fw_size, i;
+	int rc;
+
+	snprintf(fw_name, sizeof(fw_name), "habanalabs/goya/goya-fit.itb");
+
+	rc = request_firmware(&hdev->spl_fw, fw_name, hdev->dev);
+
+	if (rc) {
+		dev_err(hdev->dev, "Failed to request Linux fw image\n");
+		goto out;
+	}
+
+	fw_size = hdev->spl_fw->size;
+	if ((fw_size % 4) != 0) {
+		dev_err(hdev->dev, "illegal Linux firmware size %lu\n",
+			fw_size);
+		rc = -EINVAL;
+		goto out;
+	}
+
+	dev_dbg(hdev->dev, "Linux firmware size == %lu\n", fw_size);
+
+	fw_data = (const u64 *) hdev->spl_fw->data;
+	dst = hdev->pcie_bar[DDR_BAR_ID] + LINUX_FW_OFFSET;
+
+	if ((hdev->spl_fw->size % 8) != 0)
+		fw_size -= 8;
+
+	for (i = 0 ; i < fw_size ; i += 8, fw_data++, dst += 8) {
+		if (!(i & (0x80000 - 1))) {
+			dev_dbg(hdev->dev,
+				"Linux copied so far %lu out of %lu",
+				i, fw_size);
+			usleep_range(20, 100);
+		}
+		writeq(*fw_data, dst);
+	}
+
+	if ((hdev->spl_fw->size % 8) != 0)
+		writel(*(const u32 *) fw_data, dst);
+
+out:
+	release_firmware(hdev->spl_fw);
+	return rc;
+}
+
+static int goya_pldm_init_cpu(struct hl_device *hdev)
+{
+	u32 val, unit_rst_val;
+	int rc;
+
+	/* Must initialize SRAM scrambler before pushing u-boot to SRAM */
+	goya_init_golden_registers(hdev);
+
+	/* Put ARM cores into reset */
+	WREG32(mmCPU_CA53_CFG_ARM_RST_CONTROL, CPU_RESET_ASSERT);
+	val = RREG32(mmCPU_CA53_CFG_ARM_RST_CONTROL);
+
+	/* Reset the CA53 MACRO */
+	unit_rst_val = RREG32(mmPSOC_GLOBAL_CONF_UNIT_RST_N);
+	WREG32(mmPSOC_GLOBAL_CONF_UNIT_RST_N, CA53_RESET);
+	val = RREG32(mmPSOC_GLOBAL_CONF_UNIT_RST_N);
+	WREG32(mmPSOC_GLOBAL_CONF_UNIT_RST_N, unit_rst_val);
+	val = RREG32(mmPSOC_GLOBAL_CONF_UNIT_RST_N);
+
+	rc = goya_push_uboot_to_device(hdev);
+	if (rc)
+		return rc;
+
+	rc = goya_push_linux_to_device(hdev);
+	if (rc)
+		return rc;
 
 	WREG32(mmPSOC_GLOBAL_CONF_UBOOT_MAGIC, KMD_MSG_FIT_RDY);
 	WREG32(mmPSOC_GLOBAL_CONF_WARM_REBOOT, CPU_BOOT_STATUS_NA);
@@ -2339,6 +3160,19 @@ static int goya_hw_init(struct hl_device *hdev)
 
 	goya_init_security(hdev);
 
+	goya_init_dma_qmans(hdev);
+
+	goya_init_mme_qmans(hdev);
+
+	goya_init_tpc_qmans(hdev);
+
+	rc = goya_init_cpu_queues(hdev);
+	if (rc) {
+		dev_err(hdev->dev, "failed to initialize CPU H/W queues %d\n",
+			rc);
+		goto disable_queues;
+	}
+
 	/* CPU initialization is finished, we can now move to 48 bit DMA mask */
 	rc = pci_set_dma_mask(hdev->pdev, DMA_BIT_MASK(48));
 	if (rc) {
@@ -2347,7 +3181,7 @@ static int goya_hw_init(struct hl_device *hdev)
 		if (rc) {
 			dev_err(hdev->dev,
 				"Unable to set pci dma mask to 32 bits\n");
-			return rc;
+			goto disable_pci_access;
 		}
 	}
 
@@ -2359,7 +3193,7 @@ static int goya_hw_init(struct hl_device *hdev)
 		if (rc) {
 			dev_err(hdev->dev,
 				"Unable to set pci consistent dma mask to 32 bits\n");
-			return rc;
+			goto disable_pci_access;
 		}
 	}
 
@@ -2367,6 +3201,14 @@ static int goya_hw_init(struct hl_device *hdev)
 	val = RREG32(mmPCIE_DBI_DEVICE_ID_VENDOR_ID_REG);
 
 	return 0;
+
+disable_pci_access:
+	goya_send_pci_access_msg(hdev, ARMCP_PACKET_DISABLE_PCI_ACCESS);
+disable_queues:
+	goya_disable_internal_queues(hdev);
+	goya_disable_external_queues(hdev);
+
+	return rc;
 }
 
 /**
@@ -2473,12 +3315,40 @@ static void goya_hw_fini(struct hl_device *hdev, bool hard_reset)
 
 int goya_suspend(struct hl_device *hdev)
 {
-	return 0;
+	int rc;
+
+	rc = goya_stop_internal_queues(hdev);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop internal queues\n");
+		return rc;
+	}
+
+	rc = goya_stop_external_queues(hdev);
+
+	if (rc) {
+		dev_err(hdev->dev, "failed to stop external queues\n");
+		return rc;
+	}
+
+	rc = goya_send_pci_access_msg(hdev, ARMCP_PACKET_DISABLE_PCI_ACCESS);
+	if (rc)
+		dev_err(hdev->dev, "Failed to disable PCI access from CPU\n");
+
+	return rc;
 }
 
 int goya_resume(struct hl_device *hdev)
 {
-	return 0;
+	int rc;
+
+	goya_resume_external_queues(hdev);
+	goya_resume_internal_queues(hdev);
+
+	rc = goya_send_pci_access_msg(hdev, ARMCP_PACKET_ENABLE_PCI_ACCESS);
+	if (rc)
+		dev_err(hdev->dev, "Failed to enable PCI access from CPU\n");
+	return rc;
 }
 
 int goya_mmap(struct hl_fpriv *hpriv, struct vm_area_struct *vma)
@@ -2502,6 +3372,104 @@ int goya_cb_mmap(struct hl_device *hdev, struct vm_area_struct *vma,
 	return rc;
 }
 
+void goya_ring_doorbell(struct hl_device *hdev, u32 hw_queue_id, u32 pi)
+{
+	u32 db_reg_offset, db_value;
+	bool invalid_queue = false;
+
+	switch (hw_queue_id) {
+	case GOYA_QUEUE_ID_DMA_0:
+		db_reg_offset = mmDMA_QM_0_PQ_PI;
+		break;
+
+	case GOYA_QUEUE_ID_DMA_1:
+		db_reg_offset = mmDMA_QM_1_PQ_PI;
+		break;
+
+	case GOYA_QUEUE_ID_DMA_2:
+		db_reg_offset = mmDMA_QM_2_PQ_PI;
+		break;
+
+	case GOYA_QUEUE_ID_DMA_3:
+		db_reg_offset = mmDMA_QM_3_PQ_PI;
+		break;
+
+	case GOYA_QUEUE_ID_DMA_4:
+		db_reg_offset = mmDMA_QM_4_PQ_PI;
+		break;
+
+	case GOYA_QUEUE_ID_CPU_PQ:
+		if (hdev->cpu_queues_enable)
+			db_reg_offset = mmCPU_IF_PF_PQ_PI;
+		else
+			invalid_queue = true;
+		break;
+
+	case GOYA_QUEUE_ID_MME:
+		db_reg_offset = mmMME_QM_PQ_PI;
+		break;
+
+	case GOYA_QUEUE_ID_TPC0:
+		db_reg_offset = mmTPC0_QM_PQ_PI;
+		break;
+
+	case GOYA_QUEUE_ID_TPC1:
+		db_reg_offset = mmTPC1_QM_PQ_PI;
+		break;
+
+	case GOYA_QUEUE_ID_TPC2:
+		db_reg_offset = mmTPC2_QM_PQ_PI;
+		break;
+
+	case GOYA_QUEUE_ID_TPC3:
+		db_reg_offset = mmTPC3_QM_PQ_PI;
+		break;
+
+	case GOYA_QUEUE_ID_TPC4:
+		db_reg_offset = mmTPC4_QM_PQ_PI;
+		break;
+
+	case GOYA_QUEUE_ID_TPC5:
+		db_reg_offset = mmTPC5_QM_PQ_PI;
+		break;
+
+	case GOYA_QUEUE_ID_TPC6:
+		db_reg_offset = mmTPC6_QM_PQ_PI;
+		break;
+
+	case GOYA_QUEUE_ID_TPC7:
+		db_reg_offset = mmTPC7_QM_PQ_PI;
+		break;
+
+	default:
+		invalid_queue = true;
+	}
+
+	if (invalid_queue) {
+		/* Should never get here */
+		dev_err(hdev->dev, "h/w queue %d is invalid. Can't set pi\n",
+			hw_queue_id);
+		return;
+	}
+
+	db_value = pi;
+
+	if (hdev->ifh)
+		return;
+
+	/* ring the doorbell */
+	WREG32(db_reg_offset, db_value);
+
+	if (hw_queue_id == GOYA_QUEUE_ID_CPU_PQ)
+		WREG32(mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR,
+				GOYA_ASYNC_EVENT_ID_PI_UPDATE);
+}
+
+void goya_flush_pq_write(struct hl_device *hdev, u64 *pq, u64 exp_val)
+{
+	/* Not needed in Goya */
+}
+
 void *goya_dma_alloc_coherent(struct hl_device *hdev, size_t size,
 					dma_addr_t *dma_handle, gfp_t flags)
 {
@@ -2514,6 +3482,311 @@ void goya_dma_free_coherent(struct hl_device *hdev, size_t size, void *cpu_addr,
 	dma_free_coherent(&hdev->pdev->dev, size, cpu_addr, dma_handle);
 }
 
+void *goya_get_int_queue_base(struct hl_device *hdev, u32 queue_id,
+				dma_addr_t *dma_handle,	u16 *queue_len)
+{
+	void *base;
+	u32 offset;
+
+	*dma_handle = hdev->asic_prop.sram_base_address;
+
+	base = hdev->pcie_bar[SRAM_CFG_BAR_ID];
+
+	switch (queue_id) {
+	case GOYA_QUEUE_ID_MME:
+		offset = MME_QMAN_BASE_OFFSET;
+		*queue_len = MME_QMAN_LENGTH;
+		break;
+	case GOYA_QUEUE_ID_TPC0:
+		offset = TPC0_QMAN_BASE_OFFSET;
+		*queue_len = TPC_QMAN_LENGTH;
+		break;
+	case GOYA_QUEUE_ID_TPC1:
+		offset = TPC1_QMAN_BASE_OFFSET;
+		*queue_len = TPC_QMAN_LENGTH;
+		break;
+	case GOYA_QUEUE_ID_TPC2:
+		offset = TPC2_QMAN_BASE_OFFSET;
+		*queue_len = TPC_QMAN_LENGTH;
+		break;
+	case GOYA_QUEUE_ID_TPC3:
+		offset = TPC3_QMAN_BASE_OFFSET;
+		*queue_len = TPC_QMAN_LENGTH;
+		break;
+	case GOYA_QUEUE_ID_TPC4:
+		offset = TPC4_QMAN_BASE_OFFSET;
+		*queue_len = TPC_QMAN_LENGTH;
+		break;
+	case GOYA_QUEUE_ID_TPC5:
+		offset = TPC5_QMAN_BASE_OFFSET;
+		*queue_len = TPC_QMAN_LENGTH;
+		break;
+	case GOYA_QUEUE_ID_TPC6:
+		offset = TPC6_QMAN_BASE_OFFSET;
+		*queue_len = TPC_QMAN_LENGTH;
+		break;
+	case GOYA_QUEUE_ID_TPC7:
+		offset = TPC7_QMAN_BASE_OFFSET;
+		*queue_len = TPC_QMAN_LENGTH;
+		break;
+	default:
+		dev_err(hdev->dev, "Got invalid queue id %d\n", queue_id);
+		return NULL;
+	}
+
+	base += offset;
+	*dma_handle += offset;
+
+	return base;
+}
+
+int goya_send_cpu_message(struct hl_device *hdev, u32 *msg, u16 len,
+				u32 timeout, long *result)
+{
+	struct goya_device *goya = hdev->asic_specific;
+	struct armcp_packet *pkt;
+	dma_addr_t pkt_dma_addr;
+	u32 tmp;
+	int rc = 0;
+
+	if (!(goya->hw_cap_initialized & HW_CAP_CPU_Q)) {
+		if (result)
+			*result = 0;
+		return 0;
+	}
+
+	if (len > CPU_CB_SIZE) {
+		dev_err(hdev->dev, "Invalid CPU message size of %d bytes\n",
+			len);
+		return -ENOMEM;
+	}
+
+	pkt = hdev->asic_funcs->cpu_accessible_dma_pool_alloc(hdev, len,
+								&pkt_dma_addr);
+	if (!pkt) {
+		dev_err(hdev->dev,
+			"Failed to allocate DMA memory for packet to CPU\n");
+		return -ENOMEM;
+	}
+
+	memcpy(pkt, msg, len);
+
+	mutex_lock(&hdev->send_cpu_message_lock);
+
+	if (hdev->disabled)
+		goto out;
+
+	rc = hl_hw_queue_send_cb_no_cmpl(hdev, GOYA_QUEUE_ID_CPU_PQ, len,
+			pkt_dma_addr);
+	if (rc) {
+		dev_err(hdev->dev, "Failed to send CB on CPU PQ (%d)\n", rc);
+		goto out;
+	}
+
+	rc = hl_poll_timeout_memory(hdev, (u64) &pkt->fence, timeout, &tmp);
+
+	hl_hw_queue_inc_ci_kernel(hdev, GOYA_QUEUE_ID_CPU_PQ);
+
+	if (rc == -ETIMEDOUT) {
+		dev_err(hdev->dev,
+			"Timeout while waiting for CPU packet fence\n");
+		goto out;

drivers/misc/habanalabs/goya/goya.c void goya_dma_free_coherent(struct hl_device *hdev, size_t size, void *cpu_addr, · line 3603

Quoted 10 lines
drivers/misc/habanalabs/goya/goya.c +10 -0
+	}
+
+	if (tmp == ARMCP_PACKET_FENCE_VAL) {
+		if (pkt->rc) {
+			dev_err(hdev->dev,
+				"failed to execute CPU packet, rc: %d\n",
+					pkt->rc);
+			rc = -EINVAL;
+		} else if (result) {
+			*result = pkt->result;

For some error cases above the *result is not initialized.

Quoted 1,633 lines
drivers/misc/habanalabs/goya/goya.c +197 -0
+		}
+	} else {
+		dev_err(hdev->dev, "CPU packet wrong fence value\n");
+		rc = -EINVAL;
+	}
+
+out:
+	mutex_unlock(&hdev->send_cpu_message_lock);
+
+	hdev->asic_funcs->cpu_accessible_dma_pool_free(hdev, len, pkt);
+
+	return rc;
+}
+
+int goya_test_queue(struct hl_device *hdev, u32 hw_queue_id)
+{
+	struct packet_msg_prot *fence_pkt;
+	dma_addr_t pkt_dma_addr;
+	u32 fence_val, tmp;
+	dma_addr_t fence_dma_addr;
+	u32 *fence_ptr;
+	int rc;
+
+	fence_val = GOYA_QMAN0_FENCE_VAL;
+
+	fence_ptr = hdev->asic_funcs->dma_pool_zalloc(hdev, 4, GFP_KERNEL,
+							&fence_dma_addr);
+	if (!fence_ptr) {
+		dev_err(hdev->dev,
+			"Failed to allocate memory for queue testing\n");
+		return -ENOMEM;
+	}
+
+	*fence_ptr = 0;
+
+	fence_pkt = hdev->asic_funcs->dma_pool_zalloc(hdev,
+					sizeof(struct packet_msg_prot),
+					GFP_KERNEL, &pkt_dma_addr);
+	if (!fence_pkt) {
+		dev_err(hdev->dev,
+			"Failed to allocate packet for queue testing\n");
+		rc = -ENOMEM;
+		goto free_fence_ptr;
+	}
+
+	fence_pkt->opcode = PACKET_MSG_PROT;
+	fence_pkt->value = fence_val;
+	fence_pkt->addr = fence_dma_addr +
+				hdev->asic_prop.host_phys_base_address;
+
+	rc = hl_hw_queue_send_cb_no_cmpl(hdev, hw_queue_id,
+					sizeof(struct packet_msg_prot),
+					pkt_dma_addr);
+	if (rc) {
+		dev_err(hdev->dev,
+			"Failed to send fence packet\n");
+		goto free_pkt;
+	}
+
+	rc = hl_poll_timeout_memory(hdev, (u64) fence_ptr,
+					GOYA_TEST_QUEUE_WAIT_USEC, &tmp);
+
+	hl_hw_queue_inc_ci_kernel(hdev, hw_queue_id);
+
+	if ((!rc) && (tmp == fence_val)) {
+		dev_info(hdev->dev,
+			"queue test on H/W queue %d succeeded\n",
+			hw_queue_id);
+	} else {
+		dev_err(hdev->dev,
+			"H/W queue %d test failed (scratch(0x%08llX) == 0x%08X)\n",
+			hw_queue_id, fence_dma_addr, tmp);
+		rc = -EINVAL;
+	}
+
+free_pkt:
+	hdev->asic_funcs->dma_pool_free(hdev, (void *) fence_pkt,
+					pkt_dma_addr);
+free_fence_ptr:
+	hdev->asic_funcs->dma_pool_free(hdev, (void *) fence_ptr,
+					fence_dma_addr);
+	return rc;
+}
+
+int goya_test_cpu_queue(struct hl_device *hdev)
+{
+	struct armcp_packet test_pkt;
+	long result;
+	int rc;
+
+	/* cpu_queues_enable flag is always checked in send cpu message */
+
+	memset(&test_pkt, 0, sizeof(test_pkt));
+
+	test_pkt.opcode = ARMCP_PACKET_TEST;
+	test_pkt.value = ARMCP_PACKET_FENCE_VAL;
+
+	rc = hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &test_pkt,
+			sizeof(test_pkt), HL_DEVICE_TIMEOUT_USEC, &result);
+
+	if (!rc)
+		dev_info(hdev->dev, "queue test on CPU queue succeeded\n");
+	else
+		dev_err(hdev->dev, "CPU queue test failed (0x%08lX)\n", result);
+
+	return rc;
+}
+
+static int goya_test_queues(struct hl_device *hdev)
+{
+	struct goya_device *goya = hdev->asic_specific;
+	int i, rc, ret_val = 0;
+
+	if (hdev->ifh)
+		return 0;
+
+	for (i = 0 ; i < NUMBER_OF_EXT_HW_QUEUES ; i++) {
+		rc = goya_test_queue(hdev, i);
+		if (rc)
+			ret_val = -EINVAL;
+	}
+
+	if (hdev->cpu_queues_enable) {
+		rc = goya->test_cpu_queue(hdev);
+		if (rc)
+			ret_val = -EINVAL;
+	}
+
+	return ret_val;
+}
+
+void *goya_dma_pool_zalloc(struct hl_device *hdev, size_t size, gfp_t mem_flags,
+				dma_addr_t *dma_handle)
+{
+	if (size > GOYA_DMA_POOL_BLK_SIZE)
+		return NULL;
+
+	return dma_pool_zalloc(hdev->dma_pool, mem_flags, dma_handle);
+}
+
+void goya_dma_pool_free(struct hl_device *hdev, void *vaddr,
+			dma_addr_t dma_addr)
+{
+	dma_pool_free(hdev->dma_pool, vaddr, dma_addr);
+}
+
+void *goya_cpu_accessible_dma_pool_alloc(struct hl_device *hdev, size_t size,
+			dma_addr_t *dma_handle)
+{
+	u64 kernel_addr;
+
+	/* roundup to CPU_PKT_SIZE */
+	size = (size + (CPU_PKT_SIZE - 1)) & CPU_PKT_MASK;
+
+	kernel_addr = gen_pool_alloc(hdev->cpu_accessible_dma_pool, size);
+
+	*dma_handle = hdev->cpu_accessible_dma_address +
+			(kernel_addr - (u64) hdev->cpu_accessible_dma_mem);
+
+	return (void *) kernel_addr;
+}
+
+void goya_cpu_accessible_dma_pool_free(struct hl_device *hdev, size_t size,
+			void *vaddr)
+{
+	/* roundup to CPU_PKT_SIZE */
+	size = (size + (CPU_PKT_SIZE - 1)) & CPU_PKT_MASK;
+
+	gen_pool_free(hdev->cpu_accessible_dma_pool, (u64) vaddr, size);
+}
+
+
+static void goya_hw_queues_lock(struct hl_device *hdev)
+{
+	struct goya_device *goya = hdev->asic_specific;
+
+	spin_lock(&goya->hw_queues_lock);
+}
+
+static void goya_hw_queues_unlock(struct hl_device *hdev)
+{
+	struct goya_device *goya = hdev->asic_specific;
+
+	spin_unlock(&goya->hw_queues_lock);
+}
+
 static const struct hl_asic_funcs goya_funcs = {
 	.early_init = goya_early_init,
 	.early_fini = goya_early_fini,
@@ -2525,8 +3798,19 @@ static const struct hl_asic_funcs goya_funcs = {
 	.resume = goya_resume,
 	.mmap = goya_mmap,
 	.cb_mmap = goya_cb_mmap,
+	.ring_doorbell = goya_ring_doorbell,
+	.flush_pq_write = goya_flush_pq_write,
 	.dma_alloc_coherent = goya_dma_alloc_coherent,
 	.dma_free_coherent = goya_dma_free_coherent,
+	.get_int_queue_base = goya_get_int_queue_base,
+	.test_queues = goya_test_queues,
+	.dma_pool_zalloc = goya_dma_pool_zalloc,
+	.dma_pool_free = goya_dma_pool_free,
+	.cpu_accessible_dma_pool_alloc = goya_cpu_accessible_dma_pool_alloc,
+	.cpu_accessible_dma_pool_free = goya_cpu_accessible_dma_pool_free,
+	.hw_queues_lock = goya_hw_queues_lock,
+	.hw_queues_unlock = goya_hw_queues_unlock,
+	.send_cpu_message = goya_send_cpu_message
 };
 
 /**
drivers/misc/habanalabs/goya/goyaP.h +6 -0
index 45a6d2ca2752..598a718d3df1 100644
@@ -9,6 +9,7 @@
 #define GOYAP_H_
 
 #include "habanalabs.h"
+#include "include/goya/goya_packets.h"
 #include "include/goya/goya_boot_if.h"
 #include "include/goya/goya.h"
 
@@ -117,12 +118,17 @@ enum goya_fw_component {
 };
 
 struct goya_device {
+	int (*test_cpu_queue)(struct hl_device *hdev);
+
 	/* TODO: remove hw_queues_lock after moving to scheduler code */
 	spinlock_t	hw_queues_lock;
 	u64		ddr_bar_cur_addr;
 	u32		hw_cap_initialized;
 };
 
+int goya_test_cpu_queue(struct hl_device *hdev);
+int goya_send_cpu_message(struct hl_device *hdev, u32 *msg, u16 len,
+				u32 timeout, long *result);
 void goya_init_security(struct hl_device *hdev);
 
 #endif /* GOYAP_H_ */
drivers/misc/habanalabs/habanalabs.h +175 -1
index adda281ec2af..8232e2259463 100644
@@ -30,10 +30,36 @@
 struct hl_device;
 struct hl_fpriv;
 
+/**
+ * enum hl_queue_type - Supported QUEUE types.
+ * @QUEUE_TYPE_NA: queue is not available.
+ * @QUEUE_TYPE_EXT: external queue which is a DMA channel that may access the
+ *                  host.
+ * @QUEUE_TYPE_INT: internal queue that performs DMA inside the device's
+ *			memories and/or operates the compute engines.
+ * @QUEUE_TYPE_CPU: S/W queue for communication with the device's CPU.
+ */
+enum hl_queue_type {
+	QUEUE_TYPE_NA,
+	QUEUE_TYPE_EXT,
+	QUEUE_TYPE_INT,
+	QUEUE_TYPE_CPU
+};
 
+/**
+ * struct hw_queue_properties - queue information.
+ * @type: queue type.
+ * @kmd_only: true if only KMD is allowed to send a job to this queue, false
+ *            otherwise.
+ */
+struct hw_queue_properties {
+	enum hl_queue_type	type;
+	u8			kmd_only;
+};
 
 /**
  * struct asic_fixed_properties - ASIC specific immutable properties.
+ * @hw_queues_props: H/W queues properties.
  * @uboot_ver: F/W U-boot version.
  * @preboot_ver: F/W Preboot version.
  * @sram_base_address: SRAM physical start address.
@@ -64,6 +90,7 @@ struct hl_fpriv;
  * @tpc_enabled_mask: which TPCs are enabled.
  */
 struct asic_fixed_properties {
+	struct hw_queue_properties	hw_queues_props[HL_MAX_QUEUES];
 	char			uboot_ver[VERSION_MAX_LEN];
 	char			preboot_ver[VERSION_MAX_LEN];
 	u64			sram_base_address;
@@ -145,7 +172,92 @@ struct hl_cb {
 
 
 
+/*
+ * QUEUES
+ */
+
+struct hl_cs_job;
+
+/*
+ * Currently, there are two limitations on the maximum length of a queue:
+ *
+ * 1. The memory footprint of the queue. The current allocated space for the
+ *    queue is PAGE_SIZE. Because each entry in the queue is HL_BD_SIZE,
+ *    the maximum length of the queue can be PAGE_SIZE / HL_BD_SIZE,
+ *    which currently is 4096/16 = 256 entries.
+ *
+ *    To increase that, we need either to decrease the size of the
+ *    BD (difficult), or allocate more than a single page (easier).
+ *
+ * 2. Because the size of the JOB handle field in the BD CTL / completion queue
+ *    is 10-bit, we can have up to 1024 open jobs per hardware queue.
+ *    Therefore, each queue can hold up to 1024 entries.
+ *
+ * HL_QUEUE_LENGTH is in units of struct hl_bd.
+ * HL_QUEUE_LENGTH * sizeof(struct hl_bd) should be <= HL_PAGE_SIZE
+ */
+
+#define HL_PAGE_SIZE			4096 /* minimum page size */
+/* Must be power of 2 (HL_PAGE_SIZE / HL_BD_SIZE) */
 #define HL_QUEUE_LENGTH			256
+#define HL_QUEUE_SIZE_IN_BYTES		(HL_QUEUE_LENGTH * HL_BD_SIZE)
+
+/*
+ * HL_CQ_LENGTH is in units of struct hl_cq_entry.
+ * HL_CQ_LENGTH should be <= HL_PAGE_SIZE
+ */
+#define HL_CQ_LENGTH			HL_QUEUE_LENGTH
+#define HL_CQ_SIZE_IN_BYTES		(HL_CQ_LENGTH * HL_CQ_ENTRY_SIZE)
+
+
+
+/**
+ * struct hl_hw_queue - describes a H/W transport queue.
+ * @shadow_queue: pointer to a shadow queue that holds pointers to jobs.
+ * @queue_type: type of queue.
+ * @kernel_address: holds the queue's kernel virtual address.
+ * @bus_address: holds the queue's DMA address.
+ * @pi: holds the queue's pi value.
+ * @ci: holds the queue's ci value, AS CALCULATED BY THE DRIVER (not real ci).
+ * @hw_queue_id: the id of the H/W queue.
+ * @int_queue_len: length of internal queue (number of entries).
+ * @valid: is the queue valid (we have array of 32 queues, not all of them
+ *		exists).
+ */
+struct hl_hw_queue {
+	struct hl_cs_job	**shadow_queue;
+	enum hl_queue_type	queue_type;
+	u64			kernel_address;
+	dma_addr_t		bus_address;
+	u32			pi;
+	u32			ci;
+	u32			hw_queue_id;
+	u16			int_queue_len;
+	u8			valid;
+};
+
+/**
+ * struct hl_cq - describes a completion queue
+ * @hdev: pointer to the device structure
+ * @kernel_address: holds the queue's kernel virtual address
+ * @bus_address: holds the queue's DMA address
+ * @hw_queue_id: the id of the matching H/W queue
+ * @ci: ci inside the queue
+ * @pi: pi inside the queue
+ * @free_slots_cnt: counter of free slots in queue
+ */
+struct hl_cq {
+	struct hl_device	*hdev;
+	u64			kernel_address;
+	dma_addr_t		bus_address;
+	u32			hw_queue_id;
+	u32			ci;
+	u32			pi;
+	atomic_t		free_slots_cnt;
+};
+
+
+
 
 
 /*
@@ -180,8 +292,20 @@ enum hl_asic_type {
  * @resume: handles IP specific H/W or SW changes for resume.
  * @mmap: mmap function, does nothing.
  * @cb_mmap: maps a CB.
+ * @ring_doorbell: increment PI on a given QMAN.
+ * @flush_pq_write: flush PQ entry write if necessary, WARN if flushing failed.
  * @dma_alloc_coherent: DMA allocate coherent memory.
  * @dma_free_coherent: free DMA allocation.
+ * @get_int_queue_base: get the internal queue base address.
+ * @test_queues: run simple test on all queues for sanity check.
+ * @dma_pool_zalloc: small DMA allocation of coherent memory from DMA pool.
+ *                   size of allocation is HL_DMA_POOL_BLK_SIZE.
+ * @dma_pool_free: free small DMA allocation from pool.
+ * @cpu_accessible_dma_pool_alloc: allocate CPU PQ packet from DMA pool.
+ * @cpu_accessible_dma_pool_free: free CPU PQ packet from DMA pool.
+ * @hw_queues_lock: acquire H/W queues lock.
+ * @hw_queues_unlock: release H/W queues lock.
+ * @send_cpu_message: send buffer to ArmCP.
  */
 struct hl_asic_funcs {
 	int (*early_init)(struct hl_device *hdev);
@@ -195,10 +319,27 @@ struct hl_asic_funcs {
 	int (*mmap)(struct hl_fpriv *hpriv, struct vm_area_struct *vma);
 	int (*cb_mmap)(struct hl_device *hdev, struct vm_area_struct *vma,
 			u64 kaddress, phys_addr_t paddress, u32 size);
+	void (*ring_doorbell)(struct hl_device *hdev, u32 hw_queue_id, u32 pi);
+	void (*flush_pq_write)(struct hl_device *hdev, u64 *pq, u64 exp_val);
 	void* (*dma_alloc_coherent)(struct hl_device *hdev, size_t size,
 					dma_addr_t *dma_handle, gfp_t flag);
 	void (*dma_free_coherent)(struct hl_device *hdev, size_t size,
 					void *cpu_addr, dma_addr_t dma_handle);
+	void* (*get_int_queue_base)(struct hl_device *hdev, u32 queue_id,
+				dma_addr_t *dma_handle, u16 *queue_len);
+	int (*test_queues)(struct hl_device *hdev);
+	void* (*dma_pool_zalloc)(struct hl_device *hdev, size_t size,
+				gfp_t mem_flags, dma_addr_t *dma_handle);
+	void (*dma_pool_free)(struct hl_device *hdev, void *vaddr,
+				dma_addr_t dma_addr);
+	void* (*cpu_accessible_dma_pool_alloc)(struct hl_device *hdev,
+				size_t size, dma_addr_t *dma_handle);
+	void (*cpu_accessible_dma_pool_free)(struct hl_device *hdev,
+				size_t size, void *vaddr);
+	void (*hw_queues_lock)(struct hl_device *hdev);
+	void (*hw_queues_unlock)(struct hl_device *hdev);
+	int (*send_cpu_message)(struct hl_device *hdev, u32 *msg,
+				u16 len, u32 timeout, long *result);
 };
 
 
@@ -240,6 +381,17 @@ struct hl_ctx_mgr {
 
 
 
+/**
+ * struct hl_cs_job - command submission job.
+ * @finish_work: workqueue object to run when job is completed.
+ * @id: the id of this job inside a CS.
+ */
+struct hl_cs_job {
+	struct work_struct	finish_work;
+	u32			id;
+};
+
+
 /*
  * FILE PRIVATE STRUCTURE
  */
@@ -316,7 +468,11 @@ void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
  * @dev: realted kernel basic device structure.
  * @asic_name: ASIC specific nmae.
  * @asic_type: ASIC specific type.
+ * @completion_queue: array of hl_cq.
+ * @cq_wq: work queue of completion queues for executing work in process context
+ * @eq_wq: work queue of event queue for executing work in process context.
  * @kernel_ctx: KMD context structure.
+ * @kernel_queues: array of hl_hw_queue.
  * @kernel_cb_mgr: command buffer manager for creating/destroying/handling CGs.
  * @dma_pool: DMA pool for small allocations.
  * @cpu_accessible_dma_mem: KMD <-> ArmCP shared memory CPU address.
@@ -326,6 +482,7 @@ void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
  * @asid_bitmap: holds used/available ASIDs.
  * @asid_mutex: protects asid_bitmap.
  * @device_open: lock for sanity checks upon FD open.
+ * @send_cpu_message_lock: enforces only one message in KMD <-> ArmCP queue.
  * @asic_prop: ASIC specific immutable properties.
  * @asic_funcs: ASIC specific functions.
  * @asic_specific: ASIC specific information to use only from ASIC files.
@@ -345,7 +502,10 @@ struct hl_device {
 	struct device			*dev;
 	char				asic_name[16];
 	enum hl_asic_type		asic_type;
+	struct hl_cq			*completion_queue;
+	struct workqueue_struct		*cq_wq;
 	struct hl_ctx			*kernel_ctx;
+	struct hl_hw_queue		*kernel_queues;
 	struct hl_cb_mgr		kernel_cb_mgr;
 	struct dma_pool			*dma_pool;
 	void				*cpu_accessible_dma_mem;
@@ -356,6 +516,7 @@ struct hl_device {
 	struct mutex			asid_mutex;
 	/* TODO: change to rw_sem for multiple contexts (same as other IOCTL) */
 	struct mutex			device_open;
+	struct mutex			send_cpu_message_lock;
 	struct asic_fixed_properties	asic_prop;
 	const struct hl_asic_funcs	*asic_funcs;
 	void				*asic_specific;
@@ -374,7 +535,9 @@ struct hl_device {
 	u8				cpu_enable;
 	u8				reset_pcilink;
 	u8				config_pll;
+	u8				cpu_queues_enable;
 	u8				fw_loading;
+	u8				ifh;
 	u8				pldm;
 };
 
@@ -418,7 +581,18 @@ int hl_poll_timeout_memory(struct hl_device *hdev, u64 addr, u32 timeout_us,
 				u32 *val);
 int hl_poll_timeout_device_memory(struct hl_device *hdev, void __iomem *addr,
 				u32 timeout_us, u32 *val);
-
+int hl_hw_queues_create(struct hl_device *hdev);
+void hl_hw_queues_destroy(struct hl_device *hdev);
+int hl_hw_queue_send_cb_no_cmpl(struct hl_device *hdev, u32 hw_queue_id,
+				u32 cb_size, u64 cb_ptr);
+u32 hl_hw_queue_add_ptr(u32 ptr, u16 val);
+void hl_hw_queue_inc_ci_kernel(struct hl_device *hdev, u32 hw_queue_id);
+
+#define hl_queue_inc_ptr(p)		hl_hw_queue_add_ptr(p, 1)
+#define hl_pi_2_offset(pi)		((pi) & (HL_QUEUE_LENGTH - 1))
+
+int hl_cq_init(struct hl_device *hdev, struct hl_cq *q, u32 hw_queue_id);
+void hl_cq_fini(struct hl_device *hdev, struct hl_cq *q);
 int hl_asid_init(struct hl_device *hdev);
 void hl_asid_fini(struct hl_device *hdev);
 unsigned long hl_asid_alloc(struct hl_device *hdev);
drivers/misc/habanalabs/habanalabs_drv.c +6 -0
index bd80683118d3..b64f58ad0f5d 100644
@@ -184,13 +184,19 @@ int create_hdev(struct hl_device **dev, struct pci_dev *pdev,
 	hdev->cpu_enable = 1;
 	hdev->reset_pcilink = 0;
 	hdev->config_pll = 0;
+	hdev->cpu_queues_enable = 1;
 	hdev->fw_loading = 1;
+	hdev->ifh = 0;
 	hdev->pldm = 0;
 
 	/* If CPU is disabled, no point in loading FW */
 	if (!hdev->cpu_enable)
 		hdev->fw_loading = 0;
 
+	/* If we don't load FW, no need to initialize CPU queues */
+	if (!hdev->fw_loading)
+		hdev->cpu_queues_enable = 0;
+
 	hdev->disabled = true;
 	hdev->pdev = pdev; /* can be NULL in case of simulator device */
 
drivers/misc/habanalabs/hw_queue.c new file +404 -0
new file mode 100644
index 000000000000..65102a5bc2ca
@@ -0,0 +1,404 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ */
+
+#include "habanalabs.h"
+
+#include <linux/dma-mapping.h>
+#include <linux/sched.h>
+#include <linux/wait.h>
+#include <linux/delay.h>
+
+/**
+ * hl_queue_add_ptr - add to pi or ci and checks if it wraps around
+ *
+ * @ptr: the current pi/ci value
+ * @val: the amount to add
+ *
+ * Add val to ptr. It can go until twice the queue length.
+ */
+inline u32 hl_hw_queue_add_ptr(u32 ptr, u16 val)
+{
+	ptr += val;
+	ptr &= ((HL_QUEUE_LENGTH << 1) - 1);
+	return ptr;
+}
+
+static inline int queue_free_slots(struct hl_hw_queue *q, u32 queue_len)
+{
+	int delta = (q->pi - q->ci);
+
+	if (delta >= 0)
+		return (queue_len - delta);
+	else
+		return (abs(delta) - queue_len);
+}
+
+/**
+ * ext_queue_submit_bd - Submit a buffer descriptor to an external queue
+ *
+ * @hdev: pointer to habanalabs device structure
+ * @q: pointer to habanalabs queue structure
+ * @ctl: BD's control word
+ * @len: BD's length
+ * @ptr: BD's pointer
+ *
+ * This function assumes there is enough space on the queue to submit a new
+ * BD to it. It initializes the next BD and calls the device specific
+ * function to set the pi (and doorbell)
+ *
+ * This function must be called when the scheduler mutex is taken
+ *
+ */
+static void ext_queue_submit_bd(struct hl_device *hdev, struct hl_hw_queue *q,
+				u32 ctl, u32 len, u64 ptr)
+{
+	struct hl_bd *bd;
+
+	bd = (struct hl_bd *) q->kernel_address;
+	bd += hl_pi_2_offset(q->pi);
+	bd->ctl = ctl;
+	bd->len = len;
+	bd->ptr = ptr + hdev->asic_prop.host_phys_base_address;
+
+	q->pi = hl_queue_inc_ptr(q->pi);
+	hdev->asic_funcs->ring_doorbell(hdev, q->hw_queue_id, q->pi);
+}
+
+/**
+ * ext_queue_sanity_checks - perform some sanity checks on external queue
+ *
+ * @hdev              : pointer to hl_device structure
+ * @q                 :	pointer to hl_hw_queue structure
+ * @num_of_entries    : how many entries to check for space
+ * @reserve_cq_entry  :	whether to reserve an entry in the cq
+ *
+ * H/W queues spinlock should be taken before calling this function
+ *
+ * Perform the following:
+ * - Make sure we have enough space in the h/w queue
+ * - Make sure we have enough space in the completion queue
+ * - Reserve space in the completion queue (needs to be reversed if there
+ *   is a failure down the road before the actual submission of work). Only
+ *   do this action if reserve_cq_entry is true
+ *
+ */
+static int ext_queue_sanity_checks(struct hl_device *hdev,
+				struct hl_hw_queue *q, int num_of_entries,
+				bool reserve_cq_entry)
+{
+	atomic_t *free_slots =
+			&hdev->completion_queue[q->hw_queue_id].free_slots_cnt;
+	int free_slots_cnt;
+
+	/* Check we have enough space in the queue */
+	free_slots_cnt = queue_free_slots(q, HL_QUEUE_LENGTH);
+
+	if (free_slots_cnt < num_of_entries) {
+		dev_dbg(hdev->dev, "Queue %d doesn't have room for %d CBs\n",
+			q->hw_queue_id, num_of_entries);
+		return -EAGAIN;
+	}
+
+	if (reserve_cq_entry) {
+		/*
+		 * Check we have enough space in the completion queue
+		 * Add -1 to counter (decrement) unless counter was already 0
+		 * In that case, CQ is full so we can't submit a new CB because
+		 * we won't get ack on its completion
+		 * atomic_add_unless will return 0 if counter was already 0
+		 */
+		if (atomic_add_negative(num_of_entries * -1, free_slots)) {
+			dev_dbg(hdev->dev, "No space for %d on CQ %d\n",
+				num_of_entries, q->hw_queue_id);
+			atomic_add(num_of_entries, free_slots);
+			return -EAGAIN;
+		}
+	}
+
+	return 0;
+}
+
+/**
+ * hl_hw_queue_send_cb_no_cmpl - send a single CB (not a JOB) without completion
+ *
+ * @hdev: pointer to hl_device structure
+ * @hw_queue_id: Queue's type
+ * @cb_size: size of CB
+ * @cb_ptr: pointer to CB location
+ *
+ * This function sends a single CB, that must NOT generate a completion entry
+ *
+ */
+int hl_hw_queue_send_cb_no_cmpl(struct hl_device *hdev, u32 hw_queue_id,
+				u32 cb_size, u64 cb_ptr)
+{
+	struct hl_hw_queue *q = &hdev->kernel_queues[hw_queue_id];
+	int rc;
+
+	/*
+	 * The CPU queue is a synchronous queue with an effective depth of
+	 * a single entry (although it is allocated with room for multiple
+	 * entries). Therefore, there is a different lock, called
+	 * send_cpu_message_lock, that serializes accesses to the CPU queue.
+	 * As a result, we don't need to lock the access to the entire H/W
+	 * queues module when submitting a JOB to the CPU queue
+	 */
+	if (q->queue_type != QUEUE_TYPE_CPU)
+		hdev->asic_funcs->hw_queues_lock(hdev);
+
+	if (hdev->disabled) {
+		rc = -EPERM;
+		goto out;
+	}
+
+	rc = ext_queue_sanity_checks(hdev, q, 1, false);
+	if (rc)
+		goto out;
+
+	ext_queue_submit_bd(hdev, q, 0, cb_size, cb_ptr);
+
+out:
+	if (q->queue_type != QUEUE_TYPE_CPU)
+		hdev->asic_funcs->hw_queues_unlock(hdev);
+
+	return rc;
+}
+
+/**
+ * hl_hw_queue_inc_ci_kernel - increment ci for kernel's queue
+ *
+ * @hdev: pointer to hl_device structure
+ * @hw_queue_id: which queue to increment its ci
+ */
+void hl_hw_queue_inc_ci_kernel(struct hl_device *hdev, u32 hw_queue_id)
+{
+	struct hl_hw_queue *q = &hdev->kernel_queues[hw_queue_id];
+
+	q->ci = hl_queue_inc_ptr(q->ci);
+}
+
+static int ext_and_cpu_hw_queue_init(struct hl_device *hdev,
+					struct hl_hw_queue *q)
+{
+	void *p;
+	int rc;
+
+	p = hdev->asic_funcs->dma_alloc_coherent(hdev,
+				HL_QUEUE_SIZE_IN_BYTES,
+				&q->bus_address, GFP_KERNEL | __GFP_ZERO);
+	if (!p)
+		return -ENOMEM;
+
+	q->kernel_address = (u64) p;
+
+	q->shadow_queue = kmalloc_array(HL_QUEUE_LENGTH,
+					sizeof(*q->shadow_queue),
+					GFP_KERNEL);
+	if (!q->shadow_queue) {
+		dev_err(hdev->dev,
+			"Failed to allocate shadow queue for H/W queue %d\n",
+			q->hw_queue_id);
+		rc = -ENOMEM;
+		goto free_queue;
+	}
+
+	/* Make sure read/write pointers are initialized to start of queue */
+	q->ci = 0;
+	q->pi = 0;
+
+	return 0;
+
+free_queue:
+	hdev->asic_funcs->dma_free_coherent(hdev, HL_QUEUE_SIZE_IN_BYTES,
+			(void *) q->kernel_address, q->bus_address);
+
+	return rc;
+}
+
+static int int_hw_queue_init(struct hl_device *hdev, struct hl_hw_queue *q)
+{
+	void *p;
+
+	p = hdev->asic_funcs->get_int_queue_base(hdev, q->hw_queue_id,
+					&q->bus_address, &q->int_queue_len);
+	if (!p) {
+		dev_err(hdev->dev,
+			"Failed to get base address for internal queue %d\n",
+			q->hw_queue_id);
+		return -EFAULT;
+	}
+
+	q->kernel_address = (u64) p;
+	q->pi = 0;
+	q->ci = 0;
+
+	return 0;
+}
+
+static int cpu_hw_queue_init(struct hl_device *hdev, struct hl_hw_queue *q)
+{
+	return ext_and_cpu_hw_queue_init(hdev, q);
+}
+
+static int ext_hw_queue_init(struct hl_device *hdev, struct hl_hw_queue *q)
+{
+	return ext_and_cpu_hw_queue_init(hdev, q);
+}
+
+/**
+ * hw_queue_init - main initialization function for H/W queue object
+ *
+ * @hdev: pointer to hl_device device structure
+ * @q: pointer to hl_hw_queue queue structure
+ * @hw_queue_id: The id of the H/W queue
+ *
+ * Allocate dma-able memory for the queue and initialize fields
+ * Returns 0 on success
+ */
+static int hw_queue_init(struct hl_device *hdev, struct hl_hw_queue *q,
+			u32 hw_queue_id)
+{
+	int rc;
+
+	BUILD_BUG_ON(HL_QUEUE_SIZE_IN_BYTES > HL_PAGE_SIZE);
+
+	q->hw_queue_id = hw_queue_id;
+
+	switch (q->queue_type) {
+	case QUEUE_TYPE_EXT:
+		rc = ext_hw_queue_init(hdev, q);
+		break;
+
+	case QUEUE_TYPE_INT:
+		rc = int_hw_queue_init(hdev, q);
+		break;
+
+	case QUEUE_TYPE_CPU:
+		rc = cpu_hw_queue_init(hdev, q);
+		break;
+
+	case QUEUE_TYPE_NA:
+		q->valid = 0;
+		return 0;
+
+	default:
+		dev_crit(hdev->dev, "wrong queue type %d during init\n",
+			q->queue_type);
+		rc = -EINVAL;
+		break;
+	}
+
+	if (rc)
+		return rc;
+
+	q->valid = 1;
+
+	return 0;
+}
+
+/**
+ * hw_queue_fini - destroy queue
+ *
+ * @hdev: pointer to hl_device device structure
+ * @q: pointer to hl_hw_queue queue structure
+ *
+ * Free the queue memory
+ */
+static void hw_queue_fini(struct hl_device *hdev, struct hl_hw_queue *q)
+{
+	if (!q->valid)
+		return;
+
+	/*
+	 * If we arrived here, there are no jobs waiting on this queue
+	 * so we can safely remove it.
+	 * This is because this function can only called when:
+	 * 1. Either a context is deleted, which only can occur if all its
+	 *    jobs were finished
+	 * 2. A context wasn't able to be created due to failure or timeout,
+	 *    which means there are no jobs on the queue yet
+	 *
+	 * The only exception are the queues of the kernel context, but
+	 * if they are being destroyed, it means that the entire module is
+	 * being removed. If the module is removed, it means there is no open
+	 * user context. It also means that if a job was submitted by
+	 * the kernel driver (e.g. context creation), the job itself was
+	 * released by the kernel driver when a timeout occurred on its
+	 * Completion. Thus, we don't need to release it again.
+	 */
+
+	if (q->queue_type == QUEUE_TYPE_INT)
+		return;
+
+	kfree(q->shadow_queue);
+
+	hdev->asic_funcs->dma_free_coherent(hdev,
+			HL_QUEUE_SIZE_IN_BYTES,
+			(void *) q->kernel_address, q->bus_address);
+}
+
+int hl_hw_queues_create(struct hl_device *hdev)
+{
+	struct asic_fixed_properties *asic = &hdev->asic_prop;
+	struct hl_hw_queue *q;
+	int i, rc, q_ready_cnt;
+
+	hdev->kernel_queues = kcalloc(HL_MAX_QUEUES,
+				sizeof(*hdev->kernel_queues), GFP_KERNEL);
+
+	if (!hdev->kernel_queues) {
+		dev_err(hdev->dev, "Not enough memory for H/W queues\n");
+		return -ENOMEM;
+	}
+
+	/* Initialize the H/W queues */
+	for (i = 0, q_ready_cnt = 0, q = hdev->kernel_queues;
+			i < HL_MAX_QUEUES ; i++, q_ready_cnt++, q++) {
+
+		q->queue_type = asic->hw_queues_props[i].type;
+		rc = hw_queue_init(hdev, q, i);
+		if (rc) {
+			dev_err(hdev->dev,
+				"failed to initialize queue %d\n", i);
+			goto release_queues;
+		}
+	}
+
+	return 0;
+
+release_queues:
+	for (i = 0, q = hdev->kernel_queues ; i < q_ready_cnt ; i++, q++)
+		hw_queue_fini(hdev, q);
+
+	kfree(hdev->kernel_queues);
+
+	return rc;
+}
+
+void hl_hw_queues_destroy(struct hl_device *hdev)
+{
+	struct hl_hw_queue *q;
+	int i;
+
+	for (i = 0, q = hdev->kernel_queues ; i < HL_MAX_QUEUES ; i++, q++)
+		hw_queue_fini(hdev, q);
+
+	kfree(hdev->kernel_queues);
+}
+
+void hl_hw_queue_reset(struct hl_device *hdev, bool hard_reset)
+{
+	struct hl_hw_queue *q;
+	int i;
+
+	for (i = 0, q = hdev->kernel_queues ; i < HL_MAX_QUEUES ; i++, q++) {
+		if ((!q->valid) ||
+			((!hard_reset) && (q->queue_type == QUEUE_TYPE_CPU)))
+			continue;
+		q->pi = q->ci = 0;
+	}
+}
drivers/misc/habanalabs/include/goya/goya_packets.h new file +234 -0
new file mode 100644
index 000000000000..669a3f37ccb7
@@ -0,0 +1,234 @@
+/* SPDX-License-Identifier: GPL-2.0
+ *
+ * Copyright 2017-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ *
+ * Authors:
+ *
+ * Oded Gabbay <[email protected]>
+ * Guy Eilat <[email protected]>
+ *
+ */
+
+#ifndef GOYA_PACKETS_H
+#define GOYA_PACKETS_H
+
+#include <linux/types.h>
+
+#define PACKET_HEADER_PACKET_ID_SHIFT		56
+#define PACKET_HEADER_PACKET_ID_MASK		0x1F00000000000000ull
+
+enum packet_id {
+	PACKET_WREG_32 = 0x1,
+	PACKET_WREG_BULK = 0x2,
+	PACKET_MSG_LONG = 0x3,
+	PACKET_MSG_SHORT = 0x4,
+	PACKET_CP_DMA = 0x5,
+	PACKET_MSG_PROT = 0x7,
+	PACKET_FENCE = 0x8,
+	PACKET_LIN_DMA = 0x9,
+	PACKET_NOP = 0xA,
+	PACKET_STOP = 0xB,
+	MAX_PACKET_ID = (PACKET_HEADER_PACKET_ID_MASK >>
+				PACKET_HEADER_PACKET_ID_SHIFT) + 1
+};
+
+enum goya_dma_direction {
+	DMA_HOST_TO_DRAM,
+	DMA_HOST_TO_SRAM,
+	DMA_DRAM_TO_SRAM,
+	DMA_SRAM_TO_DRAM,
+	DMA_SRAM_TO_HOST,
+	DMA_DRAM_TO_HOST,
+	DMA_DRAM_TO_DRAM,
+	DMA_SRAM_TO_SRAM,
+	DMA_ENUM_MAX
+};
+
+struct packet_nop {
+	__u32 reserved;
+	union {
+		struct {
+			__u32:24;
+			__u32 opcode :5;
+			__u32 eng_barrier :1;
+			__u32 reg_barrier :1;
+			__u32 msg_barrier :1;
+		};
+		__u32 ctl;
+	};
+};
+
+struct packet_stop {
+	__u32 reserved;
+	union {
+		struct {
+			__u32:24;
+			__u32 opcode :5;
+			__u32 eng_barrier :1;
+			__u32 reg_barrier :1; /* must be 0 */
+			__u32 msg_barrier :1; /* must be 0 */
+		};
+		__u32 ctl;
+	};
+};
+
+struct packet_wreg32 {
+	__u32 value;
+	union {
+		struct {
+			__u32 reg_offset :16;
+			__u32:7;
+			__u32 local :1; /* 0: write to TCL regs,
+					 * 1: write to CMDQ regs
+					 */
+			__u32 opcode :5;
+			__u32 eng_barrier :1;
+			__u32 reg_barrier :1; /* must be 1 */
+			__u32 msg_barrier :1;
+		};
+		__u32 ctl;
+	};
+};
+
+struct packet_wreg_bulk {
+	__u32 size64 :16;
+	__u32:16;
+	__u32 reg_offset :16;
+	__u32:8;
+	__u32 opcode :5;
+	__u32 eng_barrier :1;
+	__u32 reg_barrier :1; /* must be 1 */
+	__u32 msg_barrier :1;
+	__u64 values[0]; /* data starts here */
+};
+
+struct packet_msg_long {
+	__u32 value;
+	union {
+		struct {
+			__u32:16;
+			__u32 weakly_ordered :1;
+			__u32 no_snoop :1;
+			__u32:2;
+			__u32 op :2; /* 0: write <value>. 1: write timestamp. */
+			__u32:2;
+			__u32 opcode :5;
+			__u32 eng_barrier :1;
+			__u32 reg_barrier :1;
+			__u32 msg_barrier :1;
+		};
+		__u32 ctl;
+	};
+	__u64 addr;
+};
+
+struct packet_msg_short {
+	union {
+		struct {
+			__u32 sync_id :10;
+			__u32:5;
+			__u32 mode : 1;
+			__u32 sync_value :16;
+		} mon_arm_register;
+		struct {
+			__u32 sync_value :16;
+			__u32:15;
+			__u32 mode :1;
+		} so_upd;
+		__u32 value;
+	};
+	union {
+		struct {
+			__u32 msg_addr_offset :16;
+			__u32 weakly_ordered :1;
+			__u32 no_snoop :1;
+			__u32:2;
+			__u32 op :2;
+			__u32 base :2;
+			__u32 opcode :5;
+			__u32 eng_barrier :1;
+			__u32 reg_barrier :1;
+			__u32 msg_barrier :1;
+		};
+		__u32 ctl;
+	};
+};
+
+struct packet_msg_prot {
+	__u32 value;
+	union {
+		struct {
+			__u32:16;
+			__u32 weakly_ordered :1;
+			__u32 no_snoop :1;
+			__u32:2;
+			__u32 op :2; /* 0: write <value>. 1: write timestamp. */
+			__u32:2;
+			__u32 opcode :5;
+			__u32 eng_barrier :1;
+			__u32 reg_barrier :1;
+			__u32 msg_barrier :1;
+		};
+		__u32 ctl;
+	};
+	__u64 addr;
+};
+
+struct packet_fence {
+	__u32 dec_val :4;
+	__u32:12;
+	__u32 gate_val :8;
+	__u32:6;
+	__u32 id :2;
+	__u32:24;
+	__u32 opcode :5;
+	__u32 eng_barrier :1;
+	__u32 reg_barrier :1;
+	__u32 msg_barrier :1;
+};
+
+struct packet_lin_dma {
+	__u32 tsize;
+	union {
+		struct {
+			__u32 weakly_ordered :1; /* H/W bug, must be 1 */
+			__u32 rdcomp :1;
+			__u32 wrcomp :1;
+			__u32 no_snoop :1;
+			__u32 src_disable :1;
+			__u32 dst_disable :1;
+			__u32 memset_mode :1;
+			__u32 tensor_dma :1; /* N/A, must be 0 */
+			__u32 cntrl :12;
+			__u32 dma_dir :3; /* S/W only, no effect on HW */
+			__u32:1;
+			__u32 opcode :5;
+			__u32 eng_barrier :1;
+			__u32 reg_barrier :1; /* must be 1 */
+			__u32 msg_barrier :1;
+		};
+		__u32 ctl;
+	};
+	__u64 src_addr;
+	__u64 dst_addr;
+};
+
+struct packet_cp_dma {
+	__u32 tsize;
+	union {
+		struct {
+			__u32 weakly_ordered :1;
+			__u32 no_snoop :1;
+			__u32:22;
+			__u32 opcode :5;
+			__u32 eng_barrier :1;
+			__u32 reg_barrier :1; /* must be 1 */
+			__u32 msg_barrier :1;
+		};
+		__u32 ctl;
+	};
+	__u64 src_addr;
+};
+
+#endif /* GOYA_PACKETS_H */
drivers/misc/habanalabs/include/habanalabs_device_if.h +272 -0
index 9dbb7077eabd..62df9981f68a 100644
@@ -97,6 +97,278 @@ enum pq_init_status {
 	PQ_INIT_STATUS_READY_FOR_HOST
 };
 
+/*
+ * ArmCP Primary Queue Packets
+ *
+ * During normal operation, KMD needs to send various messages to ArmCP,
+ * usually either to SET some value into a H/W periphery or to GET the current
+ * value of some H/W periphery. For example, SET the frequency of MME/TPC and
+ * GET the value of the thermal sensor.
+ *
+ * These messages can be initiated either by the User application or by KMD
+ * itself, e.g. power management code. In either case, the communication from
+ * KMD to ArmCP will *always* be in synchronous mode, meaning that KMD will
+ * send a single message and poll until the message was acknowledged and the
+ * results are ready (if results are needed).
+ *
+ * This means that only a single message can be sent at a time and KMD must
+ * wait for its result before sending the next message. Having said that,
+ * because these are control messages which are sent in a relatively low
+ * frequency, this limitation seems acceptable. It's important to note that
+ * in case of multiple devices, messages to different devices *can* be sent
+ * at the same time.
+ *
+ * The message, inputs/outputs (if relevant) and fence object will be located
+ * on the device DDR at an address that will be determined by KMD. During
+ * device initialization phase, KMD will pass to ArmCP that address.  Most of
+ * the message types will contain inputs/outputs inside the message itself.
+ * The common part of each message will contain the opcode of the message (its
+ * type) and a field representing a fence object.
+ *
+ * When KMD wishes to send a message to ArmCP, it will write the message
+ * contents to the device DDR, clear the fence object and then write the
+ * value 484 to the mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR register to issue
+ * the 484 interrupt-id to the ARM core.
+ *
+ * Upon receiving the 484 interrupt-id, ArmCP will read the message from the
+ * DDR. In case the message is a SET operation, ArmCP will first perform the
+ * operation and then write to the fence object on the device DDR. In case the
+ * message is a GET operation, ArmCP will first fill the results section on the
+ * device DDR and then write to the fence object. If an error occurred, ArmCP
+ * will fill the rc field with the right error code.
+ *
+ * In the meantime, KMD will poll on the fence object. Once KMD sees that the
+ * fence object is signaled, it will read the results from the device DDR
+ * (if relevant) and resume the code execution in KMD.
+ *
+ * To use QMAN packets, the opcode must be the QMAN opcode, shifted by 8
+ * so the value being put by the KMD matches the value read by ArmCP
+ *
+ * Non-QMAN packets should be limited to values 1 through (2^8 - 1)
+ *
+ * Detailed description:
+ *
+ * ARMCP_PACKET_DISABLE_PCI_ACCESS -
+ *       After receiving this packet the embedded CPU must NOT issue PCI
+ *       transactions (read/write) towards the Host CPU. This also include
+ *       sending MSI-X interrupts.
+ *       This packet is usually sent before the device is moved to D3Hot state.
+ *
+ * ARMCP_PACKET_ENABLE_PCI_ACCESS -
+ *       After receiving this packet the embedded CPU is allowed to issue PCI
+ *       transactions towards the Host CPU, including sending MSI-X interrupts.
+ *       This packet is usually send after the device is moved to D0 state.
+ *
+ * ARMCP_PACKET_TEMPERATURE_GET -
+ *       Fetch the current temperature / Max / Max Hyst / Critical /
+ *       Critical Hyst of a specified thermal sensor. The packet's
+ *       arguments specify the desired sensor and the field to get.
+ *
+ * ARMCP_PACKET_VOLTAGE_GET -
+ *       Fetch the voltage / Max / Min of a specified sensor. The packet's
+ *       arguments specify the sensor and type.
+ *
+ * ARMCP_PACKET_CURRENT_GET -
+ *       Fetch the current / Max / Min of a specified sensor. The packet's
+ *       arguments specify the sensor and type.
+ *
+ * ARMCP_PACKET_FAN_SPEED_GET -
+ *       Fetch the speed / Max / Min of a specified fan. The packet's
+ *       arguments specify the sensor and type.
+ *
+ * ARMCP_PACKET_PWM_GET -
+ *       Fetch the pwm value / mode of a specified pwm. The packet's
+ *       arguments specify the sensor and type.
+ *
+ * ARMCP_PACKET_PWM_SET -
+ *       Set the pwm value / mode of a specified pwm. The packet's
+ *       arguments specify the sensor, type and value.
+ *
+ * ARMCP_PACKET_FREQUENCY_SET -
+ *       Set the frequency of a specified PLL. The packet's arguments specify
+ *       the PLL and the desired frequency. The actual frequency in the device
+ *       might differ from the requested frequency.
+ *
+ * ARMCP_PACKET_FREQUENCY_GET -
+ *       Fetch the frequency of a specified PLL. The packet's arguments specify
+ *       the PLL.
+ *
+ * ARMCP_PACKET_LED_SET -
+ *       Set the state of a specified led. The packet's arguments
+ *       specify the led and the desired state.
+ *
+ * ARMCP_PACKET_I2C_WR -
+ *       Write 32-bit value to I2C device. The packet's arguments specify the
+ *       I2C bus, address and value.
+ *
+ * ARMCP_PACKET_I2C_RD -
+ *       Read 32-bit value from I2C device. The packet's arguments specify the
+ *       I2C bus and address.
+ *
+ * ARMCP_PACKET_INFO_GET -
+ *       Fetch information from the device as specified in the packet's
+ *       structure. KMD passes the max size it allows the ArmCP to write to
+ *       the structure, to prevent data corruption in case of mismatched
+ *       KMD/FW versions.
+ *
+ * ARMCP_PACKET_FLASH_PROGRAM_REMOVED - this packet was removed
+ *
+ * ARMCP_PACKET_UNMASK_RAZWI_IRQ -
+ *       Unmask the given IRQ. The IRQ number is specified in the value field.
+ *       The packet is sent after receiving an interrupt and printing its
+ *       relevant information.
+ *
+ * ARMCP_PACKET_UNMASK_RAZWI_IRQ_ARRAY -
+ *       Unmask the given IRQs. The IRQs numbers are specified in an array right
+ *       after the armcp_packet structure, where its first element is the array
+ *       length. The packet is sent after a soft reset was done in order to
+ *       handle any interrupts that were sent during the reset process.
+ *
+ * ARMCP_PACKET_TEST -
+ *       Test packet for ArmCP connectivity. The CPU will put the fence value
+ *       in the result field.
+ *
+ * ARMCP_PACKET_FREQUENCY_CURR_GET -
+ *       Fetch the current frequency of a specified PLL. The packet's arguments
+ *       specify the PLL.
+ *
+ * ARMCP_PACKET_MAX_POWER_GET -
+ *       Fetch the maximal power of the device.
+ *
+ * ARMCP_PACKET_MAX_POWER_SET -
+ *       Set the maximal power of the device. The packet's arguments specify
+ *       the power.
+ *
+ * ARMCP_PACKET_EEPROM_DATA_GET -
+ *       Get EEPROM data from the ArmCP kernel. The buffer is specified in the
+ *       addr field. The CPU will put the returned data size in the result
+ *       field. In addition, KMD passes the max size it allows the ArmCP to
+ *       write to the structure, to prevent data corruption in case of
+ *       mismatched KMD/FW versions.
+ *
+ */
+
+enum armcp_packet_id {
+	ARMCP_PACKET_DISABLE_PCI_ACCESS = 1,	/* internal */
+	ARMCP_PACKET_ENABLE_PCI_ACCESS,		/* internal */
+	ARMCP_PACKET_TEMPERATURE_GET,		/* sysfs */
+	ARMCP_PACKET_VOLTAGE_GET,		/* sysfs */
+	ARMCP_PACKET_CURRENT_GET,		/* sysfs */
+	ARMCP_PACKET_FAN_SPEED_GET,		/* sysfs */
+	ARMCP_PACKET_PWM_GET,			/* sysfs */
+	ARMCP_PACKET_PWM_SET,			/* sysfs */
+	ARMCP_PACKET_FREQUENCY_SET,		/* sysfs */
+	ARMCP_PACKET_FREQUENCY_GET,		/* sysfs */
+	ARMCP_PACKET_LED_SET,			/* debugfs */
+	ARMCP_PACKET_I2C_WR,			/* debugfs */
+	ARMCP_PACKET_I2C_RD,			/* debugfs */
+	ARMCP_PACKET_INFO_GET,			/* IOCTL */
+	ARMCP_PACKET_FLASH_PROGRAM_REMOVED,
+	ARMCP_PACKET_UNMASK_RAZWI_IRQ,		/* internal */
+	ARMCP_PACKET_UNMASK_RAZWI_IRQ_ARRAY,	/* internal */
+	ARMCP_PACKET_TEST,			/* internal */
+	ARMCP_PACKET_FREQUENCY_CURR_GET,	/* sysfs */
+	ARMCP_PACKET_MAX_POWER_GET,		/* sysfs */
+	ARMCP_PACKET_MAX_POWER_SET,		/* sysfs */
+	ARMCP_PACKET_EEPROM_DATA_GET,		/* sysfs */
+};
+
+#define ARMCP_PACKET_FENCE_VAL	0xFE8CE7A5
+
+struct armcp_packet {
+	union {
+		__u64 value;	/* For SET packets */
+		__u64 result;	/* For GET packets */
+		__u64 addr;	/* For PQ */
+	};
+
+	union {
+		struct {
+			__u32:12;
+			__u32 rc :4;
+			__u32 opcode :13;
+			__u32 eng_barrier :1;
+			__u32 reg_barrier :1;
+			__u32 msg_barrier :1;
+		};
+		__u32 ctl;
+	};
+
+	__u32 fence;		/* Signal to KMD that message is completed */
+
+	union {
+		struct {/* For temperature/current/voltage/fan/pwm get/set */
+			__u16 sensor_index;
+			__u16 type;
+		};
+
+		struct {	/* For I2C read/write */
+			__u8 i2c_bus;
+			__u8 i2c_addr;
+			__u8 i2c_reg;
+			__u8 pad; /* unused */
+		};
+
+		/* For frequency get/set */
+		__u32 pll_index;
+
+		/* For led set */
+		__u32 led_index;
+
+		/* For get Armcp info/EEPROM data */
+		__u32 data_max_size;
+	};
+};
+
+struct armcp_unmask_irq_arr_packet {
+	struct armcp_packet armcp_pkt;
+	__u32 length;
+	__u32 irqs[0];
+};
+
+enum armcp_packet_rc {
+	armcp_packet_success,
+	armcp_packet_invalid,
+	armcp_packet_fault
+};
+
+enum armcp_temp_type {
+	armcp_temp_input,
+	armcp_temp_max = 6,
+	armcp_temp_max_hyst,
+	armcp_temp_crit,
+	armcp_temp_crit_hyst
+};
+
+enum armcp_in_attributes {
+	armcp_in_input,
+	armcp_in_min,
+	armcp_in_max
+};
+
+enum armcp_curr_attributes {
+	armcp_curr_input,
+	armcp_curr_min,
+	armcp_curr_max
+};
+
+enum armcp_fan_attributes {
+	armcp_fan_input,
+	armcp_fan_min = 2,
+	armcp_fan_max
+};
+
+enum armcp_pwm_attributes {
+	armcp_pwm_input,
+	armcp_pwm_enable
+};
+
+/* Event Queue Packets */
+
+struct eq_generic_event {
+	__u64 data[7];
+};
+
 /*
  * ArmCP info
  */
drivers/misc/habanalabs/irq.c new file +150 -0
new file mode 100644
index 000000000000..97b0de7ea5c2
@@ -0,0 +1,150 @@
+// SPDX-License-Identifier: GPL-2.0
[… more lines in the raw message]

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.17.1
Signature · 2 lines
Sincerely yours,
Mike.

Part of the diff is not shown here. View the raw message.

#36 lore raw

Re: [PATCH 08/15] habanalabs: add event queue and interrupts

In reply to Oded Gabbay
Quoted 34 lines · Oded Gabbay

This patch adds support for receiving events from Goya's control CPU and for receiving MSI-X interrupts from Goya's DMA engines and CPU.

Goya's PCI controller supports up to 8 MSI-X interrupts, which only 6 of them are currently used. The first 5 interrupts are dedicated for Goya's DMA engine queues. The 6th interrupt is dedicated for Goya's control CPU.

The DMA queue will signal its MSI-X entry upon each completion of a command buffer that was placed on its primary queue. The driver will then mark that CB as completed and free the related resources. It will also update the command submission object which that CB belongs to.

There is a dedicated event queue (EQ) between the driver and Goya's control CPU. The EQ is located on the Host memory. The control CPU writes a new entry to the EQ for various reasons, such as ECC error, MMU page fault, Hot temperature. After writing the new entry to the EQ, the control CPU will trigger its dedicated MSI-X entry to signal the driver that there is a new entry in the EQ. The driver will then read the entry and act accordingly.

---
 drivers/misc/habanalabs/device.c            |  35 +-
 drivers/misc/habanalabs/goya/goya.c         | 522 +++++++++++++++++++-
 drivers/misc/habanalabs/goya/goyaP.h        |   1 +
 drivers/misc/habanalabs/habanalabs.h        |  37 ++
 drivers/misc/habanalabs/include/goya/goya.h |   1 -
 drivers/misc/habanalabs/irq.c               | 144 ++++++
 6 files changed, 729 insertions(+), 11 deletions(-)
drivers/misc/habanalabs/device.c +0 -0
index 98220628a467..9199e070e79e 100644

drivers/misc/habanalabs/device.c static int device_early_init(struct hl_device *hdev) · line 176

Quoted 4 lines
drivers/misc/habanalabs/device.c +1 -0
@@ -173,9 +173,17 @@ static int device_early_init(struct hl_device *hdev)
 	hdev->cq_wq = alloc_workqueue("hl-free-jobs", WQ_UNBOUND, 0);
 	if (hdev->cq_wq == NULL) {
 		dev_err(hdev->dev, "Failed to allocate CQ workqueue\n");
+		rc = -ENOMEM;

Apparently, it should have been in one of the earlier patches

Quoted 429 lines
drivers/misc/habanalabs/device.c +33 -1
 		goto asid_fini;
 	}
 
+	hdev->eq_wq = alloc_workqueue("hl-events", WQ_UNBOUND, 0);
+	if (hdev->eq_wq == NULL) {
+		dev_err(hdev->dev, "Failed to allocate EQ workqueue\n");
+		rc = -ENOMEM;
+		goto free_cq_wq;
+	}
+
 	hl_cb_mgr_init(&hdev->kernel_cb_mgr);
 
 	mutex_init(&hdev->device_open);
@@ -184,6 +192,8 @@ static int device_early_init(struct hl_device *hdev)
 
 	return 0;
 
+free_cq_wq:
+	destroy_workqueue(hdev->cq_wq);
 asid_fini:
 	hl_asid_fini(hdev);
 early_fini:
@@ -205,6 +215,7 @@ static void device_early_fini(struct hl_device *hdev)
 
 	hl_cb_mgr_fini(hdev, &hdev->kernel_cb_mgr);
 
+	destroy_workqueue(hdev->eq_wq);
 	destroy_workqueue(hdev->cq_wq);
 
 	hl_asid_fini(hdev);
@@ -343,11 +354,22 @@ int hl_device_init(struct hl_device *hdev, struct class *hclass)
 		}
 	}
 
+	/*
+	 * Initialize the event queue. Must be done before hw_init,
+	 * because there the address of the event queue is being
+	 * passed as argument to request_irq
+	 */
+	rc = hl_eq_init(hdev, &hdev->event_queue);
+	if (rc) {
+		dev_err(hdev->dev, "failed to initialize event queue\n");
+		goto cq_fini;
+	}
+
 	/* Allocate the kernel context */
 	hdev->kernel_ctx = kzalloc(sizeof(*hdev->kernel_ctx), GFP_KERNEL);
 	if (!hdev->kernel_ctx) {
 		rc = -ENOMEM;
-		goto cq_fini;
+		goto eq_fini;
 	}
 
 	hdev->user_ctx = NULL;
@@ -392,6 +414,8 @@ int hl_device_init(struct hl_device *hdev, struct class *hclass)
 			"kernel ctx is still alive on initialization failure\n");
 free_ctx:
 	kfree(hdev->kernel_ctx);
+eq_fini:
+	hl_eq_fini(hdev, &hdev->event_queue);
 cq_fini:
 	for (i = 0 ; i < cq_ready_cnt ; i++)
 		hl_cq_fini(hdev, &hdev->completion_queue[i]);
@@ -433,6 +457,13 @@ void hl_device_fini(struct hl_device *hdev)
 	/* Mark device as disabled */
 	hdev->disabled = true;
 
+	/*
+	 * Halt the engines and disable interrupts so we won't get any more
+	 * completions from H/W and we won't have any accesses from the
+	 * H/W to the host machine
+	 */
+	hdev->asic_funcs->halt_engines(hdev, true);
+
 	hl_cb_pool_fini(hdev);
 
 	/* Release kernel context */
@@ -442,6 +473,8 @@ void hl_device_fini(struct hl_device *hdev)
 	/* Reset the H/W. It will be in idle state after this returns */
 	hdev->asic_funcs->hw_fini(hdev, true);
 
+	hl_eq_fini(hdev, &hdev->event_queue);
+
 	for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
 		hl_cq_fini(hdev, &hdev->completion_queue[i]);
 	kfree(hdev->completion_queue);
drivers/misc/habanalabs/goya/goya.c +244 -9
index 08d5227eaf1d..6c04277ae0fa 100644
@@ -92,9 +92,41 @@
 
 #define GOYA_MAX_INITIATORS		20
 
+#define GOYA_MAX_STRING_LEN		20
+
 #define GOYA_CB_POOL_CB_CNT		512
 #define GOYA_CB_POOL_CB_SIZE		0x20000		/* 128KB */
 
+static const char goya_irq_name[GOYA_MSIX_ENTRIES][GOYA_MAX_STRING_LEN] = {
+		"goya cq 0", "goya cq 1", "goya cq 2", "goya cq 3",
+		"goya cq 4", "goya cpu eq"
+};
+
+static const char *goya_axi_name[GOYA_MAX_INITIATORS] = {
+	"MME0",
+	"MME1",
+	"MME2",
+	"MME3",
+	"MME4",
+	"MME5",
+	"TPC0",
+	"TPC1",
+	"TPC2",
+	"TPC3",
+	"TPC4",
+	"TPC5",
+	"TPC6",
+	"TPC7",
+	"PCI",
+	"DMA", /* HBW */
+	"DMA", /* LBW */
+	"PSOC",
+	"CPU",
+	"MMU"
+};
+
+#define GOYA_ASYC_EVENT_GROUP_NON_FATAL_SIZE 121
+
 static void goya_get_fixed_properties(struct hl_device *hdev)
 {
 	struct asic_fixed_properties *prop = &hdev->asic_prop;
@@ -139,6 +171,7 @@ static void goya_get_fixed_properties(struct hl_device *hdev)
 	prop->va_space_dram_end_address = VA_DDR_SPACE_END;
 	prop->cfg_size = CFG_SIZE;
 	prop->max_asid = MAX_ASID;
+	prop->num_of_events = GOYA_ASYNC_EVENT_ID_SIZE;
 	prop->cb_pool_cb_cnt = GOYA_CB_POOL_CB_CNT;
 	prop->cb_pool_cb_size = GOYA_CB_POOL_CB_SIZE;
 	prop->tpc_enabled_mask = TPC_ENABLED_MASK;
@@ -668,15 +701,10 @@ static void goya_init_dma_qman(struct hl_device *hdev, int dma_id,
 	WREG32(mmDMA_QM_0_PQ_CFG1 + reg_off, 0x00020002);
 	WREG32(mmDMA_QM_0_CQ_CFG1 + reg_off, 0x00080008);
 
-	if (dma_id == 0)
-		WREG32(mmDMA_QM_0_GLBL_PROT + reg_off, QMAN_DMA_FULLY_TRUSTED);
+	if (goya->hw_cap_initialized & HW_CAP_MMU)
+		WREG32(mmDMA_QM_0_GLBL_PROT + reg_off, QMAN_DMA_PARTLY_TRUSTED);
 	else
-		if (goya->hw_cap_initialized & HW_CAP_MMU)
-			WREG32(mmDMA_QM_0_GLBL_PROT + reg_off,
-					QMAN_DMA_PARTLY_TRUSTED);
-		else
-			WREG32(mmDMA_QM_0_GLBL_PROT + reg_off,
-					QMAN_DMA_FULLY_TRUSTED);
+		WREG32(mmDMA_QM_0_GLBL_PROT + reg_off, QMAN_DMA_FULLY_TRUSTED);
 
 	WREG32(mmDMA_QM_0_GLBL_ERR_CFG + reg_off, QMAN_DMA_ERR_MSG_EN);
 	WREG32(mmDMA_QM_0_GLBL_CFG0 + reg_off, QMAN_DMA_ENABLE);
@@ -870,6 +898,7 @@ static void goya_resume_external_queues(struct hl_device *hdev)
 int goya_init_cpu_queues(struct hl_device *hdev)
 {
 	struct goya_device *goya = hdev->asic_specific;
+	struct hl_eq *eq;
 	dma_addr_t bus_address;
 	u32 status;
 	struct hl_hw_queue *cpu_pq = &hdev->kernel_queues[GOYA_QUEUE_ID_CPU_PQ];
@@ -881,17 +910,24 @@ int goya_init_cpu_queues(struct hl_device *hdev)
 	if (goya->hw_cap_initialized & HW_CAP_CPU_Q)
 		return 0;
 
+	eq = &hdev->event_queue;
+
 	bus_address = cpu_pq->bus_address +
 			hdev->asic_prop.host_phys_base_address;
 	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_0, lower_32_bits(bus_address));
 	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_1, upper_32_bits(bus_address));
 
+	bus_address = eq->bus_address + hdev->asic_prop.host_phys_base_address;
+	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_2, lower_32_bits(bus_address));
+	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_3, upper_32_bits(bus_address));
+
 	bus_address = hdev->cpu_accessible_dma_address +
 			hdev->asic_prop.host_phys_base_address;
 	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_8, lower_32_bits(bus_address));
 	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_9, upper_32_bits(bus_address));
 
 	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_5, HL_QUEUE_SIZE_IN_BYTES);
+	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_4, HL_EQ_SIZE_IN_BYTES);
 	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_10, CPU_ACCESSIBLE_MEM_SIZE);
 
 	/* Used for EQ CI */
@@ -2781,6 +2817,163 @@ static void goya_resume_internal_queues(struct hl_device *hdev)
 	WREG32(mmTPC7_CMDQ_GLBL_CFG1, 0);
 }
 
+static void goya_dma_stall(struct hl_device *hdev)
+{
+	WREG32(mmDMA_QM_0_GLBL_CFG1, 1 << DMA_QM_0_GLBL_CFG1_DMA_STOP_SHIFT);
+	WREG32(mmDMA_QM_1_GLBL_CFG1, 1 << DMA_QM_1_GLBL_CFG1_DMA_STOP_SHIFT);
+	WREG32(mmDMA_QM_2_GLBL_CFG1, 1 << DMA_QM_2_GLBL_CFG1_DMA_STOP_SHIFT);
+	WREG32(mmDMA_QM_3_GLBL_CFG1, 1 << DMA_QM_3_GLBL_CFG1_DMA_STOP_SHIFT);
+	WREG32(mmDMA_QM_4_GLBL_CFG1, 1 << DMA_QM_4_GLBL_CFG1_DMA_STOP_SHIFT);
+}
+
+static void goya_tpc_stall(struct hl_device *hdev)
+{
+	WREG32(mmTPC0_CFG_TPC_STALL, 1 << TPC0_CFG_TPC_STALL_V_SHIFT);
+	WREG32(mmTPC1_CFG_TPC_STALL, 1 << TPC1_CFG_TPC_STALL_V_SHIFT);
+	WREG32(mmTPC2_CFG_TPC_STALL, 1 << TPC2_CFG_TPC_STALL_V_SHIFT);
+	WREG32(mmTPC3_CFG_TPC_STALL, 1 << TPC3_CFG_TPC_STALL_V_SHIFT);
+	WREG32(mmTPC4_CFG_TPC_STALL, 1 << TPC4_CFG_TPC_STALL_V_SHIFT);
+	WREG32(mmTPC5_CFG_TPC_STALL, 1 << TPC5_CFG_TPC_STALL_V_SHIFT);
+	WREG32(mmTPC6_CFG_TPC_STALL, 1 << TPC6_CFG_TPC_STALL_V_SHIFT);
+	WREG32(mmTPC7_CFG_TPC_STALL, 1 << TPC7_CFG_TPC_STALL_V_SHIFT);
+}
+
+static void goya_mme_stall(struct hl_device *hdev)
+{
+	WREG32(mmMME_STALL, 0xFFFFFFFF);
+}
+
+static int goya_enable_msix(struct hl_device *hdev)
+{
+	struct goya_device *goya = hdev->asic_specific;
+	int cq_cnt = hdev->asic_prop.completion_queues_count;
+	int rc, i, irq_cnt_init, irq;
+
+	if (goya->hw_cap_initialized & HW_CAP_MSIX)
+		return 0;
+
+	rc = pci_alloc_irq_vectors(hdev->pdev, GOYA_MSIX_ENTRIES,
+				GOYA_MSIX_ENTRIES, PCI_IRQ_MSIX);
+	if (rc < 0) {
+		dev_err(hdev->dev,
+			"MSI-X: Failed to enable support -- %d/%d\n",
+			GOYA_MSIX_ENTRIES, rc);
+		return rc;
+	}
+
+	for (i = 0, irq_cnt_init = 0 ; i < cq_cnt ; i++, irq_cnt_init++) {
+		irq = pci_irq_vector(hdev->pdev, i);
+		rc = request_irq(irq, hl_irq_handler_cq, 0, goya_irq_name[i],
+				&hdev->completion_queue[i]);
+		if (rc) {
+			dev_err(hdev->dev, "Failed to request IRQ %d", irq);
+			goto free_irqs;
+		}
+	}
+
+	irq = pci_irq_vector(hdev->pdev, EVENT_QUEUE_MSIX_IDX);
+
+	rc = request_irq(irq, hl_irq_handler_eq, 0,
+			goya_irq_name[EVENT_QUEUE_MSIX_IDX],
+			&hdev->event_queue);
+	if (rc) {
+		dev_err(hdev->dev, "Failed to request IRQ %d", irq);
+		goto free_irqs;
+	}
+
+	goya->hw_cap_initialized |= HW_CAP_MSIX;
+	return 0;
+
+free_irqs:
+	for (i = 0 ; i < irq_cnt_init ; i++)
+		free_irq(pci_irq_vector(hdev->pdev, i),
+			&hdev->completion_queue[i]);
+
+	pci_free_irq_vectors(hdev->pdev);
+	return rc;
+}
+
+static void goya_sync_irqs(struct hl_device *hdev)
+{
+	struct goya_device *goya = hdev->asic_specific;
+	int i;
+
+	if (!(goya->hw_cap_initialized & HW_CAP_MSIX))
+		return;
+
+	/* Wait for all pending IRQs to be finished */
+	for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
+		synchronize_irq(pci_irq_vector(hdev->pdev, i));
+
+	synchronize_irq(pci_irq_vector(hdev->pdev, EVENT_QUEUE_MSIX_IDX));
+}
+
+static void goya_disable_msix(struct hl_device *hdev)
+{
+	struct goya_device *goya = hdev->asic_specific;
+	int i, irq;
+
+	if (!(goya->hw_cap_initialized & HW_CAP_MSIX))
+		return;
+
+	goya_sync_irqs(hdev);
+
+	irq = pci_irq_vector(hdev->pdev, EVENT_QUEUE_MSIX_IDX);
+	free_irq(irq, &hdev->event_queue);
+
+	for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++) {
+		irq = pci_irq_vector(hdev->pdev, i);
+		free_irq(irq, &hdev->completion_queue[i]);
+	}
+
+	pci_free_irq_vectors(hdev->pdev);
+
+	goya->hw_cap_initialized &= ~HW_CAP_MSIX;
+}
+
+static void goya_halt_engines(struct hl_device *hdev, bool hard_reset)
+{
+	struct goya_device *goya = hdev->asic_specific;
+	u32 wait_timeout_ms, cpu_timeout_ms;
+
+	dev_info(hdev->dev,
+		"Halting compute engines and disabling interrupts\n");
+
+	if (hdev->pldm) {
+		wait_timeout_ms = GOYA_PLDM_RESET_WAIT_MSEC;
+		cpu_timeout_ms = GOYA_PLDM_RESET_WAIT_MSEC;
+	} else {
+		wait_timeout_ms = GOYA_RESET_WAIT_MSEC;
+		cpu_timeout_ms = GOYA_CPU_RESET_WAIT_MSEC;
+	}
+
+	if ((hard_reset) && (goya->hw_cap_initialized & HW_CAP_CPU)) {
+		WREG32(mmPSOC_GLOBAL_CONF_UBOOT_MAGIC, KMD_MSG_GOTO_WFE);
+		if (hdev->fw_loading)
+			WREG32(mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR,
+				GOYA_ASYNC_EVENT_ID_HALT_MACHINE);
+		msleep(cpu_timeout_ms);
+	}
+
+	goya_stop_external_queues(hdev);
+	goya_stop_internal_queues(hdev);
+
+	msleep(wait_timeout_ms);
+
+	goya_dma_stall(hdev);
+	goya_tpc_stall(hdev);
+	goya_mme_stall(hdev);
+
+	msleep(wait_timeout_ms);
+
+	goya_disable_external_queues(hdev);
+	goya_disable_internal_queues(hdev);
+
+	if (hard_reset)
+		goya_disable_msix(hdev);
+	else
+		goya_sync_irqs(hdev);
+}
 
 /**
  * goya_push_uboot_to_device - Push u-boot FW code to device
@@ -3166,11 +3359,16 @@ static int goya_hw_init(struct hl_device *hdev)
 
 	goya_init_tpc_qmans(hdev);
 
+	/* MSI-X must be enabled before CPU queues are initialized */
+	rc = goya_enable_msix(hdev);
+	if (rc)
+		goto disable_queues;
+
 	rc = goya_init_cpu_queues(hdev);
 	if (rc) {
 		dev_err(hdev->dev, "failed to initialize CPU H/W queues %d\n",
 			rc);
-		goto disable_queues;
+		goto disable_msix;
 	}
 
 	/* CPU initialization is finished, we can now move to 48 bit DMA mask */
@@ -3204,6 +3402,8 @@ static int goya_hw_init(struct hl_device *hdev)
 
 disable_pci_access:
 	goya_send_pci_access_msg(hdev, ARMCP_PACKET_DISABLE_PCI_ACCESS);
+disable_msix:
+	goya_disable_msix(hdev);
 disable_queues:
 	goya_disable_internal_queues(hdev);
 	goya_disable_external_queues(hdev);
@@ -3287,6 +3487,7 @@ static void goya_hw_fini(struct hl_device *hdev, bool hard_reset)
 					HW_CAP_DMA | HW_CAP_MME |
 					HW_CAP_MMU | HW_CAP_TPC_MBIST |
 					HW_CAP_GOLDEN | HW_CAP_TPC);
+	memset(goya->events_stat, 0, sizeof(goya->events_stat));
 
 	if (!hdev->pldm) {
 		int rc;
@@ -3772,6 +3973,305 @@ void goya_cpu_accessible_dma_pool_free(struct hl_device *hdev, size_t size,
 	gen_pool_free(hdev->cpu_accessible_dma_pool, (u64) vaddr, size);
 }
 
+static void goya_update_eq_ci(struct hl_device *hdev, u32 val)
+{
+	WREG32(mmPSOC_GLOBAL_CONF_SCRATCHPAD_6, val);
+}
+
+static void goya_get_axi_name(struct hl_device *hdev, u32 agent_id,
+		u16 event_type, char *axi_name, int len)
+{
+	if (!strcmp(goya_axi_name[agent_id], "DMA"))
+		if (event_type >= GOYA_ASYNC_EVENT_ID_DMA0_CH)
+			snprintf(axi_name, len, "DMA %d",
+				event_type - GOYA_ASYNC_EVENT_ID_DMA0_CH);
+		else
+			snprintf(axi_name, len, "DMA %d",
+				event_type - GOYA_ASYNC_EVENT_ID_DMA0_QM);
+	else
+		snprintf(axi_name, len, "%s", goya_axi_name[agent_id]);
+}
+
+static void goya_print_razwi_info(struct hl_device *hdev, u64 reg,
+		bool is_hbw, bool is_read, u16 event_type)
+{
+	u32 val, id, internal_id, agent_id, y, x;
+	char axi_name[10] = {0};
+
+	val = RREG32(reg);
+
+	if (is_hbw) {
+		id = (val & GOYA_IRQ_HBW_ID_MASK) >> GOYA_IRQ_HBW_ID_SHIFT;
+		internal_id = (val & GOYA_IRQ_HBW_INTERNAL_ID_MASK) >>
+				GOYA_IRQ_HBW_INTERNAL_ID_SHIFT;
+		agent_id = (val & GOYA_IRQ_HBW_AGENT_ID_MASK) >>
+				GOYA_IRQ_HBW_AGENT_ID_SHIFT;
+		y = (val & GOYA_IRQ_HBW_Y_MASK) >> GOYA_IRQ_HBW_Y_SHIFT;

drivers/misc/habanalabs/goya/goya.c void goya_cpu_accessible_dma_pool_free(struct hl_device *hdev, size_t size, · line 4019

Quoted 10 lines
drivers/misc/habanalabs/goya/goya.c +10 -0
+		x = (val & GOYA_IRQ_HBW_X_MASK) >> GOYA_IRQ_HBW_X_SHIFT;
+	} else {
+		id = (val & GOYA_IRQ_LBW_ID_MASK) >> GOYA_IRQ_LBW_ID_SHIFT;
+		internal_id = (val & GOYA_IRQ_LBW_INTERNAL_ID_MASK) >>
+				GOYA_IRQ_LBW_INTERNAL_ID_SHIFT;
+		agent_id = (val & GOYA_IRQ_LBW_AGENT_ID_MASK) >>
+				GOYA_IRQ_LBW_AGENT_ID_SHIFT;
+		y = (val & GOYA_IRQ_LBW_Y_MASK) >> GOYA_IRQ_LBW_Y_SHIFT;
+		x = (val & GOYA_IRQ_LBW_X_MASK) >> GOYA_IRQ_LBW_X_SHIFT;
+	}

It seems that only agent_id is used

Quoted 158 lines
drivers/misc/habanalabs/goya/goya.c +158 -0
+
+	if (agent_id >= GOYA_MAX_INITIATORS) {
+		dev_err(hdev->dev,
+			"Illegal %s %s with wrong initiator id %d, H/W IRQ %d\n",
+				is_read ? "read from" : "write to",
+				is_hbw ? "HBW" : "LBW",
+				agent_id,
+				event_type);
+	} else {
+		goya_get_axi_name(hdev, agent_id, event_type, axi_name,
+				sizeof(axi_name));
+		dev_err(hdev->dev, "Illegal %s by %s %s %s, H/W IRQ %d\n",
+				is_read ? "read" : "write",
+				axi_name,
+				is_read ? "from" : "to",
+				is_hbw ? "HBW" : "LBW",
+				event_type);
+	}
+}
+
+static void goya_print_irq_info(struct hl_device *hdev, u16 event_type)
+{
+	struct goya_device *goya = hdev->asic_specific;
+	bool is_hbw = false, is_read = false, is_info = false;
+
+	if (RREG32(mmDMA_MACRO_RAZWI_LBW_WT_VLD)) {
+		goya_print_razwi_info(hdev, mmDMA_MACRO_RAZWI_LBW_WT_ID, is_hbw,
+				is_read, event_type);
+		WREG32(mmDMA_MACRO_RAZWI_LBW_WT_VLD, 0);
+		is_info = true;
+	}
+	if (RREG32(mmDMA_MACRO_RAZWI_LBW_RD_VLD)) {
+		is_read = true;
+		goya_print_razwi_info(hdev, mmDMA_MACRO_RAZWI_LBW_RD_ID, is_hbw,
+				is_read, event_type);
+		WREG32(mmDMA_MACRO_RAZWI_LBW_RD_VLD, 0);
+		is_info = true;
+	}
+	if (RREG32(mmDMA_MACRO_RAZWI_HBW_WT_VLD)) {
+		is_hbw = true;
+		goya_print_razwi_info(hdev, mmDMA_MACRO_RAZWI_HBW_WT_ID, is_hbw,
+				is_read, event_type);
+		WREG32(mmDMA_MACRO_RAZWI_HBW_WT_VLD, 0);
+		is_info = true;
+	}
+	if (RREG32(mmDMA_MACRO_RAZWI_HBW_RD_VLD)) {
+		is_hbw = true;
+		is_read = true;
+		goya_print_razwi_info(hdev, mmDMA_MACRO_RAZWI_HBW_RD_ID, is_hbw,
+				is_read, event_type);
+		WREG32(mmDMA_MACRO_RAZWI_HBW_RD_VLD, 0);
+		is_info = true;
+	}
+	if (!is_info) {
+		dev_err(hdev->dev,
+			"Received H/W interrupt %d, no additional info\n",
+			event_type);
+		return;
+	}
+
+	if (goya->hw_cap_initialized & HW_CAP_MMU) {
+		u32 val = RREG32(mmMMU_PAGE_ERROR_CAPTURE);
+		u64 addr;
+
+		if (val & MMU_PAGE_ERROR_CAPTURE_ENTRY_VALID_MASK) {
+			addr = val & MMU_PAGE_ERROR_CAPTURE_VA_49_32_MASK;
+			addr <<= 32;
+			addr |= RREG32(mmMMU_PAGE_ERROR_CAPTURE_VA);
+
+			dev_err(hdev->dev, "MMU page fault on va 0x%llx\n",
+					addr);
+
+			WREG32(mmMMU_PAGE_ERROR_CAPTURE, 0);
+		}
+	}
+}
+
+static int goya_unmask_irq(struct hl_device *hdev, u16 event_type)
+{
+	struct armcp_packet pkt;
+	long result;
+	int rc;
+
+	memset(&pkt, 0, sizeof(pkt));
+
+	pkt.opcode = ARMCP_PACKET_UNMASK_RAZWI_IRQ;
+	pkt.value = event_type;
+
+	rc = hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &pkt, sizeof(pkt),
+			HL_DEVICE_TIMEOUT_USEC, &result);
+
+	if (rc)
+		dev_err(hdev->dev, "failed to unmask RAZWI IRQ %d", event_type);
+
+	return rc;
+}
+
+void goya_handle_eqe(struct hl_device *hdev, struct hl_eq_entry *eq_entry)
+{
+	u16 event_type = ((eq_entry->hdr.ctl & EQ_CTL_EVENT_TYPE_MASK)
+			>> EQ_CTL_EVENT_TYPE_SHIFT);
+	struct goya_device *goya = hdev->asic_specific;
+
+	goya->events_stat[event_type]++;
+
+	switch (event_type) {
+	case GOYA_ASYNC_EVENT_ID_PCIE_IF:
+	case GOYA_ASYNC_EVENT_ID_TPC0_ECC:
+	case GOYA_ASYNC_EVENT_ID_TPC1_ECC:
+	case GOYA_ASYNC_EVENT_ID_TPC2_ECC:
+	case GOYA_ASYNC_EVENT_ID_TPC3_ECC:
+	case GOYA_ASYNC_EVENT_ID_TPC4_ECC:
+	case GOYA_ASYNC_EVENT_ID_TPC5_ECC:
+	case GOYA_ASYNC_EVENT_ID_TPC6_ECC:
+	case GOYA_ASYNC_EVENT_ID_TPC7_ECC:
+	case GOYA_ASYNC_EVENT_ID_MME_ECC:
+	case GOYA_ASYNC_EVENT_ID_MME_ECC_EXT:
+	case GOYA_ASYNC_EVENT_ID_MMU_ECC:
+	case GOYA_ASYNC_EVENT_ID_DMA_MACRO:
+	case GOYA_ASYNC_EVENT_ID_DMA_ECC:
+	case GOYA_ASYNC_EVENT_ID_CPU_IF_ECC:
+	case GOYA_ASYNC_EVENT_ID_PSOC_MEM:
+	case GOYA_ASYNC_EVENT_ID_PSOC_CORESIGHT:
+	case GOYA_ASYNC_EVENT_ID_SRAM0:
+	case GOYA_ASYNC_EVENT_ID_SRAM1:
+	case GOYA_ASYNC_EVENT_ID_SRAM2:
+	case GOYA_ASYNC_EVENT_ID_SRAM3:
+	case GOYA_ASYNC_EVENT_ID_SRAM4:
+	case GOYA_ASYNC_EVENT_ID_SRAM5:
+	case GOYA_ASYNC_EVENT_ID_SRAM6:
+	case GOYA_ASYNC_EVENT_ID_SRAM7:
+	case GOYA_ASYNC_EVENT_ID_SRAM8:
+	case GOYA_ASYNC_EVENT_ID_SRAM9:
+	case GOYA_ASYNC_EVENT_ID_SRAM10:
+	case GOYA_ASYNC_EVENT_ID_SRAM11:
+	case GOYA_ASYNC_EVENT_ID_SRAM12:
+	case GOYA_ASYNC_EVENT_ID_SRAM13:
+	case GOYA_ASYNC_EVENT_ID_SRAM14:
+	case GOYA_ASYNC_EVENT_ID_SRAM15:
+	case GOYA_ASYNC_EVENT_ID_SRAM16:
+	case GOYA_ASYNC_EVENT_ID_SRAM17:
+	case GOYA_ASYNC_EVENT_ID_SRAM18:
+	case GOYA_ASYNC_EVENT_ID_SRAM19:
+	case GOYA_ASYNC_EVENT_ID_SRAM20:
+	case GOYA_ASYNC_EVENT_ID_SRAM21:
+	case GOYA_ASYNC_EVENT_ID_SRAM22:
+	case GOYA_ASYNC_EVENT_ID_SRAM23:
+	case GOYA_ASYNC_EVENT_ID_SRAM24:
+	case GOYA_ASYNC_EVENT_ID_SRAM25:
+	case GOYA_ASYNC_EVENT_ID_SRAM26:
+	case GOYA_ASYNC_EVENT_ID_SRAM27:
+	case GOYA_ASYNC_EVENT_ID_SRAM28:
+	case GOYA_ASYNC_EVENT_ID_SRAM29:
+	case GOYA_ASYNC_EVENT_ID_GIC500:
+	case GOYA_ASYNC_EVENT_ID_PLL0:
+	case GOYA_ASYNC_EVENT_ID_PLL1:
+	case GOYA_ASYNC_EVENT_ID_PLL3:
+	case GOYA_ASYNC_EVENT_ID_PLL4:

drivers/misc/habanalabs/goya/goya.c void goya_cpu_accessible_dma_pool_free(struct hl_device *hdev, size_t size, · line 4187

Quoted 10 lines
drivers/misc/habanalabs/goya/goya.c +10 -0
+	case GOYA_ASYNC_EVENT_ID_PLL5:
+	case GOYA_ASYNC_EVENT_ID_PLL6:
+	case GOYA_ASYNC_EVENT_ID_AXI_ECC:
+	case GOYA_ASYNC_EVENT_ID_L2_RAM_ECC:
+	case GOYA_ASYNC_EVENT_ID_PSOC_GPIO_05_SW_RESET:
+	case GOYA_ASYNC_EVENT_ID_PSOC_GPIO_10_VRHOT_ICRIT:
+		dev_err(hdev->dev,
+			"Received H/W interrupt %d, reset the chip\n",
+			event_type);
+		break;

Looks tough. Any chance some of these values are consecutive and can be grouped, e.g

case GOYA_ASYNC_EVENT_ID_SRAM0 ... GOYA_ASYNC_EVENT_ID_SRAM29:
?

Quoted 346 lines
drivers/misc/habanalabs/goya/goya.c +91 -0
+
+	case GOYA_ASYNC_EVENT_ID_PCIE_DEC:
+	case GOYA_ASYNC_EVENT_ID_TPC0_DEC:
+	case GOYA_ASYNC_EVENT_ID_TPC1_DEC:
+	case GOYA_ASYNC_EVENT_ID_TPC2_DEC:
+	case GOYA_ASYNC_EVENT_ID_TPC3_DEC:
+	case GOYA_ASYNC_EVENT_ID_TPC4_DEC:
+	case GOYA_ASYNC_EVENT_ID_TPC5_DEC:
+	case GOYA_ASYNC_EVENT_ID_TPC6_DEC:
+	case GOYA_ASYNC_EVENT_ID_TPC7_DEC:
+	case GOYA_ASYNC_EVENT_ID_MME_WACS:
+	case GOYA_ASYNC_EVENT_ID_MME_WACSD:
+	case GOYA_ASYNC_EVENT_ID_CPU_AXI_SPLITTER:
+	case GOYA_ASYNC_EVENT_ID_PSOC_AXI_DEC:
+	case GOYA_ASYNC_EVENT_ID_PSOC:
+	case GOYA_ASYNC_EVENT_ID_TPC0_KRN_ERR:
+	case GOYA_ASYNC_EVENT_ID_TPC1_KRN_ERR:
+	case GOYA_ASYNC_EVENT_ID_TPC2_KRN_ERR:
+	case GOYA_ASYNC_EVENT_ID_TPC3_KRN_ERR:
+	case GOYA_ASYNC_EVENT_ID_TPC4_KRN_ERR:
+	case GOYA_ASYNC_EVENT_ID_TPC5_KRN_ERR:
+	case GOYA_ASYNC_EVENT_ID_TPC6_KRN_ERR:
+	case GOYA_ASYNC_EVENT_ID_TPC7_KRN_ERR:
+	case GOYA_ASYNC_EVENT_ID_TPC0_CMDQ:
+	case GOYA_ASYNC_EVENT_ID_TPC1_CMDQ:
+	case GOYA_ASYNC_EVENT_ID_TPC2_CMDQ:
+	case GOYA_ASYNC_EVENT_ID_TPC3_CMDQ:
+	case GOYA_ASYNC_EVENT_ID_TPC4_CMDQ:
+	case GOYA_ASYNC_EVENT_ID_TPC5_CMDQ:
+	case GOYA_ASYNC_EVENT_ID_TPC6_CMDQ:
+	case GOYA_ASYNC_EVENT_ID_TPC7_CMDQ:
+	case GOYA_ASYNC_EVENT_ID_TPC0_QM:
+	case GOYA_ASYNC_EVENT_ID_TPC1_QM:
+	case GOYA_ASYNC_EVENT_ID_TPC2_QM:
+	case GOYA_ASYNC_EVENT_ID_TPC3_QM:
+	case GOYA_ASYNC_EVENT_ID_TPC4_QM:
+	case GOYA_ASYNC_EVENT_ID_TPC5_QM:
+	case GOYA_ASYNC_EVENT_ID_TPC6_QM:
+	case GOYA_ASYNC_EVENT_ID_TPC7_QM:
+	case GOYA_ASYNC_EVENT_ID_MME_QM:
+	case GOYA_ASYNC_EVENT_ID_MME_CMDQ:
+	case GOYA_ASYNC_EVENT_ID_DMA0_QM:
+	case GOYA_ASYNC_EVENT_ID_DMA1_QM:
+	case GOYA_ASYNC_EVENT_ID_DMA2_QM:
+	case GOYA_ASYNC_EVENT_ID_DMA3_QM:
+	case GOYA_ASYNC_EVENT_ID_DMA4_QM:
+	case GOYA_ASYNC_EVENT_ID_DMA0_CH:
+	case GOYA_ASYNC_EVENT_ID_DMA1_CH:
+	case GOYA_ASYNC_EVENT_ID_DMA2_CH:
+	case GOYA_ASYNC_EVENT_ID_DMA3_CH:
+	case GOYA_ASYNC_EVENT_ID_DMA4_CH:
+		goya_print_irq_info(hdev, event_type);
+		goya_unmask_irq(hdev, event_type);
+		break;
+
+	case GOYA_ASYNC_EVENT_ID_TPC0_BMON_SPMU:
+	case GOYA_ASYNC_EVENT_ID_TPC1_BMON_SPMU:
+	case GOYA_ASYNC_EVENT_ID_TPC2_BMON_SPMU:
+	case GOYA_ASYNC_EVENT_ID_TPC3_BMON_SPMU:
+	case GOYA_ASYNC_EVENT_ID_TPC4_BMON_SPMU:
+	case GOYA_ASYNC_EVENT_ID_TPC5_BMON_SPMU:
+	case GOYA_ASYNC_EVENT_ID_TPC6_BMON_SPMU:
+	case GOYA_ASYNC_EVENT_ID_TPC7_BMON_SPMU:
+	case GOYA_ASYNC_EVENT_ID_DMA_BM_CH0:
+	case GOYA_ASYNC_EVENT_ID_DMA_BM_CH1:
+	case GOYA_ASYNC_EVENT_ID_DMA_BM_CH2:
+	case GOYA_ASYNC_EVENT_ID_DMA_BM_CH3:
+	case GOYA_ASYNC_EVENT_ID_DMA_BM_CH4:
+		dev_info(hdev->dev, "Received H/W interrupt %d\n", event_type);
+		break;
+
+	default:
+		dev_err(hdev->dev, "Received invalid H/W interrupt %d\n",
+				event_type);
+		break;
+	}
+}
+
+void *goya_get_events_stat(struct hl_device *hdev, u32 *size)
+{
+	struct goya_device *goya = hdev->asic_specific;
+
+	*size = (u32) sizeof(goya->events_stat);
+
+	return goya->events_stat;
+}
+
 
 static void goya_hw_queues_lock(struct hl_device *hdev)
 {
@@ -3794,6 +4294,7 @@ static const struct hl_asic_funcs goya_funcs = {
 	.sw_fini = goya_sw_fini,
 	.hw_init = goya_hw_init,
 	.hw_fini = goya_hw_fini,
+	.halt_engines = goya_halt_engines,
 	.suspend = goya_suspend,
 	.resume = goya_resume,
 	.mmap = goya_mmap,
@@ -3808,6 +4309,9 @@ static const struct hl_asic_funcs goya_funcs = {
 	.dma_pool_free = goya_dma_pool_free,
 	.cpu_accessible_dma_pool_alloc = goya_cpu_accessible_dma_pool_alloc,
 	.cpu_accessible_dma_pool_free = goya_cpu_accessible_dma_pool_free,
+	.update_eq_ci = goya_update_eq_ci,
+	.handle_eqe = goya_handle_eqe,
+	.get_events_stat = goya_get_events_stat,
 	.hw_queues_lock = goya_hw_queues_lock,
 	.hw_queues_unlock = goya_hw_queues_unlock,
 	.send_cpu_message = goya_send_cpu_message
drivers/misc/habanalabs/goya/goyaP.h +1 -0
index 598a718d3df1..c6bfcb6c6905 100644
@@ -123,6 +123,7 @@ struct goya_device {
 	/* TODO: remove hw_queues_lock after moving to scheduler code */
 	spinlock_t	hw_queues_lock;
 	u64		ddr_bar_cur_addr;
+	u32		events_stat[GOYA_ASYNC_EVENT_ID_SIZE];
 	u32		hw_cap_initialized;
 };
 
drivers/misc/habanalabs/habanalabs.h +37 -0
index 8232e2259463..899bf98eb002 100644
@@ -83,6 +83,7 @@ struct hw_queue_properties {
  * @cfg_size: configuration space size on SRAM.
  * @sram_size: total size of SRAM.
  * @max_asid: maximum number of open contexts (ASIDs).
+ * @num_of_events: number of possible internal H/W IRQs.
  * @completion_queues_count: number of completion queues.
  * @high_pll: high PLL frequency used by the device.
  * @cb_pool_cb_cnt: number of CBs in the CB pool.
@@ -109,6 +110,7 @@ struct asic_fixed_properties {
 	u32			cfg_size;
 	u32			sram_size;
 	u32			max_asid;
+	u32			num_of_events;
 	u32			high_pll;
 	u32			cb_pool_cb_cnt;
 	u32			cb_pool_cb_size;
@@ -209,6 +211,9 @@ struct hl_cs_job;
 #define HL_CQ_LENGTH			HL_QUEUE_LENGTH
 #define HL_CQ_SIZE_IN_BYTES		(HL_CQ_LENGTH * HL_CQ_ENTRY_SIZE)
 
+/* Must be power of 2 (HL_PAGE_SIZE / HL_EQ_ENTRY_SIZE) */
+#define HL_EQ_LENGTH			64
+#define HL_EQ_SIZE_IN_BYTES		(HL_EQ_LENGTH * HL_EQ_ENTRY_SIZE)
 
 
 /**
@@ -256,6 +261,20 @@ struct hl_cq {
 	atomic_t		free_slots_cnt;
 };
 
+/**
+ * struct hl_eq - describes the event queue (single one per device)
+ * @hdev: pointer to the device structure
+ * @kernel_address: holds the queue's kernel virtual address
+ * @bus_address: holds the queue's DMA address
+ * @ci: ci inside the queue
+ */
+struct hl_eq {
+	struct hl_device	*hdev;
+	u64			kernel_address;
+	dma_addr_t		bus_address;
+	u32			ci;
+};
+
 
 
 
@@ -288,6 +307,9 @@ enum hl_asic_type {
  * @sw_fini: tears down driver state, does not configure H/W.
  * @hw_init: sets up the H/W state.
  * @hw_fini: tears down the H/W state.
+ * @halt_engines: halt engines, needed for reset sequence. This also disables
+ *                interrupts from the device. Should be called before
+ *                hw_fini and before CS rollback.
  * @suspend: handles IP specific H/W or SW changes for suspend.
  * @resume: handles IP specific H/W or SW changes for resume.
  * @mmap: mmap function, does nothing.
@@ -303,6 +325,9 @@ enum hl_asic_type {
  * @dma_pool_free: free small DMA allocation from pool.
  * @cpu_accessible_dma_pool_alloc: allocate CPU PQ packet from DMA pool.
  * @cpu_accessible_dma_pool_free: free CPU PQ packet from DMA pool.
+ * @update_eq_ci: update event queue CI.
+ * @handle_eqe: handle event queue entry (IRQ) from ArmCP.
+ * @get_events_stat: retrieve event queue entries histogram.
  * @hw_queues_lock: acquire H/W queues lock.
  * @hw_queues_unlock: release H/W queues lock.
  * @send_cpu_message: send buffer to ArmCP.
@@ -314,6 +339,7 @@ struct hl_asic_funcs {
 	int (*sw_fini)(struct hl_device *hdev);
 	int (*hw_init)(struct hl_device *hdev);
 	void (*hw_fini)(struct hl_device *hdev, bool hard_reset);
+	void (*halt_engines)(struct hl_device *hdev, bool hard_reset);
 	int (*suspend)(struct hl_device *hdev);
 	int (*resume)(struct hl_device *hdev);
 	int (*mmap)(struct hl_fpriv *hpriv, struct vm_area_struct *vma);
@@ -336,6 +362,10 @@ struct hl_asic_funcs {
 				size_t size, dma_addr_t *dma_handle);
 	void (*cpu_accessible_dma_pool_free)(struct hl_device *hdev,
 				size_t size, void *vaddr);
+	void (*update_eq_ci)(struct hl_device *hdev, u32 val);
+	void (*handle_eqe)(struct hl_device *hdev,
+				struct hl_eq_entry *eq_entry);
+	void* (*get_events_stat)(struct hl_device *hdev, u32 *size);
 	void (*hw_queues_lock)(struct hl_device *hdev);
 	void (*hw_queues_unlock)(struct hl_device *hdev);
 	int (*send_cpu_message)(struct hl_device *hdev, u32 *msg,
@@ -474,6 +504,7 @@ void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
  * @kernel_ctx: KMD context structure.
  * @kernel_queues: array of hl_hw_queue.
  * @kernel_cb_mgr: command buffer manager for creating/destroying/handling CGs.
+ * @event_queue: event queue for IRQ from ArmCP.
  * @dma_pool: DMA pool for small allocations.
  * @cpu_accessible_dma_mem: KMD <-> ArmCP shared memory CPU address.
  * @cpu_accessible_dma_address: KMD <-> ArmCP shared memory DMA address.
@@ -504,9 +535,11 @@ struct hl_device {
 	enum hl_asic_type		asic_type;
 	struct hl_cq			*completion_queue;
 	struct workqueue_struct		*cq_wq;
+	struct workqueue_struct		*eq_wq;
 	struct hl_ctx			*kernel_ctx;
 	struct hl_hw_queue		*kernel_queues;
 	struct hl_cb_mgr		kernel_cb_mgr;
+	struct hl_eq			event_queue;
 	struct dma_pool			*dma_pool;
 	void				*cpu_accessible_dma_mem;
 	dma_addr_t			cpu_accessible_dma_address;
@@ -593,6 +626,10 @@ void hl_hw_queue_inc_ci_kernel(struct hl_device *hdev, u32 hw_queue_id);
 
 int hl_cq_init(struct hl_device *hdev, struct hl_cq *q, u32 hw_queue_id);
 void hl_cq_fini(struct hl_device *hdev, struct hl_cq *q);
+int hl_eq_init(struct hl_device *hdev, struct hl_eq *q);
+void hl_eq_fini(struct hl_device *hdev, struct hl_eq *q);
+irqreturn_t hl_irq_handler_cq(int irq, void *arg);
+irqreturn_t hl_irq_handler_eq(int irq, void *arg);
 int hl_asid_init(struct hl_device *hdev);
 void hl_asid_fini(struct hl_device *hdev);
 unsigned long hl_asid_alloc(struct hl_device *hdev);
drivers/misc/habanalabs/include/goya/goya.h +0 -1
index 2d0efb7b44bb..bcc461760e5f 100644
@@ -65,7 +65,6 @@
 
 #define GOYA_MSIX_ENTRIES	8
 #define EVENT_QUEUE_MSIX_IDX	5
-#define ARMCP_RESET_MSIX_IDX	6
 
 #define QMAN_PQ_ENTRY_SIZE	16			/* Bytes */
 
drivers/misc/habanalabs/irq.c +71 -0
index 97b0de7ea5c2..9586323e7dfb 100644
@@ -9,6 +9,18 @@
 
 #include <linux/dma-mapping.h>
 
+/**
+ * This structure is used to schedule work of EQ entry and armcp_reset event
+ *
+ * @eq_work          - workqueue object to run when EQ entry is received
+ * @hdev             - pointer to device structure
+ * @eq_entry         - copy of the EQ entry
+ */
+struct hl_eqe_work {
+	struct work_struct	eq_work;
+	struct hl_device	*hdev;
+	struct hl_eq_entry	eq_entry;
+};
 
 /**
  * hl_cq_inc_ptr - increment ci or pi of cq
@@ -26,6 +38,33 @@ inline u32 hl_cq_inc_ptr(u32 ptr)
 	return ptr;
 }
 
+/**
+ * hl_eq_inc_ptr - increment ci of eq
+ *
+ * @ptr: the current ci value of the event queue
+ *
+ * Increment ptr by 1. If it reaches the number of event queue
+ * entries, set it to 0
+ */
+inline u32 hl_eq_inc_ptr(u32 ptr)
+{
+	ptr++;
+	if (unlikely(ptr == HL_EQ_LENGTH))
+		ptr = 0;
+	return ptr;
+}
+
+static void irq_handle_eqe(struct work_struct *work)
+{
+	struct hl_eqe_work *eqe_work = container_of(work, struct hl_eqe_work,
+							eq_work);
+	struct hl_device *hdev = eqe_work->hdev;
+
+	hdev->asic_funcs->handle_eqe(hdev, &eqe_work->eq_entry);
+
+	kfree(eqe_work);
+}
+
 /**
  * hl_irq_handler_cq - irq handler for completion queue
  *
@@ -103,6 +142,68 @@ irqreturn_t hl_irq_handler_cq(int irq, void *arg)
 	return IRQ_HANDLED;
 }
 
+/**
+ * hl_irq_handler_eq - irq handler for event queue
+ *
+ * @irq: irq number
+ * @arg: pointer to event queue structure
+ *
+ */
+irqreturn_t hl_irq_handler_eq(int irq, void *arg)
+{
+	struct hl_eq *eq = arg;
+	struct hl_device *hdev = eq->hdev;
+	struct hl_eq_entry *eq_entry;
+	struct hl_eq_entry *eq_base;
+	struct hl_eqe_work *handle_eqe_work;
+
+	eq_base = (struct hl_eq_entry *) eq->kernel_address;
+
+	while (1) {
+		bool entry_ready =
+				((eq_base[eq->ci].hdr.ctl & EQ_CTL_READY_MASK)
+						>> EQ_CTL_READY_SHIFT);
+
+		if (!entry_ready)
+			break;
+
+		eq_entry = &eq_base[eq->ci];
+
+		/*
+		 * Make sure we read EQ entry contents after we've
+		 * checked the ownership bit.
+		 */
+		dma_rmb();

drivers/misc/habanalabs/irq.c irqreturn_t hl_irq_handler_cq(int irq, void *arg) · line 186

Quoted 10 lines
drivers/misc/habanalabs/irq.c +10 -0
+
+		if (hdev->disabled) {
+			dev_warn(hdev->dev,
+				"Device disabled but received IRQ %d for EQ\n",
+					irq);
+			goto skip_irq;
+		}
+
+		handle_eqe_work = kmalloc(sizeof(*handle_eqe_work), GFP_ATOMIC);
+		if (handle_eqe_work) {

I couldn't find where is it freed

Quoted 73 lines
drivers/misc/habanalabs/irq.c +63 -0
+			INIT_WORK(&handle_eqe_work->eq_work, irq_handle_eqe);
+			handle_eqe_work->hdev = hdev;
+
+			memcpy(&handle_eqe_work->eq_entry, eq_entry,
+					sizeof(*eq_entry));
+
+			queue_work(hdev->eq_wq, &handle_eqe_work->eq_work);
+		}
+skip_irq:
+		/* Clear EQ entry ready bit */
+		eq_entry->hdr.ctl &= ~EQ_CTL_READY_MASK;
+
+		eq->ci = hl_eq_inc_ptr(eq->ci);
+
+		hdev->asic_funcs->update_eq_ci(hdev, eq->ci);
+	}
+
+	return IRQ_HANDLED;
+}
+
 /**
  * hl_cq_init - main initialization function for an cq object
  *
@@ -148,3 +249,46 @@ void hl_cq_fini(struct hl_device *hdev, struct hl_cq *q)
 	hdev->asic_funcs->dma_free_coherent(hdev, HL_CQ_SIZE_IN_BYTES,
 			(void *) q->kernel_address, q->bus_address);
 }
+
+/**
+ * hl_eq_init - main initialization function for an event queue object
+ *
+ * @hdev: pointer to device structure
+ * @q: pointer to eq structure
+ *
+ * Allocate dma-able memory for the event queue and initialize fields
+ * Returns 0 on success
+ */
+int hl_eq_init(struct hl_device *hdev, struct hl_eq *q)
+{
+	void *p;
+
+	BUILD_BUG_ON(HL_EQ_SIZE_IN_BYTES > HL_PAGE_SIZE);
+
+	p = hdev->asic_funcs->dma_alloc_coherent(hdev, HL_EQ_SIZE_IN_BYTES,
+				&q->bus_address, GFP_KERNEL | __GFP_ZERO);
+	if (!p)
+		return -ENOMEM;
+
+	q->hdev = hdev;
+	q->kernel_address = (u64) p;
+	q->ci = 0;
+
+	return 0;
+}
+
+/**
+ * hl_eq_fini - destroy event queue
+ *
+ * @hdev: pointer to device structure
+ * @q: pointer to eq structure
+ *
+ * Free the event queue memory
+ */
+void hl_eq_fini(struct hl_device *hdev, struct hl_eq *q)
+{
+	flush_workqueue(hdev->eq_wq);
+
+	hdev->asic_funcs->dma_free_coherent(hdev, HL_EQ_SIZE_IN_BYTES,
+			(void *) q->kernel_address, q->bus_address);
+}
Signature · 1 line
2.17.1
Signature · 2 lines
Sincerely yours,
Mike.
#39 lore raw

Re: [PATCH 09/15] habanalabs: add sysfs and hwmon support

In reply to Oded Gabbay
Quoted 389 lines · Oded Gabbay

This patch add the sysfs and hwmon entries that are exposed by the driver.

Goya has several sensors, from various categories such as temperature, voltage, current, etc. The driver exposes those sensors in the standard hwmon mechanism.

In addition, the driver exposes a couple of interfaces in sysfs, both for configuration and for providing status of the device or driver.

The configuration attributes is for Power Management:
- Automatic or manual
- Frequency value when moving to high frequency mode
- Maximum power the device is allowed to consume

The rest of the attributes are read-only and provide the following information:
- Versions of the various firmwares running on the device
- Contents of the device's EEPROM
- The device type (currently only Goya is supported)
- PCI address of the device (to allow user-space to connect between /dev/hlX to PCI address)
- Status of the device (operational, malfunction, in_reset)
- How many processes are open on the device's file

---
 .../ABI/testing/sysfs-driver-habanalabs       | 190 ++++++
 drivers/misc/habanalabs/Makefile              |   2 +-
 drivers/misc/habanalabs/device.c              | 146 +++++
 drivers/misc/habanalabs/goya/Makefile         |   2 +-
 drivers/misc/habanalabs/goya/goya.c           | 230 +++++++
 drivers/misc/habanalabs/goya/goyaP.h          |  21 +
 drivers/misc/habanalabs/goya/goya_hwmgr.c     | 306 +++++++++
 drivers/misc/habanalabs/habanalabs.h          |  97 +++
 drivers/misc/habanalabs/habanalabs_drv.c      |   7 +
 drivers/misc/habanalabs/hwmon.c               | 449 +++++++++++++
 drivers/misc/habanalabs/sysfs.c               | 588 ++++++++++++++++++
 11 files changed, 2036 insertions(+), 2 deletions(-)
 create mode 100644 Documentation/ABI/testing/sysfs-driver-habanalabs
 create mode 100644 drivers/misc/habanalabs/goya/goya_hwmgr.c
 create mode 100644 drivers/misc/habanalabs/hwmon.c
 create mode 100644 drivers/misc/habanalabs/sysfs.c
Documentation/ABI/testing/sysfs-driver-habanalabs new file +190 -0
new file mode 100644
index 000000000000..19edd4da87c1
@@ -0,0 +1,190 @@
+What:           /sys/class/habanalabs/hl<n>/armcp_kernel_ver
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Version of the Linux kernel running on the device's CPU
+
+What:           /sys/class/habanalabs/hl<n>/armcp_ver
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Version of the application running on the device's CPU
+
+What:           /sys/class/habanalabs/hl<n>/cpld_ver
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Version of the Device's CPLD F/W
+
+What:           /sys/class/habanalabs/hl<n>/device_type
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Displays the code name of the device according to its type.
+                The supported values are: "GOYA"
+
+What:           /sys/class/habanalabs/hl<n>/eeprom
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    A binary file attribute that contains the contents of the
+                on-board EEPROM
+
+What:           /sys/class/habanalabs/hl<n>/fuse_ver
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Displays the device's version from the eFuse
+
+What:           /sys/class/habanalabs/hl<n>/hard_reset
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Interface to trigger a hard-reset operation for the device.
+                Hard-reset will reset ALL internal components of the device
+                except for the PCI interface and the internal PLLs
+
+What:           /sys/class/habanalabs/hl<n>/hard_reset_cnt
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Displays how many times the device have undergone a hard-reset
+                operation
+
+What:           /sys/class/habanalabs/hl<n>/high_pll
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Allows the user to set the maximum clock frequency for MME, TPC
+                and IC when the power management profile is set to "automatic".
+
+What:           /sys/class/habanalabs/hl<n>/ic_clk
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Allows the user to set the maximum clock frequency of the
+                Interconnect fabric. Writes to this parameter affect the device
+                only when the power management profile is set to "manual" mode.
+                The device IC clock might be set to lower value then the
+                maximum. The user should read the ic_clk_curr to see the actual
+                frequency value of the IC
+
+What:           /sys/class/habanalabs/hl<n>/ic_clk_curr
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Displays the current clock frequency of the Interconnect fabric
+
+What:           /sys/class/habanalabs/hl<n>/infineon_ver
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Version of the Device's power supply F/W code
+
+What:           /sys/class/habanalabs/hl<n>/max_power
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Allows the user to set the maximum power consumption of the
+                device in milliwatts.
+
+What:           /sys/class/habanalabs/hl<n>/mme_clk
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Allows the user to set the maximum clock frequency of the
+                MME compute engine. Writes to this parameter affect the device
+                only when the power management profile is set to "manual" mode.
+                The device MME clock might be set to lower value then the
+                maximum. The user should read the mme_clk_curr to see the actual
+                frequency value of the MME
+
+What:           /sys/class/habanalabs/hl<n>/mme_clk_curr
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Displays the current clock frequency of the MME compute engine
+
+What:           /sys/class/habanalabs/hl<n>/pci_addr
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Displays the PCI address of the device. This is needed so the
+                user would be able to open a device based on its PCI address
+
+What:           /sys/class/habanalabs/hl<n>/pm_mng_profile
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Power management profile. Values are "auto", "manual". In "auto"
+                mode, the driver will set the maximum clock frequency to a high
+                value when a user-space process opens the device's file (unless
+                it was already opened by another process). The driver will set
+                the max clock frequency to a low value when there are no user
+                processes that are opened on the device's file. In "manual"
+                mode, the user sets the maximum clock frequency by writing to
+                ic_clk, mme_clk and tpc_clk
+
+
+What:           /sys/class/habanalabs/hl<n>/preboot_btl_ver
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Version of the device's preboot F/W code
+
+What:           /sys/class/habanalabs/hl<n>/soft_reset
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Interface to trigger a soft-reset operation for the device.
+                Soft-reset will reset only the compute and DMA engines of the
+                device
+
+What:           /sys/class/habanalabs/hl<n>/soft_reset_cnt
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Displays how many times the device have undergone a soft-reset
+                operation
+
+What:           /sys/class/habanalabs/hl<n>/status
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Status of the card: "Operational", "Malfunction", "In reset".
+
+What:           /sys/class/habanalabs/hl<n>/thermal_ver
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Version of the Device's thermal daemon
+
+What:           /sys/class/habanalabs/hl<n>/tpc_clk
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Allows the user to set the maximum clock frequency of the
+                TPC compute engines. Writes to this parameter affect the device
+                only when the power management profile is set to "manual" mode.
+                The device TPC clock might be set to lower value then the
+                maximum. The user should read the tpc_clk_curr to see the actual
+                frequency value of the TPC
+
+What:           /sys/class/habanalabs/hl<n>/tpc_clk_curr
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Displays the current clock frequency of the TPC compute engines
+
+What:           /sys/class/habanalabs/hl<n>/uboot_ver
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Version of the u-boot running on the device's CPU
+
+What:           /sys/class/habanalabs/hl<n>/write_open_cnt
+Date:           Jan 2019
+KernelVersion:  5.1
+Contact:        [email protected]
+Description:    Displays the total number of user processes that are currently
+                opened on the device's file
drivers/misc/habanalabs/Makefile +1 -1
index c07f3ccb57dc..b5607233d216 100644
@@ -5,7 +5,7 @@
 obj-m	:= habanalabs.o
 
 habanalabs-y := habanalabs_drv.o device.o context.o asid.o habanalabs_ioctl.o \
-		command_buffer.o hw_queue.o irq.o
+		command_buffer.o hw_queue.o irq.o sysfs.o hwmon.o
 
 include $(src)/goya/Makefile
 habanalabs-y += $(HL_GOYA_FILES)
drivers/misc/habanalabs/device.c +118 -0
index 9199e070e79e..ff7b610f18c4 100644
@@ -226,6 +226,118 @@ static void device_early_fini(struct hl_device *hdev)
 	mutex_destroy(&hdev->device_open);
 }
 
+static void set_freq_to_low_job(struct work_struct *work)
+{
+	struct hl_device *hdev = container_of(work, struct hl_device,
+						work_freq.work);
+
+	if (atomic_read(&hdev->fd_open_cnt) == 0)
+		hl_device_set_frequency(hdev, PLL_LOW);
+
+	schedule_delayed_work(&hdev->work_freq,
+			usecs_to_jiffies(HL_PLL_LOW_JOB_FREQ_USEC));
+}
+
+/**
+ * device_late_init - do late stuff initialization for the habanalabs device
+ *
+ * @hdev: pointer to habanalabs device structure
+ *
+ * Do stuff that either needs the device H/W queues to be active or needs
+ * to happen after all the rest of the initialization is finished
+ */
+static int device_late_init(struct hl_device *hdev)
+{
+	int rc;
+
+	INIT_DELAYED_WORK(&hdev->work_freq, set_freq_to_low_job);
+	hdev->high_pll = hdev->asic_prop.high_pll;
+
+	/* force setting to low frequency */
+	atomic_set(&hdev->curr_pll_profile, PLL_LOW);
+
+	if (hdev->pm_mng_profile == PM_AUTO)
+		hdev->asic_funcs->set_pll_profile(hdev, PLL_LOW);
+	else
+		hdev->asic_funcs->set_pll_profile(hdev, PLL_LAST);
+
+	if (hdev->asic_funcs->late_init) {
+		rc = hdev->asic_funcs->late_init(hdev);
+		if (rc) {
+			dev_err(hdev->dev,
+				"failed late initialization for the H/W\n");
+			return rc;
+		}
+	}
+
+	schedule_delayed_work(&hdev->work_freq,
+			usecs_to_jiffies(HL_PLL_LOW_JOB_FREQ_USEC));
+
+	hdev->late_init_done = true;
+
+	return 0;
+}
+
+/**
+ * device_late_fini - finalize all that was done in device_late_init
+ *
+ * @hdev: pointer to habanalabs device structure
+ *
+ */
+static void device_late_fini(struct hl_device *hdev)
+{
+	if (!hdev->late_init_done)
+		return;
+
+	cancel_delayed_work_sync(&hdev->work_freq);
+
+	if (hdev->asic_funcs->late_fini)
+		hdev->asic_funcs->late_fini(hdev);
+
+	hdev->late_init_done = false;
+}
+
+/**
+ * hl_device_set_frequency - set the frequency of the device
+ *
+ * @hdev: pointer to habanalabs device structure
+ * @freq: the new frequency value
+ *
+ * Change the frequency if needed.
+ * We allose to set PLL to low only if there is no user process
+ * Returns 0 if no change was done, otherwise returns 1;
+ */
+int hl_device_set_frequency(struct hl_device *hdev, enum hl_pll_frequency freq)
+{
+	enum hl_pll_frequency old_freq =
+			(freq == PLL_HIGH) ? PLL_LOW : PLL_HIGH;
+	int ret;
+
+	if (hdev->pm_mng_profile == PM_MANUAL)
+		return 0;
+
+	ret = atomic_cmpxchg(&hdev->curr_pll_profile, old_freq, freq);
+	if (ret == freq)
+		return 0;
+
+	/*
+	 * in case we want to lower frequency, check if device is not
+	 * opened. We must have a check here to workaround race condition with
+	 * hl_device_open
+	 */
+	if ((freq == PLL_LOW) && (atomic_read(&hdev->fd_open_cnt) > 0)) {
+		atomic_set(&hdev->curr_pll_profile, PLL_HIGH);
+		return 0;
+	}
+
+	dev_dbg(hdev->dev, "Changing device frequency to %s\n",
+		freq == PLL_HIGH ? "high" : "low");
+
+	hdev->asic_funcs->set_pll_profile(hdev, freq);
+
+	return 1;
+}
+
 /**
  * hl_device_suspend - initiate device suspend
  *
@@ -386,6 +498,12 @@ int hl_device_init(struct hl_device *hdev, struct class *hclass)
 		goto release_ctx;
 	}
 
+	rc = hl_sysfs_init(hdev);
+	if (rc) {
+		dev_err(hdev->dev, "failed to initialize sysfs\n");
+		goto free_cb_pool;
+	}
+
 	rc = hdev->asic_funcs->hw_init(hdev);
 	if (rc) {
 		dev_err(hdev->dev, "failed to initialize the H/W\n");

drivers/misc/habanalabs/device.c int hl_device_init(struct hl_device *hdev, struct class *hclass) · line 529

Quoted 9 lines
drivers/misc/habanalabs/device.c +6 -0
@@ -403,11 +521,33 @@ int hl_device_init(struct hl_device *hdev, struct class *hclass)
 		goto out_disabled;
 	}
 
+	/* After test_queues, KMD can start sending messages to device CPU */
+
+	rc = device_late_init(hdev);
+	if (rc) {
+		dev_err(hdev->dev, "Failed late initialization\n");
+		rc = 0;

Isn't this an error?

drivers/misc/habanalabs/device.c int hl_device_init(struct hl_device *hdev, struct class *hclass) · line 540

Quoted 11 lines
drivers/misc/habanalabs/device.c +11 -0
+		goto out_disabled;
+	}
+
+	dev_info(hdev->dev, "Found %s device with %lluGB DRAM\n",
+		hdev->asic_name,
+		hdev->asic_prop.dram_size / 1024 / 1024 / 1024);
+
+	rc = hl_hwmon_init(hdev);
+	if (rc) {
+		dev_err(hdev->dev, "Failed to initialize hwmon\n");
+		rc = 0;

Ditto

Quoted 182 lines
drivers/misc/habanalabs/device.c +11 -0
+		goto out_disabled;
+	}
+
 	dev_notice(hdev->dev,
 		"Successfully added device to habanalabs driver\n");
 
 	return 0;
 
+free_cb_pool:
+	hl_cb_pool_fini(hdev);
 release_ctx:
 	if (hl_ctx_put(hdev->kernel_ctx) != 1)
 		dev_err(hdev->dev,
@@ -457,6 +597,12 @@ void hl_device_fini(struct hl_device *hdev)
 	/* Mark device as disabled */
 	hdev->disabled = true;
 
+	hl_hwmon_fini(hdev);
+
+	device_late_fini(hdev);
+
+	hl_sysfs_fini(hdev);
+
 	/*
 	 * Halt the engines and disable interrupts so we won't get any more
 	 * completions from H/W and we won't have any accesses from the
drivers/misc/habanalabs/goya/Makefile +1 -1
index a57096fa41b6..ada8518ec215 100644
@@ -1,3 +1,3 @@
 subdir-ccflags-y += -I$(src)
 
-HL_GOYA_FILES :=  goya/goya.o goya/goya_security.o
\ No newline at end of file
+HL_GOYA_FILES :=  goya/goya.o goya/goya_security.o goya/goya_hwmgr.o
\ No newline at end of file
drivers/misc/habanalabs/goya/goya.c +106 -0
index 6c04277ae0fa..7899ff762e0b 100644
@@ -127,6 +127,8 @@ static const char *goya_axi_name[GOYA_MAX_INITIATORS] = {
 
 #define GOYA_ASYC_EVENT_GROUP_NON_FATAL_SIZE 121
 
+static int goya_armcp_info_get(struct hl_device *hdev);
+
 static void goya_get_fixed_properties(struct hl_device *hdev)
 {
 	struct asic_fixed_properties *prop = &hdev->asic_prop;
@@ -174,6 +176,7 @@ static void goya_get_fixed_properties(struct hl_device *hdev)
 	prop->num_of_events = GOYA_ASYNC_EVENT_ID_SIZE;
 	prop->cb_pool_cb_cnt = GOYA_CB_POOL_CB_CNT;
 	prop->cb_pool_cb_size = GOYA_CB_POOL_CB_SIZE;
+	prop->max_power_default = MAX_POWER_DEFAULT;
 	prop->tpc_enabled_mask = TPC_ENABLED_MASK;
 
 	prop->high_pll = PLL_HIGH_DEFAULT;
@@ -558,6 +561,89 @@ int goya_early_fini(struct hl_device *hdev)
 	return 0;
 }
 
+/**
+ * goya_fetch_psoc_frequency - Fetch PSOC frequency values
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ */
+static void goya_fetch_psoc_frequency(struct hl_device *hdev)
+{
+	struct asic_fixed_properties *prop = &hdev->asic_prop;
+
+	prop->psoc_pci_pll_nr = RREG32(mmPSOC_PCI_PLL_NR);
+	prop->psoc_pci_pll_nf = RREG32(mmPSOC_PCI_PLL_NF);
+	prop->psoc_pci_pll_od = RREG32(mmPSOC_PCI_PLL_OD);
+	prop->psoc_pci_pll_div_factor = RREG32(mmPSOC_PCI_PLL_DIV_FACTOR_1);
+}
+
+/**
+ * goya_late_init - GOYA late initialization code
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ * Get ArmCP info and send message to CPU to enable PCI access
+ */
+static int goya_late_init(struct hl_device *hdev)
+{
+	struct asic_fixed_properties *prop = &hdev->asic_prop;
+	struct goya_device *goya = hdev->asic_specific;
+	int rc;
+
+	rc = goya->armcp_info_get(hdev);
+	if (rc) {
+		dev_err(hdev->dev, "Failed to get armcp info\n");
+		return rc;
+	}
+
+	/* Now that we have the DRAM size in ASIC prop, we need to check
+	 * its size and configure the DMA_IF DDR wrap protection (which is in
+	 * the MMU block) accordingly. The value is the log2 of the DRAM size
+	 */
+	WREG32(mmMMU_LOG2_DDR_SIZE, ilog2(prop->dram_size));
+
+	rc = goya_send_pci_access_msg(hdev, ARMCP_PACKET_ENABLE_PCI_ACCESS);
+	if (rc) {
+		dev_err(hdev->dev, "Failed to enable PCI access from CPU\n");
+		return rc;
+	}
+
+	WREG32(mmGIC_DISTRIBUTOR__5_GICD_SETSPI_NSR,
+			GOYA_ASYNC_EVENT_ID_INTS_REGISTER);
+
+	goya_fetch_psoc_frequency(hdev);
+
+	return 0;
+}
+
+/**
+ * goya_late_fini - GOYA late tear-down code
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ * Free sensors allocated structures
+ */
+void goya_late_fini(struct hl_device *hdev)
+{
+	const struct hwmon_channel_info **channel_info_arr;
+	int i = 0;
+
+	if (!hdev->hl_chip_info.info)
+		return;
+
+	channel_info_arr = hdev->hl_chip_info.info;
+
+	while (channel_info_arr[i]) {
+		kfree(channel_info_arr[i]->config);
+		kfree(channel_info_arr[i]);
+		i++;
+	}
+
+	kfree(channel_info_arr);
+
+	hdev->hl_chip_info.info = NULL;
+}
+
 /**
  * goya_sw_init - Goya software initialization code
  *
@@ -575,9 +661,15 @@ static int goya_sw_init(struct hl_device *hdev)
 		return -ENOMEM;
 
 	goya->test_cpu_queue = goya_test_cpu_queue;
+	goya->armcp_info_get = goya_armcp_info_get;
 
 	/* according to goya_init_iatu */
 	goya->ddr_bar_cur_addr = DRAM_PHYS_BASE;
+
+	goya->mme_clk = GOYA_PLL_FREQ_LOW;
+	goya->tpc_clk = GOYA_PLL_FREQ_LOW;
+	goya->ic_clk = GOYA_PLL_FREQ_LOW;
+
 	hdev->asic_specific = goya;
 
 	/* Create DMA pool for small allocations */
@@ -4272,6 +4364,87 @@ void *goya_get_events_stat(struct hl_device *hdev, u32 *size)
 	return goya->events_stat;
 }
 
+static int goya_armcp_info_get(struct hl_device *hdev)
+{
+	struct goya_device *goya = hdev->asic_specific;
+	struct asic_fixed_properties *prop = &hdev->asic_prop;
+	struct armcp_packet pkt;
+	void *armcp_info_cpu_addr;
+	dma_addr_t armcp_info_dma_addr;
+	u64 dram_size;
+	long result;
+	int rc;
+
+	if (!(goya->hw_cap_initialized & HW_CAP_CPU_Q))
+		return 0;
+

drivers/misc/habanalabs/goya/goya.c void *goya_get_events_stat(struct hl_device *hdev, u32 *size) · line 4390

Quoted 10 lines
drivers/misc/habanalabs/goya/goya.c +10 -0
+	armcp_info_cpu_addr =
+			hdev->asic_funcs->cpu_accessible_dma_pool_alloc(hdev,
+			sizeof(struct armcp_info), &armcp_info_dma_addr);
+	if (!armcp_info_cpu_addr) {
+		dev_err(hdev->dev,
+			"Failed to allocate DMA memory for ArmCP info packet\n");
+		return -ENOMEM;
+	}
+
+	memset(armcp_info_cpu_addr, 0, sizeof(struct armcp_info));

Do you expect usage of cpu_accessible_dma_pool_alloc() without the need to clear the memory?
If not memset(0) can be moved inside that function.

Quoted 1,821 lines
drivers/misc/habanalabs/goya/goya.c +114 -0
+
+	memset(&pkt, 0, sizeof(pkt));
+
+	pkt.opcode = ARMCP_PACKET_INFO_GET;
+	pkt.addr = armcp_info_dma_addr + prop->host_phys_base_address;
+	pkt.data_max_size = sizeof(struct armcp_info);
+
+	rc = hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &pkt, sizeof(pkt),
+			GOYA_ARMCP_INFO_TIMEOUT, &result);
+
+	if (rc) {
+		dev_err(hdev->dev,
+			"Failed to send armcp info pkt, error %d\n", rc);
+		goto out;
+	}
+
+	memcpy(&prop->armcp_info, armcp_info_cpu_addr,
+			sizeof(prop->armcp_info));
+
+	dram_size = prop->armcp_info.dram_size;
+	if (dram_size) {
+		if ((!is_power_of_2(dram_size)) ||
+				(dram_size < DRAM_PHYS_DEFAULT_SIZE)) {
+			dev_err(hdev->dev,
+				"F/W reported invalid DRAM size %llu. Trying to use default size\n",
+				dram_size);
+			dram_size = DRAM_PHYS_DEFAULT_SIZE;
+		}
+
+		prop->dram_size = dram_size;
+		prop->dram_end_address = prop->dram_base_address + dram_size;
+	}
+
+	rc = hl_build_hwmon_channel_info(hdev, prop->armcp_info.sensors);
+	if (rc) {
+		dev_err(hdev->dev,
+			"Failed to build hwmon channel info, error %d\n", rc);
+		rc = -EFAULT;
+		goto out;
+	}
+
+out:
+	hdev->asic_funcs->cpu_accessible_dma_pool_free(hdev,
+			sizeof(struct armcp_info), armcp_info_cpu_addr);
+
+	return rc;
+}
+
+static void goya_init_clock_gating(struct hl_device *hdev)
+{
+
+}
+
+static void goya_disable_clock_gating(struct hl_device *hdev)
+{
+
+}
 
 static void goya_hw_queues_lock(struct hl_device *hdev)
 {
@@ -4287,9 +4460,60 @@ static void goya_hw_queues_unlock(struct hl_device *hdev)
 	spin_unlock(&goya->hw_queues_lock);
 }
 
+int goya_get_eeprom_data(struct hl_device *hdev, void *data, size_t max_size)
+{
+	struct goya_device *goya = hdev->asic_specific;
+	struct asic_fixed_properties *prop = &hdev->asic_prop;
+	struct armcp_packet pkt;
+	void *eeprom_info_cpu_addr;
+	dma_addr_t eeprom_info_dma_addr;
+	long result;
+	int rc;
+
+	if (!(goya->hw_cap_initialized & HW_CAP_CPU_Q))
+		return 0;
+
+	eeprom_info_cpu_addr =
+			hdev->asic_funcs->cpu_accessible_dma_pool_alloc(hdev,
+					max_size, &eeprom_info_dma_addr);
+	if (!eeprom_info_cpu_addr) {
+		dev_err(hdev->dev,
+			"Failed to allocate DMA memory for EEPROM info packet\n");
+		return -ENOMEM;
+	}
+
+	memset(eeprom_info_cpu_addr, 0, max_size);
+
+	memset(&pkt, 0, sizeof(pkt));
+
+	pkt.opcode = ARMCP_PACKET_EEPROM_DATA_GET;
+	pkt.addr = eeprom_info_dma_addr + prop->host_phys_base_address;
+	pkt.data_max_size = max_size;
+
+	rc = hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &pkt, sizeof(pkt),
+			GOYA_ARMCP_EEPROM_TIMEOUT, &result);
+
+	if (rc) {
+		dev_err(hdev->dev,
+			"Failed to send armcp EEPROM pkt, error %d\n", rc);
+		goto out;
+	}
+
+	/* result contains the actual size */
+	memcpy(data, eeprom_info_cpu_addr, min((size_t)result, max_size));
+
+out:
+	hdev->asic_funcs->cpu_accessible_dma_pool_free(hdev, max_size,
+			eeprom_info_cpu_addr);
+
+	return rc;
+}
+
 static const struct hl_asic_funcs goya_funcs = {
 	.early_init = goya_early_init,
 	.early_fini = goya_early_fini,
+	.late_init = goya_late_init,
+	.late_fini = goya_late_fini,
 	.sw_init = goya_sw_init,
 	.sw_fini = goya_sw_fini,
 	.hw_init = goya_hw_init,
@@ -4310,10 +4534,16 @@ static const struct hl_asic_funcs goya_funcs = {
 	.cpu_accessible_dma_pool_alloc = goya_cpu_accessible_dma_pool_alloc,
 	.cpu_accessible_dma_pool_free = goya_cpu_accessible_dma_pool_free,
 	.update_eq_ci = goya_update_eq_ci,
+	.add_device_attr = goya_add_device_attr,
+	.remove_device_attr = goya_remove_device_attr,
 	.handle_eqe = goya_handle_eqe,
+	.set_pll_profile = goya_set_pll_profile,
 	.get_events_stat = goya_get_events_stat,
+	.enable_clock_gating = goya_init_clock_gating,
+	.disable_clock_gating = goya_disable_clock_gating,
 	.hw_queues_lock = goya_hw_queues_lock,
 	.hw_queues_unlock = goya_hw_queues_unlock,
+	.get_eeprom_data = goya_get_eeprom_data,
 	.send_cpu_message = goya_send_cpu_message
 };
 
drivers/misc/habanalabs/goya/goyaP.h +21 -0
index c6bfcb6c6905..42e8b1baef2f 100644
@@ -48,7 +48,10 @@
 
 #define PLL_HIGH_DEFAULT		1575000000	/* 1.575 GHz */
 
+#define MAX_POWER_DEFAULT		200000		/* 200W */
+
 #define GOYA_ARMCP_INFO_TIMEOUT		10000000	/* 10s */
+#define GOYA_ARMCP_EEPROM_TIMEOUT	10000000	/* 10s */
 
 #define DRAM_PHYS_DEFAULT_SIZE		0x100000000ull	/* 4GB */
 
@@ -119,9 +122,15 @@ enum goya_fw_component {
 
 struct goya_device {
 	int (*test_cpu_queue)(struct hl_device *hdev);
+	int (*armcp_info_get)(struct hl_device *hdev);
 
 	/* TODO: remove hw_queues_lock after moving to scheduler code */
 	spinlock_t	hw_queues_lock;
+
+	u64		mme_clk;
+	u64		tpc_clk;
+	u64		ic_clk;
+
 	u64		ddr_bar_cur_addr;
 	u32		events_stat[GOYA_ASYNC_EVENT_ID_SIZE];
 	u32		hw_cap_initialized;
@@ -130,6 +139,18 @@ struct goya_device {
 int goya_test_cpu_queue(struct hl_device *hdev);
 int goya_send_cpu_message(struct hl_device *hdev, u32 *msg, u16 len,
 				u32 timeout, long *result);
+long goya_get_temperature(struct hl_device *hdev, int sensor_index, u32 attr);
+long goya_get_voltage(struct hl_device *hdev, int sensor_index, u32 attr);
+long goya_get_current(struct hl_device *hdev, int sensor_index, u32 attr);
+long goya_get_fan_speed(struct hl_device *hdev, int sensor_index, u32 attr);
+long goya_get_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr);
+void goya_set_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr,
+			long value);
+void goya_set_pll_profile(struct hl_device *hdev, enum hl_pll_frequency freq);
+int goya_add_device_attr(struct hl_device *hdev);
+void goya_remove_device_attr(struct hl_device *hdev);
 void goya_init_security(struct hl_device *hdev);
+u64 goya_get_max_power(struct hl_device *hdev);
+void goya_set_max_power(struct hl_device *hdev, u64 value);
 
 #endif /* GOYAP_H_ */
drivers/misc/habanalabs/goya/goya_hwmgr.c new file +306 -0
new file mode 100644
index 000000000000..866d1774b2e4
@@ -0,0 +1,306 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ */
+
+#include "goyaP.h"
+
+void goya_set_pll_profile(struct hl_device *hdev, enum hl_pll_frequency freq)
+{
+	struct goya_device *goya = hdev->asic_specific;
+
+	switch (freq) {
+	case PLL_HIGH:
+		hl_set_frequency(hdev, MME_PLL, hdev->high_pll);
+		hl_set_frequency(hdev, TPC_PLL, hdev->high_pll);
+		hl_set_frequency(hdev, IC_PLL, hdev->high_pll);
+		break;
+	case PLL_LOW:
+		hl_set_frequency(hdev, MME_PLL, GOYA_PLL_FREQ_LOW);
+		hl_set_frequency(hdev, TPC_PLL, GOYA_PLL_FREQ_LOW);
+		hl_set_frequency(hdev, IC_PLL, GOYA_PLL_FREQ_LOW);
+		break;
+	case PLL_LAST:
+		hl_set_frequency(hdev, MME_PLL, goya->mme_clk);
+		hl_set_frequency(hdev, TPC_PLL, goya->tpc_clk);
+		hl_set_frequency(hdev, IC_PLL, goya->ic_clk);
+		break;
+	default:
+		dev_err(hdev->dev, "unknown frequency setting\n");
+	}
+}
+
+static ssize_t mme_clk_show(struct device *dev, struct device_attribute *attr,
+				char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	long value;
+
+	if (hdev->disabled)
+		return -ENODEV;
+
+	value = hl_get_frequency(hdev, MME_PLL, false);
+
+	if (value < 0)
+		return value;
+
+	return snprintf(buf, PAGE_SIZE, "%lu\n", value);
+}
+
+static ssize_t mme_clk_store(struct device *dev, struct device_attribute *attr,
+				const char *buf, size_t count)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	struct goya_device *goya = hdev->asic_specific;
+	int rc;
+	long value;
+
+	if (hdev->disabled) {
+		count = -ENODEV;
+		goto fail;
+	}
+
+	if (hdev->pm_mng_profile == PM_AUTO) {
+		count = -EPERM;
+		goto fail;
+	}
+
+	rc = kstrtoul(buf, 0, &value);
+
+	if (rc) {
+		count = -EINVAL;
+		goto fail;
+	}
+
+	hl_set_frequency(hdev, MME_PLL, value);
+	goya->mme_clk = value;
+
+fail:
+	return count;
+}
+
+static ssize_t tpc_clk_show(struct device *dev, struct device_attribute *attr,
+				char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	long value;
+
+	if (hdev->disabled)
+		return -ENODEV;
+
+	value = hl_get_frequency(hdev, TPC_PLL, false);
+
+	if (value < 0)
+		return value;
+
+	return snprintf(buf, PAGE_SIZE, "%lu\n", value);
+}
+
+static ssize_t tpc_clk_store(struct device *dev, struct device_attribute *attr,
+				const char *buf, size_t count)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	struct goya_device *goya = hdev->asic_specific;
+	int rc;
+	long value;
+
+	if (hdev->disabled) {
+		count = -ENODEV;
+		goto fail;
+	}
+
+	if (hdev->pm_mng_profile == PM_AUTO) {
+		count = -EPERM;
+		goto fail;
+	}
+
+	rc = kstrtoul(buf, 0, &value);
+
+	if (rc) {
+		count = -EINVAL;
+		goto fail;
+	}
+
+	hl_set_frequency(hdev, TPC_PLL, value);
+	goya->tpc_clk = value;
+
+fail:
+	return count;
+}
+
+static ssize_t ic_clk_show(struct device *dev, struct device_attribute *attr,
+				char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	long value;
+
+	if (hdev->disabled)
+		return -ENODEV;
+
+	value = hl_get_frequency(hdev, IC_PLL, false);
+
+	if (value < 0)
+		return value;
+
+	return snprintf(buf, PAGE_SIZE, "%lu\n", value);
+}
+
+static ssize_t ic_clk_store(struct device *dev, struct device_attribute *attr,
+				const char *buf, size_t count)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	struct goya_device *goya = hdev->asic_specific;
+	int rc;
+	long value;
+
+	if (hdev->disabled) {
+		count = -ENODEV;
+		goto fail;
+	}
+
+	if (hdev->pm_mng_profile == PM_AUTO) {
+		count = -EPERM;
+		goto fail;
+	}
+
+	rc = kstrtoul(buf, 0, &value);
+
+	if (rc) {
+		count = -EINVAL;
+		goto fail;
+	}
+
+	hl_set_frequency(hdev, IC_PLL, value);
+	goya->ic_clk = value;
+
+fail:
+	return count;
+}
+
+static ssize_t mme_clk_curr_show(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	long value;
+
+	if (hdev->disabled)
+		return -ENODEV;
+
+	value = hl_get_frequency(hdev, MME_PLL, true);
+
+	if (value < 0)
+		return value;
+
+	return snprintf(buf, PAGE_SIZE, "%lu\n", value);
+}
+
+static ssize_t tpc_clk_curr_show(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	long value;
+
+	if (hdev->disabled)
+		return -ENODEV;
+
+	value = hl_get_frequency(hdev, TPC_PLL, true);
+
+	if (value < 0)
+		return value;
+
+	return snprintf(buf, PAGE_SIZE, "%lu\n", value);
+}
+
+static ssize_t ic_clk_curr_show(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	long value;
+
+	if (hdev->disabled)
+		return -ENODEV;
+
+	value = hl_get_frequency(hdev, IC_PLL, true);
+
+	if (value < 0)
+		return value;
+
+	return snprintf(buf, PAGE_SIZE, "%lu\n", value);
+}
+
+static DEVICE_ATTR_RW(mme_clk);
+static DEVICE_ATTR_RW(tpc_clk);
+static DEVICE_ATTR_RW(ic_clk);
+static DEVICE_ATTR_RO(mme_clk_curr);
+static DEVICE_ATTR_RO(tpc_clk_curr);
+static DEVICE_ATTR_RO(ic_clk_curr);
+
+int goya_add_device_attr(struct hl_device *hdev)
+{
+	int rc;
+
+	rc = device_create_file(hdev->dev, &dev_attr_mme_clk);
+	if (rc) {
+		dev_err(hdev->dev, "failed to create device file mme_clk\n");
+		return rc;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_tpc_clk);
+	if (rc) {
+		dev_err(hdev->dev, "failed to create device file tpc_clk\n");
+		goto remove_mme_clk;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_ic_clk);
+	if (rc) {
+		dev_err(hdev->dev, "failed to create device file ic_clk\n");
+		goto remove_tpc_clk;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_mme_clk_curr);
+	if (rc) {
+		dev_err(hdev->dev,
+			"failed to create device file mme_clk_curr\n");
+		goto remove_ic_clk;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_tpc_clk_curr);
+	if (rc) {
+		dev_err(hdev->dev,
+			"failed to create device file tpc_clk_curr\n");
+		goto remove_mme_clk_curr;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_ic_clk_curr);
+	if (rc) {
+		dev_err(hdev->dev,
+			"failed to create device file ic_clk_curr\n");
+		goto remove_tpc_clk_curr;
+	}
+
+	return 0;
+
+remove_tpc_clk_curr:
+	device_remove_file(hdev->dev, &dev_attr_tpc_clk_curr);
+remove_mme_clk_curr:
+	device_remove_file(hdev->dev, &dev_attr_mme_clk_curr);
+remove_ic_clk:
+	device_remove_file(hdev->dev, &dev_attr_ic_clk);
+remove_tpc_clk:
+	device_remove_file(hdev->dev, &dev_attr_tpc_clk);
+remove_mme_clk:
+	device_remove_file(hdev->dev, &dev_attr_mme_clk);
+	return rc;
+}
+
+void goya_remove_device_attr(struct hl_device *hdev)
+{
+	device_remove_file(hdev->dev, &dev_attr_ic_clk_curr);
+	device_remove_file(hdev->dev, &dev_attr_tpc_clk_curr);
+	device_remove_file(hdev->dev, &dev_attr_mme_clk_curr);
+	device_remove_file(hdev->dev, &dev_attr_ic_clk);
+	device_remove_file(hdev->dev, &dev_attr_tpc_clk);
+	device_remove_file(hdev->dev, &dev_attr_mme_clk);
+}
drivers/misc/habanalabs/habanalabs.h +97 -0
index 899bf98eb002..49b84b3ff864 100644
@@ -25,6 +25,8 @@
 
 #define HL_DEVICE_TIMEOUT_USEC		1000000 /* 1 s */
 
+#define HL_PLL_LOW_JOB_FREQ_USEC	5000000 /* 5 s */
+
 #define HL_MAX_QUEUES			128
 
 struct hl_device;
@@ -60,6 +62,8 @@ struct hw_queue_properties {
 /**
  * struct asic_fixed_properties - ASIC specific immutable properties.
  * @hw_queues_props: H/W queues properties.
+ * @armcp_info: received various information from ArmCP regarding the H/W. e.g.
+ *		available sensors.
  * @uboot_ver: F/W U-boot version.
  * @preboot_ver: F/W Preboot version.
  * @sram_base_address: SRAM physical start address.
@@ -72,6 +76,7 @@ struct hw_queue_properties {
  * @dram_pci_bar_size: size of PCI bar towards DRAM.
  * @host_phys_base_address: base physical address of host memory for
  *				transactions that the device generates.
+ * @max_power_default: max power of the device after reset
  * @va_space_host_start_address: base address of virtual memory range for
  *                               mapping host memory.
  * @va_space_host_end_address: end address of virtual memory range for
@@ -84,6 +89,10 @@ struct hw_queue_properties {
  * @sram_size: total size of SRAM.
  * @max_asid: maximum number of open contexts (ASIDs).
  * @num_of_events: number of possible internal H/W IRQs.
+ * @psoc_pci_pll_nr: PCI PLL NR value.
+ * @psoc_pci_pll_nf: PCI PLL NF value.
+ * @psoc_pci_pll_od: PCI PLL OD value.
+ * @psoc_pci_pll_div_factor: PCI PLL DIV FACTOR 1 value.
  * @completion_queues_count: number of completion queues.
  * @high_pll: high PLL frequency used by the device.
  * @cb_pool_cb_cnt: number of CBs in the CB pool.
@@ -92,6 +101,7 @@ struct hw_queue_properties {
  */
 struct asic_fixed_properties {
 	struct hw_queue_properties	hw_queues_props[HL_MAX_QUEUES];
+	struct armcp_info	armcp_info;
 	char			uboot_ver[VERSION_MAX_LEN];
 	char			preboot_ver[VERSION_MAX_LEN];
 	u64			sram_base_address;
@@ -103,6 +113,7 @@ struct asic_fixed_properties {
 	u64			dram_size;
 	u64			dram_pci_bar_size;
 	u64			host_phys_base_address;
+	u64			max_power_default;
 	u64			va_space_host_start_address;
 	u64			va_space_host_end_address;
 	u64			va_space_dram_start_address;
@@ -111,6 +122,10 @@ struct asic_fixed_properties {
 	u32			sram_size;
 	u32			max_asid;
 	u32			num_of_events;
+	u32			psoc_pci_pll_nr;
+	u32			psoc_pci_pll_nf;
+	u32			psoc_pci_pll_od;
+	u32			psoc_pci_pll_div_factor;
 	u32			high_pll;
 	u32			cb_pool_cb_cnt;
 	u32			cb_pool_cb_size;
@@ -296,13 +311,37 @@ enum hl_asic_type {
 };
 
 
+/**
+ * enum hl_pm_mng_profile - power management profile.
+ * @PM_AUTO: internal clock is set by KMD.
+ * @PM_MANUAL: internal clock is set by the user.
+ * @PM_LAST: last power management type.
+ */
+enum hl_pm_mng_profile {
+	PM_AUTO = 1,
+	PM_MANUAL,
+	PM_LAST
+};
 
+/**
+ * enum hl_pll_frequency - PLL frequency.
+ * @PLL_HIGH: high frequency.
+ * @PLL_LOW: low frequency.
+ * @PLL_LAST: last frequency values that were configured by the user.
+ */
+enum hl_pll_frequency {
+	PLL_HIGH = 1,
+	PLL_LOW,
+	PLL_LAST
+};
 
 /**
  * struct hl_asic_funcs - ASIC specific functions that are can be called from
  *                        common code.
  * @early_init: sets up early driver state (pre sw_init), doesn't configure H/W.
  * @early_fini: tears down what was done in early_init.
+ * @late_init: sets up late driver/hw state (post hw_init) - Optional.
+ * @late_fini: tears down what was done in late_init (pre hw_fini) - Optional.
  * @sw_init: sets up driver state, does not configure H/W.
  * @sw_fini: tears down driver state, does not configure H/W.
  * @hw_init: sets up the H/W state.
@@ -326,15 +365,23 @@ enum hl_asic_type {
  * @cpu_accessible_dma_pool_alloc: allocate CPU PQ packet from DMA pool.
  * @cpu_accessible_dma_pool_free: free CPU PQ packet from DMA pool.
  * @update_eq_ci: update event queue CI.
+ * @add_device_attr: add ASIC specific device attributes.
+ * @remove_device_attr: remove ASIC specific device attributes.
  * @handle_eqe: handle event queue entry (IRQ) from ArmCP.
+ * @set_pll_profile: change PLL profile (manual/automatic).
  * @get_events_stat: retrieve event queue entries histogram.
+ * @enable_clock_gating: enable clock gating for reducing power consumption.
+ * @disable_clock_gating: disable clock for accessing registers on HBW.
  * @hw_queues_lock: acquire H/W queues lock.
  * @hw_queues_unlock: release H/W queues lock.
+ * @get_eeprom_data: retrieve EEPROM data from F/W.
  * @send_cpu_message: send buffer to ArmCP.
  */
 struct hl_asic_funcs {
 	int (*early_init)(struct hl_device *hdev);
 	int (*early_fini)(struct hl_device *hdev);
+	int (*late_init)(struct hl_device *hdev);
+	void (*late_fini)(struct hl_device *hdev);
 	int (*sw_init)(struct hl_device *hdev);
 	int (*sw_fini)(struct hl_device *hdev);
 	int (*hw_init)(struct hl_device *hdev);
@@ -363,11 +410,19 @@ struct hl_asic_funcs {
 	void (*cpu_accessible_dma_pool_free)(struct hl_device *hdev,
 				size_t size, void *vaddr);
 	void (*update_eq_ci)(struct hl_device *hdev, u32 val);
+	int (*add_device_attr)(struct hl_device *hdev);
+	void (*remove_device_attr)(struct hl_device *hdev);
 	void (*handle_eqe)(struct hl_device *hdev,
 				struct hl_eq_entry *eq_entry);
+	void (*set_pll_profile)(struct hl_device *hdev,
+			enum hl_pll_frequency freq);
 	void* (*get_events_stat)(struct hl_device *hdev, u32 *size);
+	void (*enable_clock_gating)(struct hl_device *hdev);
+	void (*disable_clock_gating)(struct hl_device *hdev);
 	void (*hw_queues_lock)(struct hl_device *hdev);
 	void (*hw_queues_unlock)(struct hl_device *hdev);
+	int (*get_eeprom_data)(struct hl_device *hdev, void *data,
+				size_t max_size);
 	int (*send_cpu_message)(struct hl_device *hdev, u32 *msg,
 				u16 len, u32 timeout, long *result);
 };
@@ -496,6 +551,7 @@ void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
  * @rmmio: configuration area address on SRAM.
  * @cdev: related char device.
  * @dev: realted kernel basic device structure.
+ * @work_freq: delayed work to lower device frequency if possible.
  * @asic_name: ASIC specific nmae.
  * @asic_type: ASIC specific type.
  * @completion_queue: array of hl_cq.
@@ -517,13 +573,23 @@ void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
  * @asic_prop: ASIC specific immutable properties.
  * @asic_funcs: ASIC specific functions.
  * @asic_specific: ASIC specific information to use only from ASIC files.
+ * @hwmon_dev: H/W monitor device.
+ * @pm_mng_profile: current power management profile.
+ * @hl_chip_info: ASIC's sensors information.
  * @cb_pool: list of preallocated CBs.
  * @cb_pool_lock: protects the CB pool.
  * @user_ctx: current user context executing.
+ * @curr_pll_profile: current PLL profile.
  * @fd_open_cnt: number of open context executing.
+ * @max_power: the max power of the device, as configured by the sysadmin. This
+ *             value is saved so in case of hard-reset, KMD will restore this
+ *             value and update the F/W after the re-initialization
  * @major: habanalabs KMD major.
+ * @high_pll: high PLL profile frequency.
  * @id: device minor.
  * @disabled: is device disabled.
+ * @late_init_done: is late init stage was done during initialization.
+ * @hwmon_initialized: is H/W monitor sensors was initialized.
  */
 struct hl_device {
 	struct pci_dev			*pdev;
@@ -531,6 +597,7 @@ struct hl_device {
 	void __iomem			*rmmio;
 	struct cdev			cdev;
 	struct device			*dev;
+	struct delayed_work		work_freq;
 	char				asic_name[16];
 	enum hl_asic_type		asic_type;
 	struct hl_cq			*completion_queue;
@@ -553,16 +620,25 @@ struct hl_device {
 	struct asic_fixed_properties	asic_prop;
 	const struct hl_asic_funcs	*asic_funcs;
 	void				*asic_specific;
+	struct device			*hwmon_dev;
+	enum hl_pm_mng_profile		pm_mng_profile;
+	struct hwmon_chip_info		hl_chip_info;
 
 	struct list_head		cb_pool;
 	spinlock_t			cb_pool_lock;
 
 	/* TODO: The following fields should be moved for multi-context */
 	struct hl_ctx			*user_ctx;
+
+	atomic_t			curr_pll_profile;
 	atomic_t			fd_open_cnt;
+	u64				max_power;
 	u32				major;
+	u32				high_pll;
 	u16				id;
 	u8				disabled;
+	u8				late_init_done;
+	u8				hwmon_initialized;
 
 	/* Parameters for bring-up */
 	u8				cpu_enable;
@@ -647,6 +723,15 @@ int hl_device_suspend(struct hl_device *hdev);
 int hl_device_resume(struct hl_device *hdev);
 void hl_hpriv_get(struct hl_fpriv *hpriv);
 void hl_hpriv_put(struct hl_fpriv *hpriv);
+int hl_device_set_frequency(struct hl_device *hdev, enum hl_pll_frequency freq);
+int hl_build_hwmon_channel_info(struct hl_device *hdev,
+		struct armcp_sensor *sensors_arr);
+
+int hl_sysfs_init(struct hl_device *hdev);
+void hl_sysfs_fini(struct hl_device *hdev);
+
+int hl_hwmon_init(struct hl_device *hdev);
+void hl_hwmon_fini(struct hl_device *hdev);
 
 int hl_cb_create(struct hl_device *hdev, struct hl_cb_mgr *mgr, u32 cb_size,
 		u64 *handle, int ctx_id);
@@ -663,6 +748,18 @@ int hl_cb_pool_fini(struct hl_device *hdev);
 
 void goya_set_asic_funcs(struct hl_device *hdev);
 
+long hl_get_frequency(struct hl_device *hdev, u32 pll_index, bool curr);
+void hl_set_frequency(struct hl_device *hdev, u32 pll_index, u64 freq);
+long hl_get_temperature(struct hl_device *hdev, int sensor_index, u32 attr);
+long hl_get_voltage(struct hl_device *hdev, int sensor_index, u32 attr);
+long hl_get_current(struct hl_device *hdev, int sensor_index, u32 attr);
+long hl_get_fan_speed(struct hl_device *hdev, int sensor_index, u32 attr);
+long hl_get_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr);
+void hl_set_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr,
+			long value);
+u64 hl_get_max_power(struct hl_device *hdev);
+void hl_set_max_power(struct hl_device *hdev, u64 value);
+
 /* IOCTLs */
 long hl_ioctl(struct file *filep, unsigned int cmd, unsigned long arg);
 int hl_cb_ioctl(struct hl_fpriv *hpriv, void *data);
drivers/misc/habanalabs/habanalabs_drv.c +7 -0
index b64f58ad0f5d..47a9ab458b43 100644
@@ -134,6 +134,13 @@ int hl_device_open(struct inode *inode, struct file *filp)
 
 	hpriv->taskpid = find_get_pid(current->pid);
 
+	/*
+	 * Device is IDLE at this point so it is legal to change PLLs. There
+	 * is no need to check anything because if the PLL is already HIGH, the
+	 * set function will return without doing anything
+	 */
+	hl_device_set_frequency(hdev, PLL_HIGH);
+
 	return 0;
 
 out_err:
drivers/misc/habanalabs/hwmon.c new file +449 -0
new file mode 100644
index 000000000000..6ca0decb7490
@@ -0,0 +1,449 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ */
+
+#include "habanalabs.h"
+
+#define SENSORS_PKT_TIMEOUT		100000	/* 100ms */
+#define HWMON_NR_SENSOR_TYPES		(hwmon_pwm + 1)
+
+int hl_build_hwmon_channel_info(struct hl_device *hdev,
+				struct armcp_sensor *sensors_arr)
+{
+	u32 counts[HWMON_NR_SENSOR_TYPES] = {0};
+	u32 *sensors_by_type[HWMON_NR_SENSOR_TYPES] = {0};
+	u32 sensors_by_type_next_index[HWMON_NR_SENSOR_TYPES] = {0};
+	struct hwmon_channel_info **channels_info;
+	u32 num_sensors_for_type, num_active_sensor_types = 0,
+			arr_size = 0, *curr_arr;
+	enum hwmon_sensor_types type;
+	int rc, i, j;
+
+	for (i = 0 ; i < ARMCP_MAX_SENSORS ; i++) {
+		type = sensors_arr[i].type;
+
+		if ((type == 0) && (sensors_arr[i].flags == 0))
+			break;
+
+		if (type >= HWMON_NR_SENSOR_TYPES) {
+			dev_err(hdev->dev,
+				"Got wrong sensor type %d from device\n", type);
+			return -EINVAL;
+		}
+
+		counts[type]++;
+		arr_size++;
+	}
+
+	for (i = 0 ; i < HWMON_NR_SENSOR_TYPES ; i++) {
+		if (counts[i] == 0)
+			continue;
+
+		num_sensors_for_type = counts[i] + 1;
+		curr_arr = kcalloc(num_sensors_for_type, sizeof(*curr_arr),
+				GFP_KERNEL);
+		if (!curr_arr) {
+			rc = -ENOMEM;
+			goto sensors_type_err;
+		}
+
+		num_active_sensor_types++;
+		sensors_by_type[i] = curr_arr;
+	}
+
+	for (i = 0 ; i < arr_size ; i++) {
+		type = sensors_arr[i].type;
+		curr_arr = sensors_by_type[type];
+		curr_arr[sensors_by_type_next_index[type]++] =
+				sensors_arr[i].flags;
+	}
+
+	channels_info = kcalloc(num_active_sensor_types + 1,
+			sizeof(*channels_info), GFP_KERNEL);
+	if (!channels_info) {
+		rc = -ENOMEM;
+		goto channels_info_array_err;
+	}
+
+	for (i = 0 ; i < num_active_sensor_types ; i++) {
+		channels_info[i] = kzalloc(sizeof(*channels_info[i]),
+				GFP_KERNEL);
+		if (!channels_info[i]) {
+			rc = -ENOMEM;
+			goto channel_info_err;
+		}
+	}
+
+	for (i = 0, j = 0 ; i < HWMON_NR_SENSOR_TYPES ; i++) {
+		if (!sensors_by_type[i])
+			continue;
+
+		channels_info[j]->type = i;
+		channels_info[j]->config = sensors_by_type[i];
+		j++;
+	}
+
+	hdev->hl_chip_info.info =
+			(const struct hwmon_channel_info **)channels_info;
+
+	return 0;
+
+channel_info_err:
+	for (i = 0 ; i < num_active_sensor_types ; i++)
+		if (channels_info[i]) {
+			kfree(channels_info[i]->config);
+			kfree(channels_info[i]);
+		}
+	kfree(channels_info);
+channels_info_array_err:
+sensors_type_err:
+	for (i = 0 ; i < HWMON_NR_SENSOR_TYPES ; i++)
+		kfree(sensors_by_type[i]);
+
+	return rc;
+}
+
+static int hl_read(struct device *dev, enum hwmon_sensor_types type,
+			u32 attr, int channel, long *val)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	if (hdev->disabled)
+		return -ENODEV;
+
+	switch (type) {
+	case hwmon_temp:
+		switch (attr) {
+		case hwmon_temp_input:
+		case hwmon_temp_max:
+		case hwmon_temp_crit:
+		case hwmon_temp_max_hyst:
+		case hwmon_temp_crit_hyst:
+			break;
+		default:
+			return -EINVAL;
+		}
+
+		*val = hl_get_temperature(hdev, channel, attr);
+		break;
+	case hwmon_in:
+		switch (attr) {
+		case hwmon_in_input:
+		case hwmon_in_min:
+		case hwmon_in_max:
+			break;
+		default:
+			return -EINVAL;
+		}
+
+		*val = hl_get_voltage(hdev, channel, attr);
+		break;
+	case hwmon_curr:
+		switch (attr) {
+		case hwmon_curr_input:
+		case hwmon_curr_min:
+		case hwmon_curr_max:
+			break;
+		default:
+			return -EINVAL;
+		}
+
+		*val = hl_get_current(hdev, channel, attr);
+		break;
+	case hwmon_fan:
+		switch (attr) {
+		case hwmon_fan_input:
+		case hwmon_fan_min:
+		case hwmon_fan_max:
+			break;
+		default:
+			return -EINVAL;
+		}
+		*val = hl_get_fan_speed(hdev, channel, attr);
+		break;
+	case hwmon_pwm:
+		switch (attr) {
+		case hwmon_pwm_input:
+		case hwmon_pwm_enable:
+			break;
+		default:
+			return -EINVAL;
+		}
+		*val = hl_get_pwm_info(hdev, channel, attr);
+		break;
+	default:
+		return -EINVAL;
+	}
+	return 0;
+}
+
+static int hl_write(struct device *dev, enum hwmon_sensor_types type,
+			u32 attr, int channel, long val)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	if (hdev->disabled)
+		return -ENODEV;
+
+	switch (type) {
+	case hwmon_pwm:
+		switch (attr) {
+		case hwmon_pwm_input:
+		case hwmon_pwm_enable:
+			break;
+		default:
+			return -EINVAL;
+		}
+		hl_set_pwm_info(hdev, channel, attr, val);
+		break;
+	default:
+		return -EINVAL;
+	}
+	return 0;
+}
+
+static umode_t hl_is_visible(const void *data, enum hwmon_sensor_types type,
+				u32 attr, int channel)
+{
+	switch (type) {
+	case hwmon_temp:
+		switch (attr) {
+		case hwmon_temp_input:
+		case hwmon_temp_max:
+		case hwmon_temp_max_hyst:
+		case hwmon_temp_crit:
+		case hwmon_temp_crit_hyst:
+			return 0444;
+		}
+		break;
+	case hwmon_in:
+		switch (attr) {
+		case hwmon_in_input:
+		case hwmon_in_min:
+		case hwmon_in_max:
+			return 0444;
+		}
+		break;
+	case hwmon_curr:
+		switch (attr) {
+		case hwmon_curr_input:
+		case hwmon_curr_min:
+		case hwmon_curr_max:
+			return 0444;
+		}
+		break;
+	case hwmon_fan:
+		switch (attr) {
+		case hwmon_fan_input:
+		case hwmon_fan_min:
+		case hwmon_fan_max:
+			return 0444;
+		}
+		break;
+	case hwmon_pwm:
+		switch (attr) {
+		case hwmon_pwm_input:
+		case hwmon_pwm_enable:
+			return 0644;
+		}
+		break;
+	default:
+		break;
+	}
+	return 0;
+}
+
+static const struct hwmon_ops hl_hwmon_ops = {
+	.is_visible = hl_is_visible,
+	.read = hl_read,
+	.write = hl_write
+};
+
+long hl_get_temperature(struct hl_device *hdev, int sensor_index, u32 attr)
+{
+	struct armcp_packet pkt;
+	long result;
+	int rc;
+
+	memset(&pkt, 0, sizeof(pkt));
+
+	pkt.opcode = ARMCP_PACKET_TEMPERATURE_GET;
+	pkt.sensor_index = sensor_index;
+	pkt.type = attr;
+
+	rc = hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &pkt, sizeof(pkt),
+			SENSORS_PKT_TIMEOUT, &result);
+
+	if (rc) {
+		dev_err(hdev->dev,
+			"Failed to get temperature from sensor %d, error %d\n",
+			sensor_index, rc);
+		result = 0;
+	}
+
+	return result;
+}
+
+long hl_get_voltage(struct hl_device *hdev, int sensor_index, u32 attr)
+{
+	struct armcp_packet pkt;
+	long result;
+	int rc;
+
+	memset(&pkt, 0, sizeof(pkt));
+
+	pkt.opcode = ARMCP_PACKET_VOLTAGE_GET;
+	pkt.sensor_index = sensor_index;
+	pkt.type = attr;
+
+	rc = hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &pkt, sizeof(pkt),
+					SENSORS_PKT_TIMEOUT, &result);
+
+	if (rc) {
+		dev_err(hdev->dev,
+			"Failed to get voltage from sensor %d, error %d\n",
+			sensor_index, rc);
+		result = 0;
+	}
+
+	return result;
+}
+
+long hl_get_current(struct hl_device *hdev, int sensor_index, u32 attr)
+{
+	struct armcp_packet pkt;
+	long result;
+	int rc;
+
+	memset(&pkt, 0, sizeof(pkt));
+
+	pkt.opcode = ARMCP_PACKET_CURRENT_GET;
+	pkt.sensor_index = sensor_index;
+	pkt.type = attr;
+
+	rc = hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &pkt, sizeof(pkt),
+					SENSORS_PKT_TIMEOUT, &result);
+
+	if (rc) {
+		dev_err(hdev->dev,
+			"Failed to get current from sensor %d, error %d\n",
+			sensor_index, rc);
+		result = 0;
+	}
+
+	return result;
+}
+
+long hl_get_fan_speed(struct hl_device *hdev, int sensor_index, u32 attr)
+{
+	struct armcp_packet pkt;
+	long result;
+	int rc;
+
+	memset(&pkt, 0, sizeof(pkt));
+
+	pkt.opcode = ARMCP_PACKET_FAN_SPEED_GET;
+	pkt.sensor_index = sensor_index;
+	pkt.type = attr;
+
+	rc = hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &pkt, sizeof(pkt),
+					SENSORS_PKT_TIMEOUT, &result);
+
+	if (rc) {
+		dev_err(hdev->dev,
+			"Failed to get fan speed from sensor %d, error %d\n",
+			sensor_index, rc);
+		result = 0;
+	}
+
+	return result;
+}
+
+long hl_get_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr)
+{
+	struct armcp_packet pkt;
+	long result;
+	int rc;
+
+	memset(&pkt, 0, sizeof(pkt));
+
+	pkt.opcode = ARMCP_PACKET_PWM_GET;
+	pkt.sensor_index = sensor_index;
+	pkt.type = attr;
+
+	rc = hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &pkt, sizeof(pkt),
+					SENSORS_PKT_TIMEOUT, &result);
+
+	if (rc) {
+		dev_err(hdev->dev,
+			"Failed to get pwm info from sensor %d, error %d\n",
+			sensor_index, rc);
+		result = 0;
+	}
+
+	return result;
+}
+
+void hl_set_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr,
+			long value)
+{
+	struct armcp_packet pkt;
+	int rc;
+
+	memset(&pkt, 0, sizeof(pkt));
+
+	pkt.opcode = ARMCP_PACKET_PWM_SET;
+	pkt.sensor_index = sensor_index;
+	pkt.type = attr;
+	pkt.value = value;
+
+	rc = hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &pkt, sizeof(pkt),
+					SENSORS_PKT_TIMEOUT, NULL);
+
+	if (rc)
+		dev_err(hdev->dev,
+			"Failed to set pwm info to sensor %d, error %d\n",
+			sensor_index, rc);
+}
+
+int hl_hwmon_init(struct hl_device *hdev)
+{
+	struct device *dev = hdev->pdev ? &hdev->pdev->dev : hdev->dev;
+	int rc;
+
+	if ((hdev->hwmon_initialized) || !(hdev->fw_loading))
+		return 0;
+
+	if (hdev->hl_chip_info.info) {
+		hdev->hl_chip_info.ops = &hl_hwmon_ops;
+
+		hdev->hwmon_dev = hwmon_device_register_with_info(dev,
+				"habanalabs", hdev, &hdev->hl_chip_info, NULL);
+		if (IS_ERR(hdev->hwmon_dev)) {
+			rc = PTR_ERR(hdev->hwmon_dev);
+			dev_err(hdev->dev,
+				"Unable to register hwmon device: %d\n", rc);
+			return rc;
+		}
+
+		dev_info(hdev->dev, "%s: add sensors information\n",
+			dev_name(hdev->hwmon_dev));
+
+		hdev->hwmon_initialized = true;
+	} else {
+		dev_info(hdev->dev, "no available sensors\n");
+	}
+
+	return 0;
+}
+
+void hl_hwmon_fini(struct hl_device *hdev)
+{
+	if (!hdev->hwmon_initialized)
+		return;
+
+	hwmon_device_unregister(hdev->hwmon_dev);
+}
drivers/misc/habanalabs/sysfs.c new file +588 -0
new file mode 100644
index 000000000000..edd5f7159de0
@@ -0,0 +1,588 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ */
+
+#include "habanalabs.h"
+#include "include/habanalabs_device_if.h"
+
+#include <linux/hwmon-sysfs.h>
+#include <linux/hwmon.h>
+
+#define SET_CLK_PKT_TIMEOUT	200000	/* 200ms */
+#define SET_PWR_PKT_TIMEOUT	400000	/* 400ms */
+
+long hl_get_frequency(struct hl_device *hdev, u32 pll_index, bool curr)
+{
+	struct armcp_packet pkt;
+	long result;
+	int rc;
+
+	memset(&pkt, 0, sizeof(pkt));
+
+	if (curr)
+		pkt.opcode = ARMCP_PACKET_FREQUENCY_CURR_GET;
+	else
+		pkt.opcode = ARMCP_PACKET_FREQUENCY_GET;
+	pkt.pll_index = pll_index;
+
+	rc = hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &pkt, sizeof(pkt),
+						SET_CLK_PKT_TIMEOUT, &result);
+
+	if (rc) {
+		dev_err(hdev->dev,
+			"Failed to get frequency of PLL %d, error %d\n",
+			pll_index, rc);
+		result = rc;
+	}
+
+	return result;
+}
+
+void hl_set_frequency(struct hl_device *hdev, u32 pll_index, u64 freq)
+{
+	struct armcp_packet pkt;
+	int rc;
+
+	memset(&pkt, 0, sizeof(pkt));
+
+	pkt.opcode = ARMCP_PACKET_FREQUENCY_SET;
+	pkt.pll_index = pll_index;
+	pkt.value = freq;
+
+	rc = hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &pkt, sizeof(pkt),
+					SET_CLK_PKT_TIMEOUT, NULL);
+
+	if (rc)
+		dev_err(hdev->dev,
+			"Failed to set frequency to PLL %d, error %d\n",
+			pll_index, rc);
+}
+
+u64 hl_get_max_power(struct hl_device *hdev)
+{
+	struct armcp_packet pkt;
+	long result;
+	int rc;
+
+	memset(&pkt, 0, sizeof(pkt));
+
+	pkt.opcode = ARMCP_PACKET_MAX_POWER_GET;
+
+	rc = hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &pkt, sizeof(pkt),
+						SET_PWR_PKT_TIMEOUT, &result);
+
+	if (rc) {
+		dev_err(hdev->dev, "Failed to get max power, error %d\n", rc);
+		result = rc;
+	}
+
+	return result;
+}
+
+void hl_set_max_power(struct hl_device *hdev, u64 value)
+{
+	struct armcp_packet pkt;
+	int rc;
+
+	memset(&pkt, 0, sizeof(pkt));
+
+	pkt.opcode = ARMCP_PACKET_MAX_POWER_SET;
+	pkt.value = value;
+
+	rc = hdev->asic_funcs->send_cpu_message(hdev, (u32 *) &pkt, sizeof(pkt),
+					SET_PWR_PKT_TIMEOUT, NULL);
+
+	if (rc)
+		dev_err(hdev->dev, "Failed to set max power, error %d\n", rc);
+}
+
+static ssize_t pm_mng_profile_show(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	if (hdev->disabled)
+		return -ENODEV;
+
+	return snprintf(buf, PAGE_SIZE, "%s\n",
+			(hdev->pm_mng_profile == PM_AUTO) ? "auto" :
+			(hdev->pm_mng_profile == PM_MANUAL) ? "manual" :
+			"unknown");
+}
+
+static ssize_t pm_mng_profile_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t count)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	if (hdev->disabled) {
+		count = -ENODEV;
+		goto out;
+	}
+
+	mutex_lock(&hdev->device_open);
+
+	if (atomic_read(&hdev->fd_open_cnt) > 0) {
+		dev_err(hdev->dev,
+			"Can't change PM profile while user process is opened on the device\n");
+		count = -EPERM;
+		goto unlock_mutex;
+	}
+
+	if (strncmp("auto", buf, strlen("auto")) == 0) {
+		/* Make sure we are in LOW PLL when changing modes */
+		if (hdev->pm_mng_profile == PM_MANUAL) {
+			atomic_set(&hdev->curr_pll_profile, PLL_HIGH);
+			hl_device_set_frequency(hdev, PLL_LOW);
+			hdev->pm_mng_profile = PM_AUTO;
+		}
+	} else if (strncmp("manual", buf, strlen("manual")) == 0) {
+		/* Make sure we are in LOW PLL when changing modes */
+		if (hdev->pm_mng_profile == PM_AUTO) {
+			flush_delayed_work(&hdev->work_freq);
+			hdev->pm_mng_profile = PM_MANUAL;
+		}
+	} else {
+		dev_err(hdev->dev, "value should be auto or manual\n");
+		count = -EINVAL;
+		goto unlock_mutex;
+	}
+
+unlock_mutex:
+	mutex_unlock(&hdev->device_open);
+out:
+	return count;
+}
+
+static ssize_t high_pll_show(struct device *dev, struct device_attribute *attr,
+				char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	if (hdev->disabled)
+		return -ENODEV;
+
+	return snprintf(buf, PAGE_SIZE, "%u\n", hdev->high_pll);
+}
+
+static ssize_t high_pll_store(struct device *dev, struct device_attribute *attr,
+				const char *buf, size_t count)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	long value;
+	int rc;
+
+	if (hdev->disabled) {
+		count = -ENODEV;
+		goto out;
+	}
+
+	rc = kstrtoul(buf, 0, &value);
+
+	if (rc) {
+		count = -EINVAL;
+		goto out;
+	}
+
+	hdev->high_pll = value;
+
+out:
+	return count;
+}
+
+static ssize_t uboot_ver_show(struct device *dev, struct device_attribute *attr,
+				char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	return snprintf(buf, PAGE_SIZE, "%s\n", hdev->asic_prop.uboot_ver);
+}
+
+static ssize_t armcp_kernel_ver_show(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	return snprintf(buf, PAGE_SIZE, "%s",
+			hdev->asic_prop.armcp_info.kernel_version);
+}
+
+static ssize_t armcp_ver_show(struct device *dev, struct device_attribute *attr,
+				char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	return snprintf(buf, PAGE_SIZE, "%s\n",
+			hdev->asic_prop.armcp_info.armcp_version);
+}
+
+static ssize_t cpld_ver_show(struct device *dev, struct device_attribute *attr,
+				char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	return snprintf(buf, PAGE_SIZE, "0x%08x\n",
+			hdev->asic_prop.armcp_info.cpld_version);
+}
+
+static ssize_t infineon_ver_show(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	return snprintf(buf, PAGE_SIZE, "0x%04x\n",
+			hdev->asic_prop.armcp_info.infineon_version);
+}
+
+static ssize_t fuse_ver_show(struct device *dev, struct device_attribute *attr,
+				char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	return snprintf(buf, PAGE_SIZE, "%s\n",
+			hdev->asic_prop.armcp_info.fuse_version);
+}
+
+static ssize_t thermal_ver_show(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	return snprintf(buf, PAGE_SIZE, "%s",
+			hdev->asic_prop.armcp_info.thermal_version);
+}
+
+static ssize_t preboot_btl_ver_show(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	return snprintf(buf, PAGE_SIZE, "%s\n", hdev->asic_prop.preboot_ver);
+}
+
+static ssize_t device_type_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	char *str;
+
+	switch (hdev->asic_type) {
+	case ASIC_GOYA:
+		str = "GOYA";
+		break;
+	default:
+		dev_err(hdev->dev, "Unrecognized ASIC type %d\n",
+				hdev->asic_type);
+		return -EINVAL;
+	}
+
+	return snprintf(buf, PAGE_SIZE, "%s\n", str);
+}
+
+static ssize_t pci_addr_show(struct device *dev, struct device_attribute *attr,
+				char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	/* Use dummy, fixed address for simulator */
+	if (!hdev->pdev)
+		return snprintf(buf, PAGE_SIZE, "0000:%02d:00.0\n", hdev->id);
+
+	return snprintf(buf, PAGE_SIZE, "%04x:%02x:%02x.%x\n",
+			pci_domain_nr(hdev->pdev->bus),
+			hdev->pdev->bus->number,
+			PCI_SLOT(hdev->pdev->devfn),
+			PCI_FUNC(hdev->pdev->devfn));
+}
+
+static ssize_t status_show(struct device *dev, struct device_attribute *attr,
+				char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	char *str;
+
+	if (hdev->disabled)
+		str = "Malfunction";
+	else
+		str = "Operational";
+
+	return snprintf(buf, PAGE_SIZE, "%s\n", str);
+}
+
+static ssize_t write_open_cnt_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+
+	return snprintf(buf, PAGE_SIZE, "%d\n", hdev->user_ctx ? 1 : 0);
+}
+
+static ssize_t max_power_show(struct device *dev, struct device_attribute *attr,
+				char *buf)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	long val;
+
+	if (hdev->disabled)
+		return -ENODEV;
+
+	val = hl_get_max_power(hdev);
+
+	return snprintf(buf, PAGE_SIZE, "%lu\n", val);
+}
+
+static ssize_t max_power_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t count)
+{
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	unsigned long value;
+	int rc;
+
+	if (hdev->disabled) {
+		count = -ENODEV;
+		goto out;
+	}
+
+	rc = kstrtoul(buf, 0, &value);
+
+	if (rc) {
+		count = -EINVAL;
+		goto out;
+	}
+
+	hdev->max_power = value;
+	hl_set_max_power(hdev, value);
+
+out:
+	return count;
+}
+
+static ssize_t eeprom_read_handler(struct file *filp, struct kobject *kobj,
+			struct bin_attribute *attr, char *buf, loff_t offset,
+			size_t max_size)
+{
+	struct device *dev = container_of(kobj, struct device, kobj);
+	struct hl_device *hdev = dev_get_drvdata(dev);
+	char *data;
+	int rc;
+
+	if (!max_size)
+		return -EINVAL;
+
+	data = kzalloc(max_size, GFP_KERNEL);
+	if (!data)
+		return -ENOMEM;
+
+	rc = hdev->asic_funcs->get_eeprom_data(hdev, data, max_size);
+	if (rc)
+		goto out;
+
+	memcpy(buf, data, max_size);
+
+out:
+	kfree(data);
+
+	return max_size;
+}
+
+static DEVICE_ATTR_RW(pm_mng_profile);
+static DEVICE_ATTR_RW(high_pll);
+static DEVICE_ATTR_RO(uboot_ver);
+static DEVICE_ATTR_RO(armcp_kernel_ver);
+static DEVICE_ATTR_RO(armcp_ver);
+static DEVICE_ATTR_RO(cpld_ver);
+static DEVICE_ATTR_RO(infineon_ver);
+static DEVICE_ATTR_RO(fuse_ver);
+static DEVICE_ATTR_RO(thermal_ver);
+static DEVICE_ATTR_RO(preboot_btl_ver);
+static DEVICE_ATTR_RO(device_type);
+static DEVICE_ATTR_RO(pci_addr);
+static DEVICE_ATTR_RO(status);
+static DEVICE_ATTR_RO(write_open_cnt);
+static DEVICE_ATTR_RW(max_power);
+
+static const struct bin_attribute bin_attr_eeprom = {
+	.attr = {.name = "eeprom", .mode = (0444)},
+	.size = PAGE_SIZE,
+	.read = eeprom_read_handler
+};
+
+int hl_sysfs_init(struct hl_device *hdev)
+{
+	int rc;
+
+	rc = hdev->asic_funcs->add_device_attr(hdev);
+	if (rc) {
+		dev_err(hdev->dev, "failed to add device attributes\n");
+		return rc;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_pm_mng_profile);
+	if (rc) {
+		dev_err(hdev->dev,
+			"failed to create device file pm_mng_profile\n");
+		goto remove_device_attr;
+	}
+
+	hdev->pm_mng_profile = PM_AUTO;
+
+	rc = device_create_file(hdev->dev, &dev_attr_high_pll);
+	if (rc) {
+		dev_err(hdev->dev,
+			"failed to create device file pll_profile\n");
+		goto remove_pm_mng_profile;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_uboot_ver);
+	if (rc) {
+		dev_err(hdev->dev, "failed to create device file uboot_ver\n");
+		goto remove_pll_profile;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_armcp_kernel_ver);
+	if (rc) {
+		dev_err(hdev->dev,
+			"failed to create device file armcp_kernel_ver\n");
+		goto remove_uboot_ver;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_armcp_ver);
+	if (rc) {
+		dev_err(hdev->dev, "failed to create device file armcp_ver\n");
+		goto remove_armcp_kernel_ver;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_cpld_ver);
+	if (rc) {
+		dev_err(hdev->dev, "failed to create device file cpld_ver\n");
+		goto remove_armcp_ver;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_infineon_ver);
+	if (rc) {
+		dev_err(hdev->dev,
+			"failed to create device file infineon_ver\n");
+		goto remove_cpld_ver;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_fuse_ver);
+	if (rc) {
+		dev_err(hdev->dev, "failed to create device file fuse_ver\n");
+		goto remove_infineon_ver;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_thermal_ver);
+	if (rc) {
+		dev_err(hdev->dev, "failed to create device file thermal_ver\n");
+		goto remove_fuse_ver;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_preboot_btl_ver);
+	if (rc) {
+		dev_err(hdev->dev,
+			"failed to create device file preboot_btl_ver\n");
+		goto remove_thermal_ver;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_device_type);
+	if (rc) {
+		dev_err(hdev->dev,
+			"failed to create device file device_type\n");
+		goto remove_preboot_ver;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_pci_addr);
+	if (rc) {
+		dev_err(hdev->dev, "failed to create device file pci_addr\n");
+		goto remove_device_type;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_status);
+	if (rc) {
+		dev_err(hdev->dev, "failed to create device file status\n");
+		goto remove_pci_addr;
+	}
+
+	rc = device_create_file(hdev->dev, &dev_attr_write_open_cnt);
+	if (rc) {
+		dev_err(hdev->dev,
+			"failed to create device file write_open_count\n");
+		goto remove_status;
+	}
+
+	hdev->max_power = hdev->asic_prop.max_power_default;
+
+	rc = device_create_file(hdev->dev, &dev_attr_max_power);
+	if (rc) {
+		dev_err(hdev->dev,
+			"failed to create device file max_power\n");
+		goto remove_write_open_cnt;
+	}
+
+	rc = sysfs_create_bin_file(&hdev->dev->kobj, &bin_attr_eeprom);
+	if (rc) {
+		dev_err(hdev->dev, "failed to create EEPROM sysfs entry\n");
+		goto remove_attr_max_power;
+	}
+
+	return 0;
+
+remove_attr_max_power:
+	device_remove_file(hdev->dev, &dev_attr_max_power);
+remove_write_open_cnt:
+	device_remove_file(hdev->dev, &dev_attr_write_open_cnt);
+remove_status:
+	device_remove_file(hdev->dev, &dev_attr_status);
+remove_pci_addr:
+	device_remove_file(hdev->dev, &dev_attr_pci_addr);
+remove_device_type:
+	device_remove_file(hdev->dev, &dev_attr_device_type);
+remove_preboot_ver:
+	device_remove_file(hdev->dev, &dev_attr_preboot_btl_ver);
+remove_thermal_ver:
+	device_remove_file(hdev->dev, &dev_attr_thermal_ver);
+remove_fuse_ver:
+	device_remove_file(hdev->dev, &dev_attr_fuse_ver);
+remove_infineon_ver:
+	device_remove_file(hdev->dev, &dev_attr_infineon_ver);
+remove_cpld_ver:
+	device_remove_file(hdev->dev, &dev_attr_cpld_ver);
+remove_armcp_ver:
+	device_remove_file(hdev->dev, &dev_attr_armcp_ver);
+remove_armcp_kernel_ver:
+	device_remove_file(hdev->dev, &dev_attr_armcp_kernel_ver);
+remove_uboot_ver:
+	device_remove_file(hdev->dev, &dev_attr_uboot_ver);
+remove_pll_profile:
+	device_remove_file(hdev->dev, &dev_attr_high_pll);
+remove_pm_mng_profile:
+	device_remove_file(hdev->dev, &dev_attr_pm_mng_profile);
+remove_device_attr:
+	hdev->asic_funcs->remove_device_attr(hdev);
+
+	return rc;
+}
+
+void hl_sysfs_fini(struct hl_device *hdev)
+{
+	sysfs_remove_bin_file(&hdev->dev->kobj, &bin_attr_eeprom);
+	device_remove_file(hdev->dev, &dev_attr_max_power);
+	device_remove_file(hdev->dev, &dev_attr_write_open_cnt);
+	device_remove_file(hdev->dev, &dev_attr_status);
+	device_remove_file(hdev->dev, &dev_attr_pci_addr);
+	device_remove_file(hdev->dev, &dev_attr_device_type);
+	device_remove_file(hdev->dev, &dev_attr_preboot_btl_ver);
+	device_remove_file(hdev->dev, &dev_attr_thermal_ver);
+	device_remove_file(hdev->dev, &dev_attr_fuse_ver);
+	device_remove_file(hdev->dev, &dev_attr_infineon_ver);
+	device_remove_file(hdev->dev, &dev_attr_cpld_ver);
+	device_remove_file(hdev->dev, &dev_attr_armcp_ver);
+	device_remove_file(hdev->dev, &dev_attr_armcp_kernel_ver);
+	device_remove_file(hdev->dev, &dev_attr_uboot_ver);
+	device_remove_file(hdev->dev, &dev_attr_high_pll);
+	device_remove_file(hdev->dev, &dev_attr_pm_mng_profile);
+	hdev->asic_funcs->remove_device_attr(hdev);
+}
Signature · 1 line
2.17.1
Signature · 2 lines
Sincerely yours,
Mike.
#77 lore raw
In reply to Daniel Vetter
Quoted 60 lines · Daniel Vetter
Quoted 16 lines · Olof Johansson
Quoted 5 lines · Dave Airlie
Quoted 4 lines

I know I won't be able to convince you but I want to say that I think your arguments for full userspace open source are not really technical.

Quoted 8 lines

There is more to keeping a kernel going than technical argument unfortunately.

I guess the question for Greg, Olof etc, is do we care about Linux the kernel, or Linux the open source ecosystem, if the former, these sort of accelerator shim drivers are fine, useless to anyone who doesn't have all the magic hidden userspace, and impossible to support for anyone else, if the latter, we should leave the cost of maintenance to the company benefiting from it and leave maintaining it out of tree.

Quoted 5 lines

As mentioned in my reply to Daniel, I think we've got a history of being pragmatic and finding reasonable trade-offs of what can be open and what can be closed. For example, if truly care about open source ecosystem, drivers that require closed firmware should also be refused.

Firmware has traditionally been different since usually it's looked down, doesn't do much wrt functionality (dumb fifo scheduling at best, not really power management) and so could be reasonably shrugged off as "it's part of hw". If you care about the open graphics ecosystem, i.e. your ability to port the stack to new cpu architectures, new window systems (e.g. android -> xorg, or xorg -> android, or something entirely new like wayland), new, more efficient client interface (vulkan is a very new fad), then having a closed firmware is not going to be a problem. Closed compiler, closed runtime, closed anything else otoh is a serious practical pain.

Unfortunately hw vendors seem to have realized that we (overall community of customers, distro, upstream) are not insisting on open firmware, so they're moving a lot of "valuable sauce" (no really, it's not) into the firmware. PM governors, cpu scheduling algorithms, that kind of stuff. We're not pleased, and there's lots of people doing the behind the scenes work to fix it. One practical problem is that even if we've demonstrated that r/e'ing a uc is no bigger challenge than anything, there's usually this pesky issue with signatures. So we can't force the vendors like we can with the userspace side. Otherwise nouveau would have completely open firmware even for latest chips (like it has for olders).

Quoted 9 lines
Quoted 2 lines

Simple question like If I plug your accelerator into Power or ARM64, where do I get the port of your userspace to use it?

Does demanding complete open userspace get us closer to that goal in reality? By refusing to work with people to enable their hardware, they will still ship their platforms out of tree, using DKMS and all the other ways of getting kernel modules installed to talk to the hardware. And we'd be no closer.

Quoted 3 lines

In the end, they'd open up their userspace when there's business reasons to do so. It's well-known how to work around refusal from us to merge drivers by now, so it's not much leverage in that area.

Quoted 6 lines

Correct. None of the hw vendors had a business reason to open source anything unforunately. Yes, eventually customers started demanding open source and treatening to buy the competition, but this only works if you have multiple reasonably performant & conformant stacks for different vendors. The only way to get these is to reverse engineer them.

That's the grass-roots version of it, and it is indeed a lot of work. What _has_ proven to have success is when companies that would drive real revenue for the vendors have requirements for them to open up, contribute, and participate. In the graphics world it hasn't gotten things all the way to the right spot, but I know first hand that for example Chrome OS's insistence on upstream participation has made significant differences in how several companies interact with our communities.

It's not something that's easy to do when the target is consumer-oriented hardware (which graphics mostly is), but at least for now, these accelerators aren't targeting end users as much as corporate environments, where we do have allies.

Quoted 16 lines

Now reverse-engineering is a major pain in itself (despite all the great tooling gpu folks developed over the past 10 years to convert it from a black art to a repeatable engineering excercise), but if you additionally prefer the vendors closed stack (which you do by allowing to get them to get merged) the r/e'd stack has no chance. And there is not other way to get your open source stack. I can't really go into all the details of the past 15+ of open source gpus, but without the pressure of other r/e'ed stacks and the pressure of having stacks for competitiors (all made possible through aggressive code sharing) we would have 0 open source gfx stacks. All the ones we have either got started with r/e first (and eventually the vendor jumped on board) or survived through r/e and customer efforts (because the vendor planned to abandon it). Another part of this is that we accept userspace only when it's the common upstream (if there is one), to prevent vendors closing down their stacks gradually.

Quoted 5 lines

So yeah I think by not clearly preferring open source over stacks-with-blobs (how radically you do that is a bit a balance act in the end, I think we've maxed out in drivers/gpu on what's practically possible) you'll just make sure that there's never going to be a serious open source stack.

I can confidently say that I would myself clearly give preferential treatment to open stacks when they show up. The trick is how we get there -- do we get there quicker by refusing to work with the partially closed stacks? My viewpoint is that we don't, and that the best way to get there is to bring them in and start working with what we have instead of building separate camps that we later need to figure out how to move.

Quoted 27 lines
Quoted 5 lines
Quoted 4 lines

I'm not the final arbiter on this sort of thing, but I'm definitely going to make sure that anyone who lands this code is explicit in ignoring any experience we've had in this area and in the future will gladly accept "I told you so" :-)

Quoted 8 lines

There's only one final arbiter on any inclusion to code to the kernel, but we tend to sort out most disagreements without going all the way there.

I still think engaging has a better chance of success than rejecting the contributions, especially with clear expectations w.r.t. continued engagement and no second implementations over time. In all honestly, either approach might fail miserably.

This is maybe not clear, but we still work together with the blob folks as much as possible, for demonstration: nvidia sponsored XDC this year, and nvidia engineers have been regularly presenting there. Collaboration happens around the driver interfaces, like loaders (in userspace), buffer sharing, synchronization, negotiation of buffer formats and all that stuff. Do as much enganging as possible, but if you give preferrential treatment to the closed stacks over the open ones (and by default the vendor _always_ gives you a closed stack, or as closed as possible, there's just no business case for them to open up without a customer demanding it and competition providing it too), you will end up with a closed stack for a very long time, maybe forever.

Quoted 13 lines

Even if you insist on an open stack it's going to take years, since the only way to get there is lots of r/e, and you need to have at least 2 stacks or otherwise the customers can't walk away from the negotiation table. So again from gfx experience: The only way to get open stacks is solid competition by open stacks, and customers/distros investing ridiculous amounts of money to r/e the chips and write these open&cross vendor stacks. The business case for vendors to open source their stacks is just not there. Not until they can't sell their chips any other way anymore (nvidia will embrace open stacks as soon as their margins evaporate, not a second earlier, like all the others before them). Maybe at the next hallway track we need to go through a few examples of what all happened and is still happening in the background (here's maybe not a good idea).

Again, the graphics world is different since the volume market has traditionally been consumers, and the split got very deep. What we want to avoid here is to get into the same situation by avoiding the large split.

Look at it another way, these are roughly the options and possible outcomes:

1a. We don't merge these drivers, vendors say "okay then" and open up their whole stacks. We merge the drivers. Then we start working together on moving to a common base.
1b. We don't merge these drivers, the vendors all do their own thing and over the next 5 years, we reverse engineer and start to bring in second implementations of all their code.
2a. We merge these drivers, start close engagement with the vendors, collaborate and converge with their next-gen products (possibly move first-gen over).
2b. We merge these drivers, and vendors still go off on their own and do their own thing. We spend the next 5 years reverse engineering and move over to open, new drivers even though the first ones are in-tree.

1a/2a are successful outcomes. I put 1a at very very low probability. 2b at medium probability with the right allies in the corporate world.

1b/2b are partial failure modes with huge effort needed and a passionate volunteer base.

Both 1a/2a and 1b/2b have similar amounts of work involved. In other words, I don't see how anyone benefits from eliminating (2) as an approach, especially since 1a is an unlikely development of events.

And, guess what -- if we do get open stacks early on, and give heavy preferential treatment to these, we can push others in that direction sooner rather than later, before stacks diverge too far. I just don't see how _not_ engaging is going to help here. Even if we do engage, the worst possible outcome is still the same as not engaging but a good chance for something better.

-Olof

#82 lore raw
In reply to Greg Kroah-Hartman

Hi,

Quoted 41 lines · Greg Kroah-Hartman
Quoted 15 lines · Dave Airlie
Quoted 6 lines · Oded Gabbay

Hello,

For those who don't know me, my name is Oded Gabbay (Kernel Maintainer for AMD's amdkfd driver, worked at RedHat's Desktop group) and I work at Habana Labs since its inception two and a half years ago.

Hey Oded,

So this creates a driver with a userspace facing API via ioctls. Although this isn't a "GPU" driver we have a rule in the graphics drivers are for accelerators that we don't merge userspace API with an appropriate userspace user.

Quoted 4 lines

https://dri.freedesktop.org/docs/drm/gpu/drm-uapi.html#open-source-userspace-requirements

I see nothing in these accelerator drivers that make me think we should be treating them different.

I understand that this is your position on when you accept drivers into the DRM layer, as you need to interact with common interfaces and a massive userspace stack at the same time. And that's wonderful, it allows you to be able to move both sides of that stack forward without removing support for devices that worked on older kernels.

But, that's not really the case with this new driver at all. We add new driver subsystems, and individual drivers, with loads of new ioctls, in every new kernel release. We don't impose on all of them the "your userspace code must be open" rule, so why is this new driver somehow different from them?

Yes, there is the fun legal issue of "derivative works" when talking about a userspace program that is written to only interact with a specific kernel driver using a custom api like this one has, and how the license of the kernel side (GPLv2) affects the userspace side (whatever), but that is something that I leave up to the lawyers who like discussing and enforcing such things.

Quoted 7 lines

When evaluating this driver (note, I saw it for a few revisions before Oded posted it here), all I did was try to make sure that it fit in properly with the kernel apis and methods of operations. Given that there are no in-kernel drivers for this type of device, and that it really is a pretty small shim layer around the hardware, which means that userspace does a lot of the heavy lifting, it is going to be a very hardware-specific user/kernel api, and that shows.

I brought this up because there are sort of, if you squint, three-ish of these already (the OpenCAPI/CAPI ones and now this). Also, Jonathan's comment about CCIX pieces coming as well.

I've talked to a handful of vendors in this space and more or less all of them hope that drivers/misc is still a suitable home for their driver by the time it's ready to post, and I know that if we keep them there, it'll only be one or two more drivers until we have this discussion anyway.

That's really why I brought it up now, to get a clear stance on "Yeah, we know these are all slightly different today, and we're willing to give them a predictable home for the first while as we figure out together how things should look". Keep in mind, this space is also currently a bit of a gold rush, with many people working hard to get to market with near-zero talk between them.

Quoted 4 lines

Sidenote, this could have almost just been a UIO driver, which would have put _ALL_ of the logic in userspace. At least this way we have a chance for the kernel code to be sane and not try to inflict problems on the rest of the system.

Yeah, and sharing hardware when you have userspace drivers tends to need a bunch of synchronization and coordination which leads to taller (closed?) stacks there. Having resource arbitration and sharing assisted by the kernel is usually the right thing, and we should encourage that.

Quoted 9 lines

Going forward, it would be wonderful if we could come up with a unified api for how to interact with these types of hardware accelerators, but given the newness of this industry, and the vastly different ways people are trying to solve the problem, that is going to take a few attempts, and many years before we can get there. Until then, taking drivers like this into the kernel tree makes sense as that way all of our users will be able to use that hardware, and better yet, the rest of us can learn more about how this stuff works so that we can help out with that api generation when it happens.

Exactly my viewpoint as well, combined with not pushing vendors towards nvidia models by default even if they start out separate, and having a chance to find inroads with them on engineering levels when they come to us with the drivers.

Absolutely best chance for success is _always_ when we can engage with the vendor engineers as peers, instead of going up and down the corporate charts first (you often need to do a bit of both, but having allies in engineering makes it much easier).

Quoted 6 lines

So for now, I have no objection to taking this type of driver into the tree. Yes, it would be wonderful if we had an open userspace program to drive it so that we could actually test and make changes to the api over time, but I think that is something that the submitting company needs to realize will be better for them to do, as for right now, all of that testing and changes are their responsibility.

I do think having requirements of being able to exercise the hardware is really valuable, and we should consider what a requirement for that would look like. For the Habana case that could be a separate low-level library and a test workload on top. For FPGA cases it could be a well-known reference bitstream with the vendor reference control/communication path + similar low-level pieces.

Quoted 5 lines

As for what directory the code should live in, I suggested "misc" as there was no other universal location, and I hate to see new subsystems be created with only one driver, as that's pretty sad. But it's just a name/location, I have no dog in the fight, so I really don't care where it ends up in the tree, just as long as it gets merged somewhere :)

I'm usually one to push back against new subsystems too, especially when I see a framework proposal with just one driver. In this case, given that we all know more vendors will come along, I think it makes sense to take the discussion and establish structure now. This should give some clarity to those who are out there that we haven't seen yet, and give them a chance to prepare for things such as the low-level userspace pieces mentioned above.

So I think setting this up now is the right thing to do, we know there will be more material here and having a common aggregation of it makes sense.

-Olof

#78 lore raw
In reply to Olof Johansson
Quoted 78 lines · Olof Johansson
Quoted 60 lines · Daniel Vetter
Quoted 16 lines · Olof Johansson
Quoted 5 lines · Dave Airlie
Quoted 4 lines

I know I won't be able to convince you but I want to say that I think your arguments for full userspace open source are not really technical.

Quoted 8 lines

There is more to keeping a kernel going than technical argument unfortunately.

I guess the question for Greg, Olof etc, is do we care about Linux the kernel, or Linux the open source ecosystem, if the former, these sort of accelerator shim drivers are fine, useless to anyone who doesn't have all the magic hidden userspace, and impossible to support for anyone else, if the latter, we should leave the cost of maintenance to the company benefiting from it and leave maintaining it out of tree.

Quoted 5 lines

As mentioned in my reply to Daniel, I think we've got a history of being pragmatic and finding reasonable trade-offs of what can be open and what can be closed. For example, if truly care about open source ecosystem, drivers that require closed firmware should also be refused.

Firmware has traditionally been different since usually it's looked down, doesn't do much wrt functionality (dumb fifo scheduling at best, not really power management) and so could be reasonably shrugged off as "it's part of hw". If you care about the open graphics ecosystem, i.e. your ability to port the stack to new cpu architectures, new window systems (e.g. android -> xorg, or xorg -> android, or something entirely new like wayland), new, more efficient client interface (vulkan is a very new fad), then having a closed firmware is not going to be a problem. Closed compiler, closed runtime, closed anything else otoh is a serious practical pain.

Unfortunately hw vendors seem to have realized that we (overall community of customers, distro, upstream) are not insisting on open firmware, so they're moving a lot of "valuable sauce" (no really, it's not) into the firmware. PM governors, cpu scheduling algorithms, that kind of stuff. We're not pleased, and there's lots of people doing the behind the scenes work to fix it. One practical problem is that even if we've demonstrated that r/e'ing a uc is no bigger challenge than anything, there's usually this pesky issue with signatures. So we can't force the vendors like we can with the userspace side. Otherwise nouveau would have completely open firmware even for latest chips (like it has for olders).

Quoted 9 lines
Quoted 2 lines

Simple question like If I plug your accelerator into Power or ARM64, where do I get the port of your userspace to use it?

Does demanding complete open userspace get us closer to that goal in reality? By refusing to work with people to enable their hardware, they will still ship their platforms out of tree, using DKMS and all the other ways of getting kernel modules installed to talk to the hardware. And we'd be no closer.

Quoted 3 lines

In the end, they'd open up their userspace when there's business reasons to do so. It's well-known how to work around refusal from us to merge drivers by now, so it's not much leverage in that area.

Quoted 6 lines

Correct. None of the hw vendors had a business reason to open source anything unforunately. Yes, eventually customers started demanding open source and treatening to buy the competition, but this only works if you have multiple reasonably performant & conformant stacks for different vendors. The only way to get these is to reverse engineer them.

That's the grass-roots version of it, and it is indeed a lot of work. What _has_ proven to have success is when companies that would drive real revenue for the vendors have requirements for them to open up, contribute, and participate. In the graphics world it hasn't gotten things all the way to the right spot, but I know first hand that for example Chrome OS's insistence on upstream participation has made significant differences in how several companies interact with our communities.

Quoted 4 lines

It's not something that's easy to do when the target is consumer-oriented hardware (which graphics mostly is), but at least for now, these accelerators aren't targeting end users as much as corporate environments, where we do have allies.

Cros is the only reason we do have the stack we do in graphics. They've been investing ridiculous amounts of money into this, and they actually invest even more now than 1-2 years ago. I know for a fact that without cros a few of the open stacks would have substantially, if not completely, closed down again. If you don't believe that, look at how debian treats the latest intel libva driver as partially non-free (because it's become that).

Quoted 101 lines
Quoted 16 lines

Now reverse-engineering is a major pain in itself (despite all the great tooling gpu folks developed over the past 10 years to convert it from a black art to a repeatable engineering excercise), but if you additionally prefer the vendors closed stack (which you do by allowing to get them to get merged) the r/e'd stack has no chance. And there is not other way to get your open source stack. I can't really go into all the details of the past 15+ of open source gpus, but without the pressure of other r/e'ed stacks and the pressure of having stacks for competitiors (all made possible through aggressive code sharing) we would have 0 open source gfx stacks. All the ones we have either got started with r/e first (and eventually the vendor jumped on board) or survived through r/e and customer efforts (because the vendor planned to abandon it). Another part of this is that we accept userspace only when it's the common upstream (if there is one), to prevent vendors closing down their stacks gradually.

Quoted 5 lines

So yeah I think by not clearly preferring open source over stacks-with-blobs (how radically you do that is a bit a balance act in the end, I think we've maxed out in drivers/gpu on what's practically possible) you'll just make sure that there's never going to be a serious open source stack.

I can confidently say that I would myself clearly give preferential treatment to open stacks when they show up. The trick is how we get there -- do we get there quicker by refusing to work with the partially closed stacks? My viewpoint is that we don't, and that the best way to get there is to bring them in and start working with what we have instead of building separate camps that we later need to figure out how to move.

Quoted 27 lines
Quoted 5 lines
Quoted 4 lines

I'm not the final arbiter on this sort of thing, but I'm definitely going to make sure that anyone who lands this code is explicit in ignoring any experience we've had in this area and in the future will gladly accept "I told you so" :-)

Quoted 8 lines

There's only one final arbiter on any inclusion to code to the kernel, but we tend to sort out most disagreements without going all the way there.

I still think engaging has a better chance of success than rejecting the contributions, especially with clear expectations w.r.t. continued engagement and no second implementations over time. In all honestly, either approach might fail miserably.

This is maybe not clear, but we still work together with the blob folks as much as possible, for demonstration: nvidia sponsored XDC this year, and nvidia engineers have been regularly presenting there. Collaboration happens around the driver interfaces, like loaders (in userspace), buffer sharing, synchronization, negotiation of buffer formats and all that stuff. Do as much enganging as possible, but if you give preferrential treatment to the closed stacks over the open ones (and by default the vendor _always_ gives you a closed stack, or as closed as possible, there's just no business case for them to open up without a customer demanding it and competition providing it too), you will end up with a closed stack for a very long time, maybe forever.

Quoted 13 lines

Even if you insist on an open stack it's going to take years, since the only way to get there is lots of r/e, and you need to have at least 2 stacks or otherwise the customers can't walk away from the negotiation table. So again from gfx experience: The only way to get open stacks is solid competition by open stacks, and customers/distros investing ridiculous amounts of money to r/e the chips and write these open&cross vendor stacks. The business case for vendors to open source their stacks is just not there. Not until they can't sell their chips any other way anymore (nvidia will embrace open stacks as soon as their margins evaporate, not a second earlier, like all the others before them). Maybe at the next hallway track we need to go through a few examples of what all happened and is still happening in the background (here's maybe not a good idea).

Again, the graphics world is different since the volume market has traditionally been consumers, and the split got very deep. What we want to avoid here is to get into the same situation by avoiding the large split.

Look at it another way, these are roughly the options and possible outcomes:

1a. We don't merge these drivers, vendors say "okay then" and open up their whole stacks. We merge the drivers. Then we start working together on moving to a common base.
1b. We don't merge these drivers, the vendors all do their own thing and over the next 5 years, we reverse engineer and start to bring in second implementations of all their code.
2a. We merge these drivers, start close engagement with the vendors, collaborate and converge with their next-gen products (possibly move first-gen over).
2b. We merge these drivers, and vendors still go off on their own and do their own thing. We spend the next 5 years reverse engineering and move over to open, new drivers even though the first ones are in-tree.

1a/2a are successful outcomes. I put 1a at very very low probability. 2b at medium probability with the right allies in the corporate world.

1b/2b are partial failure modes with huge effort needed and a passionate volunteer base.

Both 1a/2a and 1b/2b have similar amounts of work involved. In other words, I don't see how anyone benefits from eliminating (2) as an approach, especially since 1a is an unlikely development of events.

Quoted 6 lines

And, guess what -- if we do get open stacks early on, and give heavy preferential treatment to these, we can push others in that direction sooner rather than later, before stacks diverge too far. I just don't see how _not_ engaging is going to help here. Even if we do engage, the worst possible outcome is still the same as not engaging but a good chance for something better.

If you do have allies with big purses (both product buying power and the willingness & ability to just hire a driver team and create facts if the vendor doesnt cooperate), then you can directly make option 1a
happen: vendors open their stacks, you merge them (and of course you start engaging right away). If you don't have that, then you'll have 1b or 2b and will entirely depend upon students and other fools with too much time to r/e and write your open stack. And for those 1b is the substantially better option. Only cases where 2a works is if some team internally in the vendor makes it happen and somehow convinces management that there's a real market for this (or going to be). But if that real market (said customer with a big purse and an insistence on open source) does not materialize, the effort will crumble again after a few years.

Anyway I don't think we'll convince each other of anything here, so we'll just see what happens and we have a nice chat in a few years about this all :-) Maybe if you want someone else still from the graphics hippies club, perhaps chat with Keith Packard. He's got quite a bit of experience and has seen even more dumpster fires than Dave, Jerome or me.

Cheers, Daniel

Signature · 3 lines
Daniel Vetter
Software Engineer, Intel Corporation
+41 (0) 79 365 57 48 - http://blog.ffwll.ch
#83 lore raw
In reply to Olof Johansson
Quoted 15 lines · Olof Johansson

On Thu, Jan 24, 2019 at 11:37 PM Greg Kroah-Hartman

Quoted 5 lines

As for what directory the code should live in, I suggested "misc" as there was no other universal location, and I hate to see new subsystems be created with only one driver, as that's pretty sad. But it's just a name/location, I have no dog in the fight, so I really don't care where it ends up in the tree, just as long as it gets merged somewhere :)

I'm usually one to push back against new subsystems too, especially when I see a framework proposal with just one driver. In this case, given that we all know more vendors will come along, I think it makes sense to take the discussion and establish structure now. This should give some clarity to those who are out there that we haven't seen yet, and give them a chance to prepare for things such as the low-level userspace pieces mentioned above.

Quoted 3 lines

So I think setting this up now is the right thing to do, we know there will be more material here and having a common aggregation of it makes sense.

Ok, how about:
drivers/deep_thought/

as a first proposal.

Let the bikeshedding begin! :)

greg k-h

#84 lore raw
Quoted 21 lines · Greg Kroah-Hartman
Quoted 15 lines · Olof Johansson

On Thu, Jan 24, 2019 at 11:37 PM Greg Kroah-Hartman

Quoted 5 lines

As for what directory the code should live in, I suggested "misc" as there was no other universal location, and I hate to see new subsystems be created with only one driver, as that's pretty sad. But it's just a name/location, I have no dog in the fight, so I really don't care where it ends up in the tree, just as long as it gets merged somewhere :)

I'm usually one to push back against new subsystems too, especially when I see a framework proposal with just one driver. In this case, given that we all know more vendors will come along, I think it makes sense to take the discussion and establish structure now. This should give some clarity to those who are out there that we haven't seen yet, and give them a chance to prepare for things such as the low-level userspace pieces mentioned above.

Quoted 3 lines

So I think setting this up now is the right thing to do, we know there will be more material here and having a common aggregation of it makes sense.

Quoted 6 lines

Ok, how about:
drivers/deep_thought/

as a first proposal.

Let the bikeshedding begin! :)

My original proposal upthread was driver/accel. I'm not sure whether Dave and/or anyone else wants to participate to start though, I hope they will at least join in once things are heading in the direction they want.

I'll post patches with the proposed moves and documentation of expectations shortly, hopefully to collect acks.

-Olof

#60 lore raw
In reply to Andrew Donnellan
Quoted 20 lines · Andrew Donnellan
Quoted 18 lines · Olof Johansson

But, I think the largest question I have (for a broader audience) is:

I predict that we will see a handful of these kind of devices over the upcoming future -- definitely from ML accelerators but maybe also for other kinds of processing, where there's a command-based, buffer-based setup sending workloads to an offload engine and getting results back. While the first waves will all look different due to design trade-offs made in isolation, I think it makes sense to group them in one bucket instead of merging them through drivers/misc, if nothing else to encourage more cross-collaboration over time. First steps in figuring out long-term suitable frameworks is to get a survey of a few non-shared implementations.

So, I'd like to propose a drivers/accel drivers subtree, and I'd be happy to bootstrap it with a small group (@Dave Airlie: I think your input from GPU land be very useful, want to join in?). Individual drivers maintained by existing maintainers, of course.

Quoted 7 lines
Quoted 3 lines

I think it might make sense to move the CAPI/OpenCAPI drivers over as well -- not necessarily to change those drivers, but to group them with the rest as more show up.

For cxl/ocxl, I have no objection to moving to this new subtree if that's what we all agree to do. (what do people do about UAPI headers in this situation? keep them where they are in misc/?)

How about moving them but keeping a stub in misc that just includes the moved file?

Quoted 3 lines

If we do go ahead and set up this new subtree, perhaps we can use the mailing list I set up at [email protected] but we haven't really started using...

I've lost all lists.ozlabs.org muscle memory these days, but that seems reasonable to me.

-Olof

#85 lore raw

cover HW accel subsystem

In reply to Olof Johansson

Per discussion in on the Habana Labs driver submission
(https://lore.kernel.org/lkml/[email protected]/),
there seems to be time to create a separate subsystem for hw accellerators instead of letting them proliferate around the tree (and/or in misc).

There's difference in opinion on how stringent the requirements are for a fully open stack for these kind of drivers. I've documented the middle road approach in the first patch (requiring some sort of open low-level userspace for the kernel interaction, and a way to use/test it).

Comments and suggestions for better approaches are definitely welcome.

#86 lore raw

PATCH 1/5 drivers/accel: Introduce subsystem

We're starting to see more of these kind of devices, the current upcoming wave will likely be around machine learning and inference engines. A few drivers have been added to drivers/misc for this, but it's timely to make it into a separate group of drivers/subsystem, to make it easier to find them, and to encourage collaboration between contributors.

Over time, we expect to build shared frameworks that the drivers will make use of, but how that framework needs to look like to fill the needs is still unclear, and the best way to gain that knowledge is to give the disparate implementations a shared location.

There has been some controversy around expectations for userspace stacks being open. The clear preference is to see that happen, and any driver and platform stack that is delivered like that will be given preferential treatment, and at some point in the future it might become the requirement. Until then, the bare minimum we need is an open low-level userspace such that the driver and HW interfaces can be exercised if someone is modifying the driver, even if the full details of the workload are not always available.

Bootstrapping this with myself and Greg as maintainers (since the current drivers will be moving out of drivers/misc). Looking forward to expanding that group over time.

Cc Greg Kroah-Hartman <[email protected]>
---
 MAINTAINERS            |  8 ++++++++
 drivers/Kconfig        |  2 ++
 drivers/Makefile       |  1 +
 drivers/accel/Kconfig  | 16 ++++++++++++++++
 drivers/accel/Makefile |  5 +++++
 5 files changed, 32 insertions(+)
 create mode 100644 drivers/accel/Kconfig
 create mode 100644 drivers/accel/Makefile
MAINTAINERS +8 -0
index ddcdc29dfe1f6..8a9bbaf8f6e90 100644
@@ -7033,6 +7033,14 @@ W:	https://linuxtv.org
 S:	Supported
 F:	drivers/media/platform/sti/hva
 
+HW ACCELERATOR OFFLOAD SUBSYSTEM
+M:	Olof Johansson <[email protected]>
+M:	Greg Kroah-Hartman <[email protected]>
+L:	[email protected]
+S:	Supported
+F:	drivers/accel/
+F:	Documentation/accelerators/
+
 HWPOISON MEMORY FAILURE HANDLING
 M:	Naoya Horiguchi <[email protected]>
 L:	[email protected]
drivers/Kconfig +2 -0
index 4f9f99057ff85..3cc461f325569 100644
@@ -228,4 +228,6 @@ source "drivers/siox/Kconfig"
 
 source "drivers/slimbus/Kconfig"
 
+source "drivers/accel/Kconfig"
+
 endmenu
drivers/Makefile +1 -0
index 04da7876032cc..e4be06579cc5d 100644
@@ -186,3 +186,4 @@ obj-$(CONFIG_MULTIPLEXER)	+= mux/
 obj-$(CONFIG_UNISYS_VISORBUS)	+= visorbus/
 obj-$(CONFIG_SIOX)		+= siox/
 obj-$(CONFIG_GNSS)		+= gnss/
+obj-$(CONFIG_ACCEL)		+= accel/
drivers/accel/Kconfig new file +16 -0
new file mode 100644
index 0000000000000..13b36c0398895
@@ -0,0 +1,16 @@
+#
+# Drivers for hardware offload accelerators
+# See Documentation/accel/README.rst for more details
+#
+
+menuconfig ACCEL
+	bool "Hardware offload accelerator support"
+        help
+	  HW offload accelerators are used for high-bandwidth workloads
+	  where a higher-level kernel/userspace interface isn't suitable.
+
+if ACCEL
+
+comment "HW Accellerator drivers"
+
+endif
drivers/accel/Makefile new file +5 -0
new file mode 100644
index 0000000000000..343bbb8f45a14
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Makefile for accel devices
+#
+
Signature · 1 line
2.11.0
#94 lore raw

PATCH 3/5 drivers/accel: cxl: Move non-uapi include files

In reply to Olof Johansson

Separate to expose the edits vs pure moves.

Cc Greg Kroah-Hartman <[email protected]>
Cc Frederic Barrat <[email protected]>
Cc Andrew Donnellan <[email protected]>
Cc Arnd Bergmann <[email protected]>
---
 MAINTAINERS                               | 2 +-
 arch/powerpc/include/asm/pnv-pci.h        | 2 +-
 arch/powerpc/mm/copro_fault.c             | 2 +-
 arch/powerpc/mm/hash_native_64.c          | 2 +-
 arch/powerpc/mm/pgtable-book3s64.c        | 2 +-
 arch/powerpc/platforms/powernv/pci-ioda.c | 2 +-
 drivers/accel/cxl/api.c                   | 2 +-
 drivers/accel/cxl/base.c                  | 2 +-
 drivers/accel/cxl/cxl.h                   | 4 ++--
 drivers/accel/cxl/cxllib.c                | 2 +-
 drivers/accel/cxl/irq.c                   | 2 +-
 drivers/accel/cxl/main.c                  | 2 +-
 drivers/accel/cxl/native.c                | 2 +-
 drivers/accel/cxl/pci.c                   | 2 +-
 drivers/accel/cxl/vphb.c                  | 2 +-
 drivers/scsi/cxlflash/cxl_hw.c            | 2 +-
 include/{misc => linux/accel}/cxl-base.h  | 4 ++--
 include/{misc => linux/accel}/cxl.h       | 6 +++---
 include/{misc => linux/accel}/cxllib.h    | 6 +++---
 19 files changed, 25 insertions(+), 25 deletions(-)
 rename include/{misc => linux/accel}/cxl-base.h (94%)
 rename include/{misc => linux/accel}/cxl.h (99%)
 rename include/{misc => linux/accel}/cxllib.h (97%)
MAINTAINERS +1 -1
index 93fbfed6e6915..97aed390129f0 100644
@@ -4215,7 +4215,7 @@ L:	[email protected]
 S:	Supported
 F:	arch/powerpc/platforms/powernv/pci-cxl.c
 F:	drivers/accel/cxl/
-F:	include/misc/cxl*
+F:	include/linux/accel/cxl*
 F:	include/uapi/misc/cxl.h
 F:	Documentation/powerpc/cxl.txt
 F:	Documentation/ABI/testing/sysfs-class-cxl
arch/powerpc/include/asm/pnv-pci.h +1 -1
index 630eb8b1b7ed3..17e0ded18ffd6 100644
@@ -13,7 +13,7 @@
 #include <linux/pci.h>
 #include <linux/pci_hotplug.h>
 #include <linux/irq.h>
-#include <misc/cxl-base.h>
+#include <linux/accel/cxl-base.h>
 #include <asm/opal-api.h>
 
 #define PCI_SLOT_ID_PREFIX	(1UL << 63)
arch/powerpc/mm/copro_fault.c +1 -1
index c8da352e8686c..441a51d9c8f8a 100644
@@ -26,7 +26,7 @@
 #include <asm/reg.h>
 #include <asm/copro.h>
 #include <asm/spu.h>
-#include <misc/cxl-base.h>
+#include <linux/accel/cxl-base.h>
 
 /*
  * This ought to be kept in sync with the powerpc specific do_page_fault
arch/powerpc/mm/hash_native_64.c +1 -1
index aaa28fd918fe4..b6f49c98aa732 100644
@@ -31,7 +31,7 @@
 #include <asm/ppc-opcode.h>
 #include <asm/feature-fixups.h>
 
-#include <misc/cxl-base.h>
+#include <linux/accel/cxl-base.h>
 
 #ifdef DEBUG_LOW
 #define DBG_LOW(fmt...) udbg_printf(fmt)
arch/powerpc/mm/pgtable-book3s64.c +1 -1
index 55876b7e38130..34bdd8bca31e6 100644
@@ -10,7 +10,7 @@
 #include <linux/sched.h>
 #include <linux/mm_types.h>
 #include <linux/memblock.h>
-#include <misc/cxl-base.h>
+#include <linux/accel/cxl-base.h>
 
 #include <asm/pgalloc.h>
 #include <asm/tlb.h>
arch/powerpc/platforms/powernv/pci-ioda.c +1 -1
index 7db3119f8a5b3..0506eb74b99b6 100644
@@ -41,7 +41,7 @@
 #include <asm/pnv-pci.h>
 #include <asm/mmzone.h>
 
-#include <misc/cxl-base.h>
+#include <linux/accel/cxl-base.h>
 
 #include "powernv.h"
 #include "pci.h"
drivers/accel/cxl/api.c +1 -1
index 750470ef2049b..220944d7a398c 100644
@@ -10,7 +10,7 @@
 #include <linux/pci.h>
 #include <linux/slab.h>
 #include <linux/file.h>
-#include <misc/cxl.h>
+#include <linux/accel/cxl.h>
 #include <linux/module.h>
 #include <linux/mount.h>
 #include <linux/sched/mm.h>
drivers/accel/cxl/base.c +1 -1
index 7557835cdfcd6..bd2958a7a379a 100644
@@ -10,7 +10,7 @@
 #include <linux/module.h>
 #include <linux/rcupdate.h>
 #include <asm/errno.h>
-#include <misc/cxl-base.h>
+#include <linux/accel/cxl-base.h>
 #include <linux/of_platform.h>
 #include "cxl.h"
 
drivers/accel/cxl/cxl.h +2 -2
index d1d927ccb589c..82457ccc58cad 100644
@@ -22,9 +22,9 @@
 #include <asm/cputable.h>
 #include <asm/mmu.h>
 #include <asm/reg.h>
-#include <misc/cxl-base.h>
+#include <linux/accel/cxl-base.h>
 
-#include <misc/cxl.h>
+#include <linux/accel/cxl.h>
 #include <uapi/misc/cxl.h>
 
 extern uint cxl_verbose;
drivers/accel/cxl/cxllib.c +1 -1
index 5a3f912552585..ba5cde62e030f 100644
@@ -10,7 +10,7 @@
 #include <linux/hugetlb.h>
 #include <linux/sched/mm.h>
 #include <asm/pnv-pci.h>
-#include <misc/cxllib.h>
+#include <linux/accel/cxllib.h>
 
 #include "cxl.h"
 
drivers/accel/cxl/irq.c +1 -1
index ce08a9f22308f..6f55130dd014c 100644
@@ -14,7 +14,7 @@
 #include <linux/slab.h>
 #include <linux/pid.h>
 #include <asm/cputable.h>
-#include <misc/cxl-base.h>
+#include <linux/accel/cxl-base.h>
 
 #include "cxl.h"
 #include "trace.h"
drivers/accel/cxl/main.c +1 -1
index f35406be465a5..f49edfe0371d2 100644
@@ -22,7 +22,7 @@
 #include <linux/sched/task.h>
 
 #include <asm/cputable.h>
-#include <misc/cxl-base.h>
+#include <linux/accel/cxl-base.h>
 
 #include "cxl.h"
 #include "trace.h"
drivers/accel/cxl/native.c +1 -1
index c9d5d82dce8ec..e9b8116a5e34b 100644
@@ -17,7 +17,7 @@
 #include <linux/delay.h>
 #include <asm/synch.h>
 #include <asm/switch_to.h>
-#include <misc/cxl-base.h>
+#include <linux/accel/cxl-base.h>
 
 #include "cxl.h"
 #include "trace.h"
drivers/accel/cxl/pci.c +1 -1
index c79ba1c699ad1..ff8d0b5679c43 100644
@@ -24,7 +24,7 @@
 #include <asm/reg.h>
 
 #include "cxl.h"
-#include <misc/cxl.h>
+#include <linux/accel/cxl.h>
 
 
 #define CXL_PCI_VSEC_ID	0x1280
drivers/accel/cxl/vphb.c +1 -1
index 49da2f744bbf1..c3670d8b4a252 100644
@@ -8,7 +8,7 @@
  */
 
 #include <linux/pci.h>
-#include <misc/cxl.h>
+#include <linux/accel/cxl.h>
 #include "cxl.h"
 
 static int cxl_pci_probe_mode(struct pci_bus *bus)
drivers/scsi/cxlflash/cxl_hw.c +1 -1
index b42da88386bdd..bb3b6b9443062 100644
@@ -12,7 +12,7 @@
  * 2 of the License, or (at your option) any later version.
  */
 
-#include <misc/cxl.h>
+#include <linux/accel/cxl.h>
 
 #include "backend.h"
 
include/linux/accel/cxl-base.h renamed from include/misc/cxl-base.h +2 -2
similarity index 94%
rename from include/misc/cxl-base.h
rename to include/linux/accel/cxl-base.h
index f53808fa638ab..8e7825693f7de 100644
@@ -7,8 +7,8 @@
  * 2 of the License, or (at your option) any later version.
  */
 
-#ifndef _MISC_CXL_BASE_H
-#define _MISC_CXL_BASE_H
+#ifndef _LINUX_ACCEL_CXL_BASE_H
+#define _LINUX_ACCEL_CXL_BASE_H
 
 #ifdef CONFIG_CXL_BASE
 
include/linux/accel/cxl.h renamed from include/misc/cxl.h +3 -3
similarity index 99%
rename from include/misc/cxl.h
rename to include/linux/accel/cxl.h
index ea9ff4a1a9ca5..07c3942c62ea1 100644
@@ -7,8 +7,8 @@
  * 2 of the License, or (at your option) any later version.
  */
 
-#ifndef _MISC_CXL_H
-#define _MISC_CXL_H
+#ifndef _LINUX_ACCEL_CXL_H
+#define _LINUX_ACCEL_CXL_H
 
 #include <linux/pci.h>
 #include <linux/poll.h>
@@ -266,4 +266,4 @@ void cxl_set_driver_ops(struct cxl_context *ctx,
 void cxl_context_events_pending(struct cxl_context *ctx,
 				unsigned int new_events);
 
-#endif /* _MISC_CXL_H */
+#endif /* _LINUX_ACCEL_CXL_H */
include/linux/accel/cxllib.h renamed from include/misc/cxllib.h +3 -3
similarity index 97%
rename from include/misc/cxllib.h
rename to include/linux/accel/cxllib.h
index e5aa29f019a6b..ef045430a9679 100644
@@ -7,8 +7,8 @@
  * 2 of the License, or (at your option) any later version.
  */
 
-#ifndef _MISC_CXLLIB_H
-#define _MISC_CXLLIB_H
+#ifndef _LINUX_ACCEL_CXLLIB_H
+#define _LINUX_ACCEL_CXLLIB_H
 
 #include <linux/pci.h>
 #include <asm/reg.h>
@@ -130,4 +130,4 @@ int cxllib_get_PE_attributes(struct task_struct *task,
 int cxllib_handle_fault(struct mm_struct *mm, u64 addr, u64 size, u64 flags);
 
 
-#endif /* _MISC_CXLLIB_H */
+#endif /* _LINUX_ACCEL_CXLLIB_H */
Signature · 1 line
2.11.0
#95 lore raw

PATCH 4/5 ocxl: Move to drivers/accel

In reply to Olof Johansson

Move include files in separate commit, so leave them alone for now.

Cc Greg Kroah-Hartman <[email protected]>
Cc Frederic Barrat <[email protected]>
Cc Andrew Donnellan <[email protected]>
Cc Arnd Bergmann <[email protected]>
---
 MAINTAINERS                                  | 2 +-
 drivers/accel/Kconfig                        | 1 +
 drivers/accel/Makefile                       | 1 +
 drivers/{misc => accel}/ocxl/Kconfig         | 0
 drivers/{misc => accel}/ocxl/Makefile        | 0
 drivers/{misc => accel}/ocxl/afu_irq.c       | 0
 drivers/{misc => accel}/ocxl/config.c        | 0
 drivers/{misc => accel}/ocxl/context.c       | 0
 drivers/{misc => accel}/ocxl/file.c          | 0
 drivers/{misc => accel}/ocxl/link.c          | 0
 drivers/{misc => accel}/ocxl/main.c          | 0
 drivers/{misc => accel}/ocxl/ocxl_internal.h | 0
 drivers/{misc => accel}/ocxl/pasid.c         | 0
 drivers/{misc => accel}/ocxl/pci.c           | 0
 drivers/{misc => accel}/ocxl/sysfs.c         | 0
 drivers/{misc => accel}/ocxl/trace.c         | 0
 drivers/{misc => accel}/ocxl/trace.h         | 0
 drivers/misc/Kconfig                         | 1 -
 drivers/misc/Makefile                        | 1 -
 19 files changed, 3 insertions(+), 3 deletions(-)
 rename drivers/{misc => accel}/ocxl/Kconfig (100%)
 rename drivers/{misc => accel}/ocxl/Makefile (100%)
 rename drivers/{misc => accel}/ocxl/afu_irq.c (100%)
 rename drivers/{misc => accel}/ocxl/config.c (100%)
 rename drivers/{misc => accel}/ocxl/context.c (100%)
 rename drivers/{misc => accel}/ocxl/file.c (100%)
 rename drivers/{misc => accel}/ocxl/link.c (100%)
 rename drivers/{misc => accel}/ocxl/main.c (100%)
 rename drivers/{misc => accel}/ocxl/ocxl_internal.h (100%)
 rename drivers/{misc => accel}/ocxl/pasid.c (100%)
 rename drivers/{misc => accel}/ocxl/pci.c (100%)
 rename drivers/{misc => accel}/ocxl/sysfs.c (100%)
 rename drivers/{misc => accel}/ocxl/trace.c (100%)
 rename drivers/{misc => accel}/ocxl/trace.h (100%)
MAINTAINERS +1 -1
index 97aed390129f0..a1b2ba3bd402d 100644
@@ -11012,7 +11012,7 @@ L:	[email protected]
 S:	Supported
 F:	arch/powerpc/platforms/powernv/ocxl.c
 F:	arch/powerpc/include/asm/pnv-ocxl.h
-F:	drivers/misc/ocxl/
+F:	drivers/accel/ocxl/
 F:	include/misc/ocxl*
 F:	include/uapi/misc/ocxl.h
 F:	Documentation/accelerators/ocxl.rst
drivers/accel/Kconfig +1 -0
index c0754448efdf0..1790630c560e6 100644
@@ -14,5 +14,6 @@ if ACCEL
 comment "HW Accellerator drivers"
 
 source "drivers/accel/cxl/Kconfig"
+source "drivers/accel/ocxl/Kconfig"
 
 endif
drivers/accel/Makefile +1 -0
index 752a54e227ad7..313867582ff5a 100644
@@ -4,3 +4,4 @@
 #
 
 obj-$(CONFIG_CXL_BASE)		+= cxl/
+obj-$(CONFIG_OCXL)		+= ocxl/
drivers/accel/ocxl/Kconfig renamed from drivers/misc/ocxl/Kconfig +0 -0
similarity index 100%
rename from drivers/misc/ocxl/Kconfig
rename to drivers/accel/ocxl/Kconfig
drivers/accel/ocxl/Makefile renamed from drivers/misc/ocxl/Makefile +0 -0
similarity index 100%
rename from drivers/misc/ocxl/Makefile
rename to drivers/accel/ocxl/Makefile
drivers/accel/ocxl/afu_irq.c renamed from drivers/misc/ocxl/afu_irq.c +0 -0
similarity index 100%
rename from drivers/misc/ocxl/afu_irq.c
rename to drivers/accel/ocxl/afu_irq.c
drivers/accel/ocxl/config.c renamed from drivers/misc/ocxl/config.c +0 -0
similarity index 100%
rename from drivers/misc/ocxl/config.c
rename to drivers/accel/ocxl/config.c
drivers/accel/ocxl/context.c renamed from drivers/misc/ocxl/context.c +0 -0
similarity index 100%
rename from drivers/misc/ocxl/context.c
rename to drivers/accel/ocxl/context.c
drivers/accel/ocxl/file.c renamed from drivers/misc/ocxl/file.c +0 -0
similarity index 100%
rename from drivers/misc/ocxl/file.c
rename to drivers/accel/ocxl/file.c
drivers/accel/ocxl/link.c renamed from drivers/misc/ocxl/link.c +0 -0
similarity index 100%
rename from drivers/misc/ocxl/link.c
rename to drivers/accel/ocxl/link.c
drivers/accel/ocxl/main.c renamed from drivers/misc/ocxl/main.c +0 -0
similarity index 100%
rename from drivers/misc/ocxl/main.c
rename to drivers/accel/ocxl/main.c
drivers/accel/ocxl/ocxl_internal.h renamed from drivers/misc/ocxl/ocxl_internal.h +0 -0
similarity index 100%
rename from drivers/misc/ocxl/ocxl_internal.h
rename to drivers/accel/ocxl/ocxl_internal.h
drivers/accel/ocxl/pasid.c renamed from drivers/misc/ocxl/pasid.c +0 -0
similarity index 100%
rename from drivers/misc/ocxl/pasid.c
rename to drivers/accel/ocxl/pasid.c
drivers/accel/ocxl/pci.c renamed from drivers/misc/ocxl/pci.c +0 -0
similarity index 100%
rename from drivers/misc/ocxl/pci.c
rename to drivers/accel/ocxl/pci.c
drivers/accel/ocxl/sysfs.c renamed from drivers/misc/ocxl/sysfs.c +0 -0
similarity index 100%
rename from drivers/misc/ocxl/sysfs.c
rename to drivers/accel/ocxl/sysfs.c
drivers/accel/ocxl/trace.c renamed from drivers/misc/ocxl/trace.c +0 -0
similarity index 100%
rename from drivers/misc/ocxl/trace.c
rename to drivers/accel/ocxl/trace.c
drivers/accel/ocxl/trace.h renamed from drivers/misc/ocxl/trace.h +0 -0
similarity index 100%
rename from drivers/misc/ocxl/trace.h
rename to drivers/accel/ocxl/trace.h
drivers/misc/Kconfig +0 -1
index 02153382d67b6..35c11005a5150 100644
@@ -532,6 +532,5 @@ source "drivers/misc/vmw_vmci/Kconfig"
 source "drivers/misc/mic/Kconfig"
 source "drivers/misc/genwqe/Kconfig"
 source "drivers/misc/echo/Kconfig"
-source "drivers/misc/ocxl/Kconfig"
 source "drivers/misc/cardreader/Kconfig"
 endmenu
drivers/misc/Makefile +0 -1
index 72fa4fc42a2d6..2ee4eeb573b58 100644
@@ -55,6 +55,5 @@ obj-$(CONFIG_VEXPRESS_SYSCFG)	+= vexpress-syscfg.o
 obj-$(CONFIG_ASPEED_LPC_CTRL)	+= aspeed-lpc-ctrl.o
 obj-$(CONFIG_ASPEED_LPC_SNOOP)	+= aspeed-lpc-snoop.o
 obj-$(CONFIG_PCI_ENDPOINT_TEST)	+= pci_endpoint_test.o
-obj-$(CONFIG_OCXL)		+= ocxl/
 obj-y				+= cardreader/
 obj-$(CONFIG_PVPANIC)   	+= pvpanic.o
Signature · 1 line
2.11.0
#96 lore raw

PATCH 5/5 drivers/accel: ocxl: Move non-uapi include files

In reply to Olof Johansson

Separate to expose the edits vs pure moves.

Cc Greg Kroah-Hartman <[email protected]>
Cc Frederic Barrat <[email protected]>
Cc Andrew Donnellan <[email protected]>
Cc Arnd Bergmann <[email protected]>
---
 MAINTAINERS                                 | 2 +-
 arch/powerpc/platforms/powernv/ocxl.c       | 2 +-
 drivers/accel/ocxl/config.c                 | 4 ++--
 drivers/accel/ocxl/link.c                   | 2 +-
 drivers/accel/ocxl/ocxl_internal.h          | 2 +-
 drivers/scsi/cxlflash/ocxl_hw.c             | 2 +-
 include/{misc => linux/accel}/ocxl-config.h | 6 +++---
 include/{misc => linux/accel}/ocxl.h        | 6 +++---
 8 files changed, 13 insertions(+), 13 deletions(-)
 rename include/{misc => linux/accel}/ocxl-config.h (94%)
 rename include/{misc => linux/accel}/ocxl.h (98%)
MAINTAINERS +1 -1
index a1b2ba3bd402d..faa39da1445d1 100644
@@ -11013,7 +11013,7 @@ S:	Supported
 F:	arch/powerpc/platforms/powernv/ocxl.c
 F:	arch/powerpc/include/asm/pnv-ocxl.h
 F:	drivers/accel/ocxl/
-F:	include/misc/ocxl*
+F:	include/linux/accel/ocxl*
 F:	include/uapi/misc/ocxl.h
 F:	Documentation/accelerators/ocxl.rst
 
arch/powerpc/platforms/powernv/ocxl.c +1 -1
index 8c65aacda9c81..90e3a66c51dde 100644
@@ -3,7 +3,7 @@
 #include <asm/pnv-ocxl.h>
 #include <asm/opal.h>
 #include <asm/xive.h>
-#include <misc/ocxl-config.h>
+#include <linux/accel/ocxl-config.h>
 #include "pci.h"
 
 #define PNV_OCXL_TL_P9_RECV_CAP		0x000000000000000Full
drivers/accel/ocxl/config.c +2 -2
index 8f2c5d8bd2eee..38351c6b28039 100644
@@ -2,8 +2,8 @@
 // Copyright 2017 IBM Corp.
 #include <linux/pci.h>
 #include <asm/pnv-ocxl.h>
-#include <misc/ocxl.h>
-#include <misc/ocxl-config.h>
+#include <linux/accel/ocxl.h>
+#include <linux/accel/ocxl-config.h>
 
 #define EXTRACT_BIT(val, bit) (!!(val & BIT(bit)))
 #define EXTRACT_BITS(val, s, e) ((val & GENMASK(e, s)) >> s)
drivers/accel/ocxl/link.c +1 -1
index d50b861d7e57b..7c0550425a129 100644
@@ -6,7 +6,7 @@
 #include <linux/mmu_context.h>
 #include <asm/copro.h>
 #include <asm/pnv-ocxl.h>
-#include <misc/ocxl.h>
+#include <linux/accel/ocxl.h>
 #include "ocxl_internal.h"
 #include "trace.h"
 
drivers/accel/ocxl/ocxl_internal.h +1 -1
index a32f2151029f6..4516390a8dbcb 100644
@@ -6,7 +6,7 @@
 #include <linux/pci.h>
 #include <linux/cdev.h>
 #include <linux/list.h>
-#include <misc/ocxl.h>
+#include <linux/accel/ocxl.h>
 
 #define MAX_IRQ_PER_LINK	2000
 #define MAX_IRQ_PER_CONTEXT	MAX_IRQ_PER_LINK
drivers/scsi/cxlflash/ocxl_hw.c +1 -1
index 37b8dc60f5f6d..7a62f78033b73 100644
@@ -19,7 +19,7 @@
 #include <linux/poll.h>
 #include <linux/sched/signal.h>
 
-#include <misc/ocxl.h>
+#include <linux/accel/ocxl.h>
 
 #include <uapi/misc/cxl.h>
 
include/linux/accel/ocxl-config.h renamed from include/misc/ocxl-config.h +3 -3
similarity index 94%
rename from include/misc/ocxl-config.h
rename to include/linux/accel/ocxl-config.h
index 3526fa996a220..4d25ed7b971f8 100644
@@ -1,7 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0+
 // Copyright 2017 IBM Corp.
-#ifndef _OCXL_CONFIG_H_
-#define _OCXL_CONFIG_H_
+#ifndef _LINUX_ACCEL_OCXL_CONFIG_H_
+#define _LINUX_ACCEL_OCXL_CONFIG_H_
 
 /*
  * This file lists the various constants used to read the
@@ -42,4 +42,4 @@
 #define   OCXL_DVSEC_VENDOR_TLX_VERS            0x10
 #define   OCXL_DVSEC_VENDOR_DLX_VERS            0x20
 
-#endif /* _OCXL_CONFIG_H_ */
+#endif /* _LINUX_ACCEL_OCXL_CONFIG_H_ */
include/linux/accel/ocxl.h renamed from include/misc/ocxl.h +3 -3
similarity index 98%
rename from include/misc/ocxl.h
rename to include/linux/accel/ocxl.h
index 9ff6ddc28e221..1ab4c50700029 100644
@@ -1,7 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0+
 // Copyright 2017 IBM Corp.
-#ifndef _MISC_OCXL_H_
-#define _MISC_OCXL_H_
+#ifndef _LINUX_ACCEL_OCXL_H_
+#define _LINUX_ACCEL_OCXL_H_
 
 #include <linux/pci.h>
 
@@ -220,4 +220,4 @@ extern int ocxl_link_irq_alloc(void *link_handle, int *hw_irq,
  */
 extern void ocxl_link_free_irq(void *link_handle, int hw_irq);
 
-#endif /* _MISC_OCXL_H_ */
+#endif /* _LINUX_ACCEL_OCXL_H_ */
Signature · 1 line
2.11.0
#93 lore raw

PATCH 2/5 cxl: Move to drivers/accel

In reply to Olof Johansson

Move include files in separate commit, so leave them alone for now.

Cc Greg Kroah-Hartman <[email protected]>
Cc Frederic Barrat <[email protected]>
Cc Andrew Donnellan <[email protected]>
Cc Arnd Bergmann <[email protected]>
---
 MAINTAINERS                           | 2 +-
 drivers/accel/Kconfig                 | 2 ++
 drivers/accel/Makefile                | 1 +
 drivers/{misc => accel}/cxl/Kconfig   | 0
 drivers/{misc => accel}/cxl/Makefile  | 0
 drivers/{misc => accel}/cxl/api.c     | 0
 drivers/{misc => accel}/cxl/base.c    | 0
 drivers/{misc => accel}/cxl/context.c | 0
 drivers/{misc => accel}/cxl/cxl.h     | 0
 drivers/{misc => accel}/cxl/cxllib.c  | 0
 drivers/{misc => accel}/cxl/debugfs.c | 0
 drivers/{misc => accel}/cxl/fault.c   | 0
 drivers/{misc => accel}/cxl/file.c    | 0
 drivers/{misc => accel}/cxl/flash.c   | 0
 drivers/{misc => accel}/cxl/guest.c   | 0
 drivers/{misc => accel}/cxl/hcalls.c  | 0
 drivers/{misc => accel}/cxl/hcalls.h  | 0
 drivers/{misc => accel}/cxl/irq.c     | 0
 drivers/{misc => accel}/cxl/main.c    | 0
 drivers/{misc => accel}/cxl/native.c  | 0
 drivers/{misc => accel}/cxl/of.c      | 0
 drivers/{misc => accel}/cxl/pci.c     | 0
 drivers/{misc => accel}/cxl/sysfs.c   | 0
 drivers/{misc => accel}/cxl/trace.c   | 0
 drivers/{misc => accel}/cxl/trace.h   | 0
 drivers/{misc => accel}/cxl/vphb.c    | 0
 drivers/misc/Kconfig                  | 1 -
 drivers/misc/Makefile                 | 1 -
 28 files changed, 4 insertions(+), 3 deletions(-)
 rename drivers/{misc => accel}/cxl/Kconfig (100%)
 rename drivers/{misc => accel}/cxl/Makefile (100%)
 rename drivers/{misc => accel}/cxl/api.c (100%)
 rename drivers/{misc => accel}/cxl/base.c (100%)
 rename drivers/{misc => accel}/cxl/context.c (100%)
 rename drivers/{misc => accel}/cxl/cxl.h (100%)
 rename drivers/{misc => accel}/cxl/cxllib.c (100%)
 rename drivers/{misc => accel}/cxl/debugfs.c (100%)
 rename drivers/{misc => accel}/cxl/fault.c (100%)
 rename drivers/{misc => accel}/cxl/file.c (100%)
 rename drivers/{misc => accel}/cxl/flash.c (100%)
 rename drivers/{misc => accel}/cxl/guest.c (100%)
 rename drivers/{misc => accel}/cxl/hcalls.c (100%)
 rename drivers/{misc => accel}/cxl/hcalls.h (100%)
 rename drivers/{misc => accel}/cxl/irq.c (100%)
 rename drivers/{misc => accel}/cxl/main.c (100%)
 rename drivers/{misc => accel}/cxl/native.c (100%)
 rename drivers/{misc => accel}/cxl/of.c (100%)
 rename drivers/{misc => accel}/cxl/pci.c (100%)
 rename drivers/{misc => accel}/cxl/sysfs.c (100%)
 rename drivers/{misc => accel}/cxl/trace.c (100%)
 rename drivers/{misc => accel}/cxl/trace.h (100%)
 rename drivers/{misc => accel}/cxl/vphb.c (100%)
MAINTAINERS +1 -1
index 8a9bbaf8f6e90..93fbfed6e6915 100644
@@ -4214,7 +4214,7 @@ M:	Andrew Donnellan <[email protected]>
 L:	[email protected]
 S:	Supported
 F:	arch/powerpc/platforms/powernv/pci-cxl.c
-F:	drivers/misc/cxl/
+F:	drivers/accel/cxl/
 F:	include/misc/cxl*
 F:	include/uapi/misc/cxl.h
 F:	Documentation/powerpc/cxl.txt
drivers/accel/Kconfig +2 -0
index 13b36c0398895..c0754448efdf0 100644
@@ -13,4 +13,6 @@ if ACCEL
 
 comment "HW Accellerator drivers"
 
+source "drivers/accel/cxl/Kconfig"
+
 endif
drivers/accel/Makefile +1 -0
index 343bbb8f45a14..752a54e227ad7 100644
@@ -3,3 +3,4 @@
 # Makefile for accel devices
 #
 
+obj-$(CONFIG_CXL_BASE)		+= cxl/
drivers/accel/cxl/Kconfig renamed from drivers/misc/cxl/Kconfig +0 -0
similarity index 100%
rename from drivers/misc/cxl/Kconfig
rename to drivers/accel/cxl/Kconfig
drivers/accel/cxl/Makefile renamed from drivers/misc/cxl/Makefile +0 -0
similarity index 100%
rename from drivers/misc/cxl/Makefile
rename to drivers/accel/cxl/Makefile
drivers/accel/cxl/api.c renamed from drivers/misc/cxl/api.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/api.c
rename to drivers/accel/cxl/api.c
drivers/accel/cxl/base.c renamed from drivers/misc/cxl/base.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/base.c
rename to drivers/accel/cxl/base.c
drivers/accel/cxl/context.c renamed from drivers/misc/cxl/context.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/context.c
rename to drivers/accel/cxl/context.c
drivers/accel/cxl/cxl.h renamed from drivers/misc/cxl/cxl.h +0 -0
similarity index 100%
rename from drivers/misc/cxl/cxl.h
rename to drivers/accel/cxl/cxl.h
drivers/accel/cxl/cxllib.c renamed from drivers/misc/cxl/cxllib.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/cxllib.c
rename to drivers/accel/cxl/cxllib.c
drivers/accel/cxl/debugfs.c renamed from drivers/misc/cxl/debugfs.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/debugfs.c
rename to drivers/accel/cxl/debugfs.c
drivers/accel/cxl/fault.c renamed from drivers/misc/cxl/fault.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/fault.c
rename to drivers/accel/cxl/fault.c
drivers/accel/cxl/file.c renamed from drivers/misc/cxl/file.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/file.c
rename to drivers/accel/cxl/file.c
drivers/accel/cxl/flash.c renamed from drivers/misc/cxl/flash.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/flash.c
rename to drivers/accel/cxl/flash.c
drivers/accel/cxl/guest.c renamed from drivers/misc/cxl/guest.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/guest.c
rename to drivers/accel/cxl/guest.c
drivers/accel/cxl/hcalls.c renamed from drivers/misc/cxl/hcalls.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/hcalls.c
rename to drivers/accel/cxl/hcalls.c
drivers/accel/cxl/hcalls.h renamed from drivers/misc/cxl/hcalls.h +0 -0
similarity index 100%
rename from drivers/misc/cxl/hcalls.h
rename to drivers/accel/cxl/hcalls.h
drivers/accel/cxl/irq.c renamed from drivers/misc/cxl/irq.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/irq.c
rename to drivers/accel/cxl/irq.c
drivers/accel/cxl/main.c renamed from drivers/misc/cxl/main.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/main.c
rename to drivers/accel/cxl/main.c
drivers/accel/cxl/native.c renamed from drivers/misc/cxl/native.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/native.c
rename to drivers/accel/cxl/native.c
drivers/accel/cxl/of.c renamed from drivers/misc/cxl/of.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/of.c
rename to drivers/accel/cxl/of.c
drivers/accel/cxl/pci.c renamed from drivers/misc/cxl/pci.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/pci.c
rename to drivers/accel/cxl/pci.c
drivers/accel/cxl/sysfs.c renamed from drivers/misc/cxl/sysfs.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/sysfs.c
rename to drivers/accel/cxl/sysfs.c
drivers/accel/cxl/trace.c renamed from drivers/misc/cxl/trace.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/trace.c
rename to drivers/accel/cxl/trace.c
drivers/accel/cxl/trace.h renamed from drivers/misc/cxl/trace.h +0 -0
similarity index 100%
rename from drivers/misc/cxl/trace.h
rename to drivers/accel/cxl/trace.h
drivers/accel/cxl/vphb.c renamed from drivers/misc/cxl/vphb.c +0 -0
similarity index 100%
rename from drivers/misc/cxl/vphb.c
rename to drivers/accel/cxl/vphb.c
drivers/misc/Kconfig +0 -1
index f417b06e11c51..02153382d67b6 100644
@@ -532,7 +532,6 @@ source "drivers/misc/vmw_vmci/Kconfig"
 source "drivers/misc/mic/Kconfig"
 source "drivers/misc/genwqe/Kconfig"
 source "drivers/misc/echo/Kconfig"
-source "drivers/misc/cxl/Kconfig"
 source "drivers/misc/ocxl/Kconfig"
 source "drivers/misc/cardreader/Kconfig"
 endmenu
drivers/misc/Makefile +0 -1
index e39ccbbc1b3a8..72fa4fc42a2d6 100644
@@ -52,7 +52,6 @@ obj-y				+= mic/
 obj-$(CONFIG_GENWQE)		+= genwqe/
 obj-$(CONFIG_ECHO)		+= echo/
 obj-$(CONFIG_VEXPRESS_SYSCFG)	+= vexpress-syscfg.o
-obj-$(CONFIG_CXL_BASE)		+= cxl/
 obj-$(CONFIG_ASPEED_LPC_CTRL)	+= aspeed-lpc-ctrl.o
 obj-$(CONFIG_ASPEED_LPC_SNOOP)	+= aspeed-lpc-snoop.o
 obj-$(CONFIG_PCI_ENDPOINT_TEST)	+= pci_endpoint_test.o
Signature · 1 line
2.11.0
#3 lore raw

Re: [PATCH 01/15] habanalabs: add skeleton driver

In reply to Joe Perches
Quoted 130 lines · Joe Perches
Quoted 3 lines · Oded Gabbay

This patch adds the habanalabs skeleton driver. The driver does nothing at this stage except very basic operations. It contains the minimal code to insmod and rmmod the driver and to create a /dev/hlX file per PCI device.

trivial notes:

drivers/misc/habanalabs/Makefile

Quoted 2 lines
drivers/misc/habanalabs/Makefile +0 -0

[]

Quoted 1 line

\ No newline at end of file

You should fixes these. There are a least a couple of them.

drivers/misc/habanalabs/device.c

Quoted 1 line
drivers/misc/habanalabs/device.c +0 -0

[]

drivers/misc/habanalabs/device.c line 6

Quoted 7 lines
drivers/misc/habanalabs/device.c +6 -0
@@ -0,0 +1,331 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ */

Add #define pr_fmt(fmt) "habanalabs: " fmt

drivers/misc/habanalabs/device.c line 8

Quoted 2 lines
drivers/misc/habanalabs/device.c +2 -0
+
+#include "habanalabs.h"

or add it in this file

drivers/misc/habanalabs/device.c line 82

Quoted 8 lines
drivers/misc/habanalabs/device.c +8 -0
+static int device_setup_cdev(struct hl_device *hdev, struct class *hclass,
+                             int minor, const struct file_operations *fops)
+{
+     int err, devno = MKDEV(hdev->major, minor);
+     struct cdev *hdev_cdev = &hdev->cdev;
+     char name[8];
+
+     sprintf(name, "hl%d", hdev->id);

Might overflow name one day

drivers/misc/habanalabs/device.c line 88

Quoted 6 lines
drivers/misc/habanalabs/device.c +6 -0
+
+     cdev_init(hdev_cdev, fops);
+     hdev_cdev->owner = THIS_MODULE;
+     err = cdev_add(hdev_cdev, devno, 1);
+     if (err) {
+             pr_err("habanalabs: Failed to add char device %s", name);

So #define pr_fmt can auto prefix these and this would be

                pr_err("Failed to add char device %s\n", name);

missing terminating '\n' btw

drivers/misc/habanalabs/device.c line 94

Quoted 6 lines
drivers/misc/habanalabs/device.c +6 -0
+             goto err_cdev_add;
+     }
+
+     hdev->dev = device_create(hclass, NULL, devno, NULL, "%s", name);
+     if (IS_ERR(hdev->dev)) {
+             pr_err("habanalabs: Failed to create device %s\n", name);

And this would be:

                pr_err("Failed to create device %s\n", name);

etc...

drivers/misc/habanalabs/device.c line 121

Quoted 5 lines
drivers/misc/habanalabs/device.c +5 -0
+static int device_early_init(struct hl_device *hdev)
+{
+     switch (hdev->asic_type) {
+     case ASIC_GOYA:
+             sprintf(hdev->asic_name, "GOYA");

strcpy or perhaps better still as strlcpy

drivers/misc/habanalabs/device.c line 35

Quoted 2 lines
drivers/misc/habanalabs/device.c +2 -0
+int hl_device_init(struct hl_device *hdev, struct class *hclass)
+{

[]

drivers/misc/habanalabs/device.c line 212

Quoted 2 lines
drivers/misc/habanalabs/device.c +2 -0
+     dev_notice(hdev->dev,
+             "Successfully added device to habanalabs driver\n");

This is mostly aligned to open parenthesis, but perhaps it could check with scripts/checkpatch.pl --strict and see if you agree with anything it bleats.

drivers/misc/habanalabs/device.c line 278

Quoted 9 lines
drivers/misc/habanalabs/device.c +9 -0
+int hl_poll_timeout_memory(struct hl_device *hdev, u64 addr,
+                             u32 timeout_us, u32 *val)
+{
+     /*
+      * pReturnVal is defined as volatile because it points to HOST memory,
+      * which is being written to by the device. Therefore, we can't use
+      * locks to synchronize it and it is not a memory-mapped register space
+      */
+     volatile u32 *pReturnVal = (volatile u32 *) addr;

It'd be nice to avoid hungarian and camelcase

Quoted 6 lines
drivers/misc/habanalabs/device.c +6 -0
+     ktime_t timeout = ktime_add_us(ktime_get(), timeout_us);
+
+     might_sleep();
+
+     for (;;) {
+             *val = *pReturnVal;

drivers/misc/habanalabs/device.c line 294

Quoted 10 lines
drivers/misc/habanalabs/device.c +10 -0
+             if (*val)
+                     break;
+             if (ktime_compare(ktime_get(), timeout) > 0) {
+                     *val = *pReturnVal;
+                     break;
+             }
+             usleep_range((100 >> 2) + 1, 100);
+     }
+
+     return (*val ? 0 : -ETIMEDOUT);

Unnecessary parentheses

drivers/misc/habanalabs/habanalabs_drv.c

Quoted 1 line
drivers/misc/habanalabs/habanalabs_drv.c +0 -0

[]

drivers/misc/habanalabs/habanalabs_drv.c line 40

Quoted 4 lines
drivers/misc/habanalabs/habanalabs_drv.c +4 -0
+static struct pci_device_id ids[] = {
+     { PCI_DEVICE(PCI_VENDOR_ID_HABANALABS, PCI_IDS_GOYA), },
+     { 0, }
+};

static const?

drivers/misc/habanalabs/include/habanalabs_device_if.h

Quoted 1 line
drivers/misc/habanalabs/include/habanalabs_device_if.h +0 -0

[]

Quoted 18 lines

drivers/misc/habanalabs/include/habanalabs_device_if.h line 29

Quoted 13 lines
drivers/misc/habanalabs/include/habanalabs_device_if.h +13 -0
+struct hl_bd {
+     __u64   ptr;
+     __u32   len;
+     union {
+             struct {
+                     __u32   repeat:16;
+                     __u32   res1:8;
+                     __u32   repeat_valid:1;
+                     __u32   res2:7;
+             };
+             __u32   ctl;
+     };
+};

Maybe use the appropriate bit-endian __le<size> instead of __u<size> with whatever cpu_to_le<size> / le<size>_to_cpu bits are necessary.

Hi Joe,
Thanks for the review.
I fixed everything except for two things:
1. Alignment to open parenthesis. I never code like that in the kernel and I don't really believe in anything that requires to combine spaces and tabs.
2. The bit-endian format. We don't support big-endian architecture (what's left after POWER moved to support little endian ?). And in any case, our software stack is so big that this minor change in the driver won't have any impact.

Thanks,
Oded

#8 lore raw

Re: [PATCH 01/15] habanalabs: add skeleton driver

In reply to Mike Rapoport
Quoted 772 lines · Mike Rapoport
Quoted 124 lines · Oded Gabbay

This patch adds the habanalabs skeleton driver. The driver does nothing at this stage except very basic operations. It contains the minimal code to insmod and rmmod the driver and to create a /dev/hlX file per PCI device.

---
 drivers/misc/Kconfig                          |   1 +
 drivers/misc/Makefile                         |   1 +
 drivers/misc/habanalabs/Kconfig               |  22 ++
 drivers/misc/habanalabs/Makefile              |   7 +
 drivers/misc/habanalabs/device.c              | 331 ++++++++++++++++
 drivers/misc/habanalabs/habanalabs.h          | 149 +++++++
 drivers/misc/habanalabs/habanalabs_drv.c      | 366 ++++++++++++++++++
 .../habanalabs/include/habanalabs_device_if.h | 125 ++++++
 8 files changed, 1002 insertions(+)
 create mode 100644 drivers/misc/habanalabs/Kconfig
 create mode 100644 drivers/misc/habanalabs/Makefile
 create mode 100644 drivers/misc/habanalabs/device.c
 create mode 100644 drivers/misc/habanalabs/habanalabs.h
 create mode 100644 drivers/misc/habanalabs/habanalabs_drv.c
 create mode 100644 drivers/misc/habanalabs/include/habanalabs_device_if.h
drivers/misc/Kconfig +1 -0
index f417b06e11c5..fecab53c4f21 100644
@@ -535,4 +535,5 @@ source "drivers/misc/echo/Kconfig"
 source "drivers/misc/cxl/Kconfig"
 source "drivers/misc/ocxl/Kconfig"
 source "drivers/misc/cardreader/Kconfig"
+source "drivers/misc/habanalabs/Kconfig"
 endmenu
drivers/misc/Makefile +1 -0
index e39ccbbc1b3a..ae77dfd790a4 100644
@@ -59,3 +59,4 @@ obj-$(CONFIG_PCI_ENDPOINT_TEST)     += pci_endpoint_test.o
 obj-$(CONFIG_OCXL)           += ocxl/
 obj-y                                += cardreader/
 obj-$(CONFIG_PVPANIC)        += pvpanic.o
+obj-$(CONFIG_HABANA_AI)              += habanalabs/
drivers/misc/habanalabs/Kconfig new file +22 -0
new file mode 100644
index 000000000000..b7f38a14caf5
@@ -0,0 +1,22 @@
+#
+# HabanaLabs AI accelerators driver
+#
+
+config HABANA_AI
+     tristate "HabanaAI accelerators (habanalabs)"
+     depends on PCI
+     select FRAME_VECTOR
+     help
+       Enables PCIe card driver for Habana's AI Processors (AIP) that are
+       designed to accelerate Deep Learning inference and training workloads.
+
+       The driver manages the PCIe devices and provides IOCTL interface for
+       the user to submit workloads to the devices.
+
+       The user-space interface is described in
+       include/uapi/misc/habanalabs.h
+
+       If unsure, say N.
+
+       To compile this driver as a module, choose M here: the
+       module will be called habanalabs.
drivers/misc/habanalabs/Makefile new file +7 -0
new file mode 100644
index 000000000000..b41433a09e02
@@ -0,0 +1,7 @@
+#
+# Makefile for HabanaLabs AI accelerators driver
+#
+
+obj-m        := habanalabs.o
+
+habanalabs-y := habanalabs_drv.o device.o
\ No newline at end of file
drivers/misc/habanalabs/device.c new file +35 -0
new file mode 100644
index 000000000000..376b55eb73d4
@@ -0,0 +1,331 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ */
+
+#include "habanalabs.h"
+
+#include <linux/fs.h>
+#include <linux/kthread.h>
+#include <linux/sched/signal.h>
+
+static void hpriv_release(struct kref *ref)
+{
+     struct hl_fpriv *hpriv;
+     struct hl_device *hdev;
+
+     hpriv = container_of(ref, struct hl_fpriv, refcount);
+
+     hdev = hpriv->hdev;
+
+     put_pid(hpriv->taskpid);
+
+     kfree(hpriv);
+}
+
+void hl_hpriv_get(struct hl_fpriv *hpriv)
+{
+     kref_get(&hpriv->refcount);
+}
+
+void hl_hpriv_put(struct hl_fpriv *hpriv)
+{
+     kref_put(&hpriv->refcount, hpriv_release);

drivers/misc/habanalabs/device.c line 45

Quoted 10 lines
drivers/misc/habanalabs/device.c new file +10 -0
+}
+
+/**
+ * hl_device_release - release function for habanalabs device
+ *
+ * @inode: pointer to inode structure
+ * @filp: pointer to file structure
+ *
+ * Called when process closes an habanalabs device
+ */

It's nice to see docs coming along with the codei
I have some comments for the formatting.

kernel-doc won't be happy about missing return value descriptions, and although they are sometimes redundant or too obvious their absence makes 'make V=1 htmldocs' really noisy.

In general, it would be nice if you could link hanabnalabs driver kernel-doc somewhere in Documentation/ run 'make V=1 htmldocs'.

Quoted 78 lines
drivers/misc/habanalabs/device.c new file +78 -0
+static int hl_device_release(struct inode *inode, struct file *filp)
+{
+     struct hl_fpriv *hpriv = filp->private_data;
+
+     filp->private_data = NULL;
+
+     hl_hpriv_put(hpriv);
+
+     return 0;
+}
+
+static const struct file_operations hl_ops = {
+     .owner = THIS_MODULE,
+     .open = hl_device_open,
+     .release = hl_device_release
+};
+
+/**
+ * device_setup_cdev - setup cdev and device for habanalabs device
+ *
+ * @hdev: pointer to habanalabs device structure
+ * @hclass: pointer to the class object of the device
+ * @minor: minor number of the specific device
+ * @fpos : file operations to install for this device
+ *
+ * Create a cdev and a Linux device for habanalabs's device. Need to be
+ * called at the end of the habanalabs device initialization process,
+ * because this function exposes the device to the user
+ */
+static int device_setup_cdev(struct hl_device *hdev, struct class *hclass,
+                             int minor, const struct file_operations *fops)
+{
+     int err, devno = MKDEV(hdev->major, minor);
+     struct cdev *hdev_cdev = &hdev->cdev;
+     char name[8];
+
+     sprintf(name, "hl%d", hdev->id);
+
+     cdev_init(hdev_cdev, fops);
+     hdev_cdev->owner = THIS_MODULE;
+     err = cdev_add(hdev_cdev, devno, 1);
+     if (err) {
+             pr_err("habanalabs: Failed to add char device %s", name);
+             goto err_cdev_add;
+     }
+
+     hdev->dev = device_create(hclass, NULL, devno, NULL, "%s", name);
+     if (IS_ERR(hdev->dev)) {
+             pr_err("habanalabs: Failed to create device %s\n", name);
+             err = PTR_ERR(hdev->dev);
+             goto err_device_create;
+     }
+
+     dev_set_drvdata(hdev->dev, hdev);
+
+     return 0;
+
+err_device_create:
+     cdev_del(hdev_cdev);
+err_cdev_add:
+     return err;
+}
+
+/**
+ * device_early_init - do some early initialization for the habanalabs device
+ *
+ * @hdev: pointer to habanalabs device structure
+ *
+ * Install the relevant function pointers and call the early_init function,
+ * if such a function exists
+ */
+static int device_early_init(struct hl_device *hdev)
+{
+     switch (hdev->asic_type) {
+     case ASIC_GOYA:
+             sprintf(hdev->asic_name, "GOYA");
+             break;
+     default:

drivers/misc/habanalabs/device.c line 133

Quoted 10 lines
drivers/misc/habanalabs/device.c new file +10 -0
+             dev_err(hdev->dev, "Unrecognized ASIC type %d\n",
+                     hdev->asic_type);
+             return -EINVAL;
+     }
+
+     return 0;
+}
+
+/**
+ * device_early_fini - finalize all that was done in device_early_fini

^init

Quoted 5 lines
drivers/misc/habanalabs/device.c new file +5 -0
+ *
+ * @hdev: pointer to habanalabs device structure
+ *
+ */
+static void device_early_fini(struct hl_device *hdev)

drivers/misc/habanalabs/device.c line 148

Quoted 10 lines
drivers/misc/habanalabs/device.c new file +10 -0
+{
+}
+
+/**
+ * hl_device_suspend - initiate device suspend
+ *
+ * @hdev: pointer to habanalabs device structure
+ *
+ * Puts the hw in the suspend state (all asics).
+ * Returns 0 for success or an error on failure.

Should be Return: or Returns: for kernel-doc to understand it.

drivers/misc/habanalabs/device.c line 149

Quoted 1 line
drivers/misc/habanalabs/device.c new file +1 -0
+ * Called at driver suspend.

This probably should be marked as Context:

Quoted 10 lines
drivers/misc/habanalabs/device.c new file +10 -0
+ */
+int hl_device_suspend(struct hl_device *hdev)
+{
+     pci_save_state(hdev->pdev);
+
+     /* Shut down the device */
+     pci_disable_device(hdev->pdev);
+     pci_set_power_state(hdev->pdev, PCI_D3hot);
+
+     return 0;

drivers/misc/habanalabs/device.c line 169

Quoted 10 lines
drivers/misc/habanalabs/device.c new file +10 -0
+}
+
+/**
+ * hl_device_resume - initiate device resume
+ *
+ * @hdev: pointer to habanalabs device structure
+ *
+ * Bring the hw back to operating state (all asics).
+ * Returns 0 for success or an error on failure.
+ * Called at driver resume.

Same comments as for the previous functions.

Quoted 48 lines
drivers/misc/habanalabs/device.c new file +48 -0
+ */
+int hl_device_resume(struct hl_device *hdev)
+{
+     int rc;
+
+     pci_set_power_state(hdev->pdev, PCI_D0);
+     pci_restore_state(hdev->pdev);
+     rc = pci_enable_device(hdev->pdev);
+     if (rc) {
+             dev_err(hdev->dev,
+                     "Failed to enable PCI device in resume\n");
+             return rc;
+     }
+
+     return 0;
+}
+
+/**
+ * hl_device_init - main initialization function for habanalabs device
+ *
+ * @hdev: pointer to habanalabs device structure
+ *
+ * Allocate an id for the device, do early initialization and then call the
+ * ASIC specific initialization functions. Finally, create the cdev and the
+ * Linux device to expose it to the user
+ */
+int hl_device_init(struct hl_device *hdev, struct class *hclass)
+{
+     int rc;
+
+     /* Create device */
+     rc = device_setup_cdev(hdev, hclass, hdev->id, &hl_ops);
+
+     if (rc)
+             goto out_disabled;
+
+     /* Initialize ASIC function pointers and perform early init */
+     rc = device_early_init(hdev);
+     if (rc)
+             goto release_device;
+
+     dev_notice(hdev->dev,
+             "Successfully added device to habanalabs driver\n");
+
+     return 0;
+
+release_device:
+     device_destroy(hclass, hdev->dev->devt);

drivers/misc/habanalabs/device.c line 227

Quoted 10 lines
drivers/misc/habanalabs/device.c new file +10 -0
+     cdev_del(&hdev->cdev);
+out_disabled:
+     hdev->disabled = true;
+     if (hdev->pdev)
+             dev_err(&hdev->pdev->dev,
+                     "Failed to initialize hl%d. Device is NOT usable !!!\n",
+                     hdev->id);
+     else
+             pr_err("habanalabs: Failed to initialize hl%d. Device is NOT usable !!!\n",
+                     hdev->id);

Maybe three exclamation marks would be too much?

Quoted 130 lines
drivers/misc/habanalabs/device.c new file +104 -0
+
+     return rc;
+}
+
+/**
+ * hl_device_fini - main tear-down function for habanalabs device
+ *
+ * @hdev: pointer to habanalabs device structure
+ *
+ * Destroy the device, call ASIC fini functions and release the id
+ */
+void hl_device_fini(struct hl_device *hdev)
+{
+     dev_info(hdev->dev, "Removing device\n");
+
+     /* Mark device as disabled */
+     hdev->disabled = true;
+
+     device_early_fini(hdev);
+
+     /* Hide device from user */
+     device_destroy(hdev->dev->class, hdev->dev->devt);
+     cdev_del(&hdev->cdev);
+
+     pr_info("habanalabs: removed device successfully\n");
+}
+
+/**
+ * hl_poll_timeout_memory - Periodically poll a host memory address
+ *                              until it is not zero or a timeout occurs
+ * @hdev: pointer to habanalabs device structure
+ * @addr: Address to poll
+ * @timeout_us: timeout in us
+ * @val: Variable to read the value into
+ *
+ * Returns 0 on success and -ETIMEDOUT upon a timeout. In either
+ * case, the last read value at @addr is stored in @val. Must not
+ * be called from atomic context if sleep_us or timeout_us are used.
+ *
+ * The function sleeps for 100us with timeout value of
+ * timeout_us
+ */
+int hl_poll_timeout_memory(struct hl_device *hdev, u64 addr,
+                             u32 timeout_us, u32 *val)
+{
+     /*
+      * pReturnVal is defined as volatile because it points to HOST memory,
+      * which is being written to by the device. Therefore, we can't use
+      * locks to synchronize it and it is not a memory-mapped register space
+      */
+     volatile u32 *pReturnVal = (volatile u32 *) addr;
+     ktime_t timeout = ktime_add_us(ktime_get(), timeout_us);
+
+     might_sleep();
+
+     for (;;) {
+             *val = *pReturnVal;
+             if (*val)
+                     break;
+             if (ktime_compare(ktime_get(), timeout) > 0) {
+                     *val = *pReturnVal;
+                     break;
+             }
+             usleep_range((100 >> 2) + 1, 100);
+     }
+
+     return (*val ? 0 : -ETIMEDOUT);
+}
+
+/**
+ * hl_poll_timeout_devicememory - Periodically poll a device memory address
+ *                                until it is not zero or a timeout occurs
+ * @hdev: pointer to habanalabs device structure
+ * @addr: Device address to poll
+ * @timeout_us: timeout in us
+ * @val: Variable to read the value into
+ *
+ * Returns 0 on success and -ETIMEDOUT upon a timeout. In either
+ * case, the last read value at @addr is stored in @val. Must not
+ * be called from atomic context if sleep_us or timeout_us are used.
+ *
+ * The function sleeps for 100us with timeout value of
+ * timeout_us
+ */
+int hl_poll_timeout_device_memory(struct hl_device *hdev, void __iomem *addr,
+                             u32 timeout_us, u32 *val)
+{
+     ktime_t timeout = ktime_add_us(ktime_get(), timeout_us);
+
+     might_sleep();
+
+     for (;;) {
+             *val = readl(addr);
+             if (*val)
+                     break;
+             if (ktime_compare(ktime_get(), timeout) > 0) {
+                     *val = readl(addr);
+                     break;
+             }
+             usleep_range((100 >> 2) + 1, 100);
+     }
+
+     return (*val ? 0 : -ETIMEDOUT);
+}
drivers/misc/habanalabs/habanalabs.h new file +20 -0
new file mode 100644
index 000000000000..7e1b088b677c
@@ -0,0 +1,149 @@
+/* SPDX-License-Identifier: GPL-2.0
+ *
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ *
+ */
+
+#ifndef HABANALABSP_H_
+#define HABANALABSP_H_
+
+#include "include/habanalabs_device_if.h"
+
+#include <linux/pci.h>
+#include <linux/types.h>
+#include <linux/cdev.h>
+#include <linux/interrupt.h>
+#include <linux/iopoll.h>
+#include <linux/dma-fence.h>
+#include <linux/hashtable.h>
+#include <linux/hwmon.h>

drivers/misc/habanalabs/habanalabs.h line 30

Quoted 10 lines
drivers/misc/habanalabs/habanalabs.h new file +10 -0
+
+#define HL_NAME                              "habanalabs"
+
+struct hl_device;
+
+
+
+
+
+

Too many blank lines, IMHO.

Quoted 167 lines
drivers/misc/habanalabs/habanalabs.h new file +119 -0
+/*
+ * ASICs
+ */
+
+/**
+ * enum hl_asic_type - supported ASIC types.
+ * @ASIC_AUTO_DETECT: ASIC type will be automatically set.
+ * @ASIC_GOYA: Goya device.
+ * @ASIC_LAST: last ASIC type.
+ */
+enum hl_asic_type {
+     ASIC_AUTO_DETECT,
+     ASIC_GOYA,
+     ASIC_LAST
+};
+
+
+
+
+
+/*
+ * FILE PRIVATE STRUCTURE
+ */
+
+/**
+ * struct hl_fpriv - process information stored in FD private data.
+ * @hdev: habanalabs device structure.
+ * @filp: pointer to the given file structure.
+ * @taskpid: current process ID.
+ * @refcount: number of related contexts.
+ */
+struct hl_fpriv {
+     struct hl_device        *hdev;
+     struct file             *filp;
+     struct pid              *taskpid;
+     struct kref             refcount;
+};
+
+
+
+
+/*
+ * DEVICES
+ */
+
+/* Theoretical limit only. A single host can only contain up to 4 or 8 PCIe
+ * x16 cards. In extereme cases, there are hosts that can accommodate 16 cards
+ */
+#define HL_MAX_MINORS        256
+
+/**
+ * struct hl_device - habanalabs device structure.
+ * @pdev: pointer to PCI device, can be NULL in case of simulator device.
+ * @cdev: related char device.
+ * @dev: realted kernel basic device structure.
+ * @asic_name: ASIC specific nmae.
+ * @asic_type: ASIC specific type.
+ * @major: habanalabs KMD major.
+ * @id: device minor.
+ * @disabled: is device disabled.
+ */
+struct hl_device {
+     struct pci_dev                  *pdev;
+     struct cdev                     cdev;
+     struct device                   *dev;
+     char                            asic_name[16];
+     enum hl_asic_type               asic_type;
+     u32                             major;
+     u16                             id;
+     u8                              disabled;
+};
+
+/*
+ * IOCTLs
+ */
+
+/**
+ * typedef hl_ioctl_t - typedef for ioctl function in the driver
+ * @hpriv: pointer to the FD's private data, which contains state of
+ *           user process
+ * @data: pointer to the input/output arguments structure of the IOCTL
+ *
+ * Return: 0 for success, negative value for error
+ */
+typedef int hl_ioctl_t(struct hl_fpriv *hpriv, void *data);
+
+/**
+ * struct hl_ioctl_desc - describes an IOCTL entry of the driver.
+ * @cmd: the IOCTL code as created by the kernel macros.
+ * @func: pointer to the driver's function that should be called for this IOCTL.
+ */
+struct hl_ioctl_desc {
+     unsigned int cmd;
+     hl_ioctl_t *func;
+};
+
+
+
+
+
+/*
+ * Kernel module functions that can be accessed by entire module
+ */
+
+int hl_device_open(struct inode *inode, struct file *filp);
+int create_hdev(struct hl_device **dev, struct pci_dev *pdev,
+             enum hl_asic_type asic_type, int minor);
+void destroy_hdev(struct hl_device *hdev);
+int hl_poll_timeout_memory(struct hl_device *hdev, u64 addr, u32 timeout_us,
+                             u32 *val);
+int hl_poll_timeout_device_memory(struct hl_device *hdev, void __iomem *addr,
+                             u32 timeout_us, u32 *val);
+
+int hl_device_init(struct hl_device *hdev, struct class *hclass);
+void hl_device_fini(struct hl_device *hdev);
+int hl_device_suspend(struct hl_device *hdev);
+int hl_device_resume(struct hl_device *hdev);
+
+#endif /* HABANALABSP_H_ */
drivers/misc/habanalabs/habanalabs_drv.c new file +42 -0
new file mode 100644
index 000000000000..15217975327b
@@ -0,0 +1,366 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ *
+ * Author: Oded Gabbay <[email protected]>
+ *
+ */
+
+#include "habanalabs.h"
+
+#include <linux/device.h>
+#include <linux/module.h>
+#include <linux/init.h>
+#include <linux/kthread.h>
+
+#include <linux/fs.h>
+
+#define HL_DRIVER_AUTHOR     "HabanaLabs Kernel Driver Team"
+
+#define HL_DRIVER_DESC               "Driver for HabanaLabs's AI Accelerators"
+
+MODULE_AUTHOR(HL_DRIVER_AUTHOR);
+MODULE_DESCRIPTION(HL_DRIVER_DESC);
+MODULE_LICENSE("GPL v2");
+
+static int hl_major;
+static struct class *hl_class;
+DEFINE_IDR(hl_devs_idr);
+DEFINE_MUTEX(hl_devs_idr_lock);
+
+#define PCI_VENDOR_ID_HABANALABS     0x1da3
+
+#define PCI_IDS_GOYA                 0x0001
+
+static struct pci_device_id ids[] = {
+     { PCI_DEVICE(PCI_VENDOR_ID_HABANALABS, PCI_IDS_GOYA), },
+     { 0, }
+};
+MODULE_DEVICE_TABLE(pci, ids);
+

drivers/misc/habanalabs/habanalabs_drv.c line 52

Quoted 10 lines
drivers/misc/habanalabs/habanalabs_drv.c new file +10 -0
+/**
+ * get_asic_type - translate device id to asic type
+ *
+ * @device: id of the PCI device
+ * @asic_type: pointer that will be filled by the asic type
+ *
+ * Translate device id to asic type.
+ * In case of unidentified device, return -1
+ */
+static int get_asic_type(u16 device, enum hl_asic_type *asic_type)

This can simply return the hl_asic_type, see also a comment in create_hdev(().

Quoted 81 lines
drivers/misc/habanalabs/habanalabs_drv.c new file +81 -0
+{
+     int rc = 0;
+
+     switch (device) {
+     case PCI_IDS_GOYA:
+             *asic_type = ASIC_GOYA;
+             break;
+     default:
+             *asic_type = rc = -1;
+             break;
+     }
+
+     return rc;
+}
+
+/**
+ * hl_device_open - open function for habanalabs device
+ *
+ * @inode: pointer to inode structure
+ * @filp: pointer to file structure
+ *
+ * Called when process opens an habanalabs device.
+ */
+int hl_device_open(struct inode *inode, struct file *filp)
+{
+     struct hl_device *hdev;
+     struct hl_fpriv *hpriv;
+
+     mutex_lock(&hl_devs_idr_lock);
+     hdev = idr_find(&hl_devs_idr, iminor(inode));
+     mutex_unlock(&hl_devs_idr_lock);
+
+     if (!hdev) {
+             pr_err("habanalabs: Couldn't find device %d:%d\n",
+                     imajor(inode), iminor(inode));
+             return -ENXIO;
+     }
+
+     hpriv = kzalloc(sizeof(*hpriv), GFP_KERNEL);
+     if (!hpriv)
+             return -ENOMEM;
+
+     hpriv->hdev = hdev;
+     filp->private_data = hpriv;
+     hpriv->filp = filp;
+     kref_init(&hpriv->refcount);
+     nonseekable_open(inode, filp);
+
+     hpriv->taskpid = find_get_pid(current->pid);
+
+     return 0;
+}
+
+/**
+ * create_hdev - create habanalabs device instance
+ *
+ * @dev: will hold the pointer to the new habanalabs device structure
+ * @pdev: pointer to the pci device
+ * @asic_type: in case of simulator device, which device is it
+ * @minor: in case of simulator device, the minor of the device
+ *
+ * Allocate memory for habanalabs device and initialize basic fields
+ * Identify the ASIC type
+ * Allocate ID (minor) for the device (only for real devices)
+ */
+int create_hdev(struct hl_device **dev, struct pci_dev *pdev,
+             enum hl_asic_type asic_type, int minor)
+{
+     struct hl_device *hdev;
+     int rc;
+
+     *dev = NULL;
+
+     hdev = kzalloc(sizeof(*hdev), GFP_KERNEL);
+     if (!hdev) {
+             if (pdev)
+                     dev_err(&pdev->dev,
+                             "Not enough memory for habanalabs device\n");
+             else
+                     pr_err("habanalabs: Not enough memory for  device\n");
+

drivers/misc/habanalabs/habanalabs_drv.c line 143

Quoted 10 lines
drivers/misc/habanalabs/habanalabs_drv.c new file +10 -0
+             return -ENOMEM;
+     }
+
+     hdev->major = hl_major;
+
+     hdev->disabled = true;
+     hdev->pdev = pdev; /* can be NULL in case of simulator device */
+
+     if (asic_type == ASIC_AUTO_DETECT) {
+             rc = get_asic_type(pdev->device, &hdev->asic_type);

You can just make it

                &hdev->asic_type = get_asic_type(pdev->device);

drivers/misc/habanalabs/habanalabs_drv.c line 151

Quoted 8 lines
drivers/misc/habanalabs/habanalabs_drv.c new file +8 -0
+             if (rc) {
+                     dev_err(&pdev->dev, "Unsupported ASIC\n");
+                     rc = -ENODEV;
+                     goto free_hdev;
+             }
+     } else {
+             hdev->asic_type = asic_type;
+     }
Quoted 3 lines

In the current version create_hdev() is always called with ASIC_AUTO_DETECT, what are the usecases for other types?

So I don't think I mentioned this, but we have a software simulator that we wrote for our ASICs.
To support that, you can load the driver in simulation mode. Most of the simulation code is in an asic-specific file (goya_simulator.c) which I don't intend to upstream because:
1. It does really nasty things to make the simulator work and those nasty things are totally un-upstreamable :)
2. We don't intend to open source the simulator, nor give it to customers, so there is no need to upstream that code.

Having said that, there are very few places in the common code, which I think all of them are in habanalabs_drv.c, that contain code which is for simulation mode.
One of those places is:
hdev->asic_type = asic_type;

Another place is the idr_replace below.

I hope that because we are talking about a couple of lines in the entire driver, and because by themselves they are totally valid, I could upstream them even if that path will never be taken. If even those few lines are problematic, I will remove them, but it will just make my life a bit harder.

Oded

Quoted 357 lines

drivers/misc/habanalabs/habanalabs_drv.c line 159

Quoted 8 lines
drivers/misc/habanalabs/habanalabs_drv.c new file +8 -0
+
+     mutex_lock(&hl_devs_idr_lock);
+
+     if (minor == -1) {
+             rc = idr_alloc(&hl_devs_idr, hdev, 0, HL_MAX_MINORS,
+                             GFP_KERNEL);
+     } else {
+             idr_replace(&hl_devs_idr, hdev, minor);

idr_replace can fail, can't it?

Quoted 339 lines
drivers/misc/habanalabs/habanalabs_drv.c new file +207 -0
+             rc = minor;
+     }
+
+     mutex_unlock(&hl_devs_idr_lock);
+
+     if (rc < 0) {
+             if (rc == -ENOSPC) {
+                     pr_err("habanalabs: too many devices in the system\n");
+                     rc = -EBUSY;
+             }
+             goto free_hdev;
+     }
+
+     hdev->id = rc;
+
+     *dev = hdev;
+
+     return 0;
+
+free_hdev:
+     kfree(hdev);
+     return rc;
+}
+
+/**
+ * destroy_hdev - destroy habanalabs device instance
+ *
+ * @dev: pointer to the habanalabs device structure
+ *
+ */
+void destroy_hdev(struct hl_device *hdev)
+{
+     /* Remove device from the device list */
+     mutex_lock(&hl_devs_idr_lock);
+     idr_remove(&hl_devs_idr, hdev->id);
+     mutex_unlock(&hl_devs_idr_lock);
+
+     kfree(hdev);
+}
+
+static int hl_pmops_suspend(struct device *dev)
+{
+     struct pci_dev *pdev = to_pci_dev(dev);
+     struct hl_device *hdev = pci_get_drvdata(pdev);
+
+     pr_debug("habanalabs: Going to suspend PCI device\n");
+
+     if (!hdev) {
+             pr_err("habanalabs: device pointer is NULL in suspend\n");
+             return 0;
+     }
+
+     return hl_device_suspend(hdev);
+}
+
+static int hl_pmops_resume(struct device *dev)
+{
+     struct pci_dev *pdev = to_pci_dev(dev);
+     struct hl_device *hdev = pci_get_drvdata(pdev);
+
+     pr_debug("habanalabs: Going to resume PCI device\n");
+
+     if (!hdev) {
+             pr_err("habanalabs: device pointer is NULL in resume\n");
+             return 0;
+     }
+
+     return hl_device_resume(hdev);
+}
+
+/**
+ * hl_pci_probe - probe PCI habanalabs devices
+ *
+ * @pdev: pointer to pci device
+ * @id: pointer to pci device id structure
+ *
+ * Standard PCI probe function for habanalabs device.
+ * Create a new habanalabs device and initialize it according to the
+ * device's type
+ */
+static int hl_pci_probe(struct pci_dev *pdev,
+                             const struct pci_device_id *id)
+{
+     struct hl_device *hdev;
+     int rc;
+
+     dev_info(&pdev->dev, HL_NAME
+              " device found [%04x:%04x] (rev %x)\n",
+              (int)pdev->vendor, (int)pdev->device, (int)pdev->revision);
+
+     rc = create_hdev(&hdev, pdev, ASIC_AUTO_DETECT, -1);
+     if (rc)
+             return rc;
+
+     pci_set_drvdata(pdev, hdev);
+
+     rc = hl_device_init(hdev, hl_class);
+     if (rc) {
+             dev_err(&pdev->dev, "Fatal error during habanalabs device init\n");
+             rc = -ENODEV;
+             goto disable_device;
+     }
+
+     return 0;
+
+disable_device:
+     pci_set_drvdata(pdev, NULL);
+     destroy_hdev(hdev);
+
+     return rc;
+}
+
+/**
+ * hl_pci_remove - remove PCI habanalabs devices
+ *
+ * @pdev: pointer to pci device
+ *
+ * Standard PCI remove function for habanalabs device
+ */
+static void hl_pci_remove(struct pci_dev *pdev)
+{
+     struct hl_device *hdev;
+
+     hdev = pci_get_drvdata(pdev);
+     if (!hdev)
+             return;
+
+     hl_device_fini(hdev);
+     pci_set_drvdata(pdev, NULL);
+
+     destroy_hdev(hdev);
+}
+
+static const struct dev_pm_ops hl_pm_ops = {
+     .suspend = hl_pmops_suspend,
+     .resume = hl_pmops_resume,
+};
+
+static struct pci_driver hl_pci_driver = {
+     .name = HL_NAME,
+     .id_table = ids,
+     .probe = hl_pci_probe,
+     .remove = hl_pci_remove,
+     .driver.pm = &hl_pm_ops,
+};
+
+/**
+ * hl_init - Initialize the habanalabs kernel driver
+ *
+ */
+static int __init hl_init(void)
+{
+     int rc;
+     dev_t dev;
+
+     pr_info("habanalabs: loading driver\n");
+
+     rc = alloc_chrdev_region(&dev, 0, HL_MAX_MINORS, HL_NAME);
+     if (rc < 0) {
+             pr_err("habanalabs: unable to get major\n");
+             return rc;
+     }
+
+     hl_major = MAJOR(dev);
+
+     hl_class = class_create(THIS_MODULE, HL_NAME);
+     if (IS_ERR(hl_class)) {
+             pr_err("habanalabs: failed to allocate class\n");
+             rc = PTR_ERR(hl_class);
+             goto remove_major;
+     }
+
+     rc = pci_register_driver(&hl_pci_driver);
+     if (rc) {
+             pr_err("habanalabs: failed to register pci device\n");
+             goto remove_class;
+     }
+
+     pr_debug("habanalabs: driver loaded\n");
+
+     return 0;
+
+remove_class:
+     class_destroy(hl_class);
+remove_major:
+     unregister_chrdev_region(MKDEV(hl_major, 0), HL_MAX_MINORS);
+     return rc;
+}
+
+/**
+ * hl_exit - Release all resources of the habanalabs kernel driver
+ *
+ */
+static void __exit hl_exit(void)
+{
+     pci_unregister_driver(&hl_pci_driver);
+
+     class_destroy(hl_class);
+     unregister_chrdev_region(MKDEV(hl_major, 0), HL_MAX_MINORS);
+
+     idr_destroy(&hl_devs_idr);
+
+     pr_debug("habanalabs: driver removed\n");
+}
+
+module_init(hl_init);
+module_exit(hl_exit);
drivers/misc/habanalabs/include/habanalabs_device_if.h new file +125 -1
new file mode 100644
index 000000000000..9dbb7077eabd
@@ -0,0 +1,125 @@
+/* SPDX-License-Identifier: GPL-2.0
+ *
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ *
+ */
+
+#ifndef HABANALABS_DEVICE_IF_H
+#define HABANALABS_DEVICE_IF_H
+
+#include <linux/types.h>
+
+/*
+ * PRIMARY QUEUE
+ */
+
+struct hl_bd {
+     __u64   ptr;
+     __u32   len;
+     union {
+             struct {
+                     __u32   repeat:16;
+                     __u32   res1:8;
+                     __u32   repeat_valid:1;
+                     __u32   res2:7;
+             };
+             __u32   ctl;
+     };
+};
+
+#define HL_BD_SIZE                   sizeof(struct hl_bd)
+
+/*
+ * BD_CTL_REPEAT_VALID tells the CP whether the repeat field in the BD CTL is
+ * valid. 1 means the repeat field is valid, 0 means not-valid,
+ * i.e. repeat == 1
+ */
+#define BD_CTL_REPEAT_VALID_SHIFT    24
+#define BD_CTL_REPEAT_VALID_MASK     0x01000000
+
+#define BD_CTL_SHADOW_INDEX_SHIFT    0
+#define BD_CTL_SHADOW_INDEX_MASK     0x00000FFF
+
+/*
+ * COMPLETION QUEUE
+ */
+
+struct hl_cq_entry {
+     __u32   data;
+};
+
+#define HL_CQ_ENTRY_SIZE             sizeof(struct hl_cq_entry)
+
+#define CQ_ENTRY_READY_SHIFT                 31
+#define CQ_ENTRY_READY_MASK                  0x80000000
+
+#define CQ_ENTRY_SHADOW_INDEX_VALID_SHIFT    30
+#define CQ_ENTRY_SHADOW_INDEX_VALID_MASK     0x40000000
+
+#define CQ_ENTRY_SHADOW_INDEX_SHIFT          BD_CTL_SHADOW_INDEX_SHIFT
+#define CQ_ENTRY_SHADOW_INDEX_MASK           BD_CTL_SHADOW_INDEX_MASK
+
+/*
+ * EVENT QUEUE
+ */
+
+struct hl_eq_header {
+     __u32 reserved;
+     union {
+             struct {
+                     __u32 ctx_id :10;
+                     __u32:6;
+                     __u32 opcode :10;
+                     __u32:5;
+                     __u32 ready :1;
+             };
+             __u32 ctl;
+     };
+};
+
+struct hl_eq_entry {
+     struct hl_eq_header hdr;
+     __u64 data[7];
+};
+
+#define HL_EQ_ENTRY_SIZE             sizeof(struct hl_eq_entry)
+
+#define EQ_CTL_READY_SHIFT           31
+#define EQ_CTL_READY_MASK            0x80000000
+
+#define EQ_CTL_EVENT_TYPE_SHIFT              16
+#define EQ_CTL_EVENT_TYPE_MASK               0x03FF0000
+
+enum pq_init_status {
+     PQ_INIT_STATUS_NA = 0,
+     PQ_INIT_STATUS_READY_FOR_CP,
+     PQ_INIT_STATUS_READY_FOR_HOST
+};
+
+/*
+ * ArmCP info
+ */
+
+#define VERSION_MAX_LEN                      128
+#define ARMCP_MAX_SENSORS            128
+
+struct armcp_sensor {
+     __u32 type;
+     __u32 flags;
+};
+
+/* must be aligned to 4 bytes */
+struct armcp_info {
+     struct armcp_sensor sensors[ARMCP_MAX_SENSORS];
+     __u8 kernel_version[VERSION_MAX_LEN];
+     __u32 reserved[3];
+     __u32 cpld_version;
+     __u32 infineon_version;
+     __u8 fuse_version[VERSION_MAX_LEN];
+     __u8 thermal_version[VERSION_MAX_LEN];
+     __u8 armcp_version[VERSION_MAX_LEN];
+     __u64 dram_size;
+};
+
+#endif /* HABANALABS_DEVICE_IF_H */
--
Quoted 2 lines

2.17.1

--
Sincerely yours,
Mike.

#7 lore raw

Re: [PATCH 01/15] habanalabs: add skeleton driver

In reply to Mike Rapoport
Quoted 25 lines · Mike Rapoport
Quoted 23 lines · Greg KH
Quoted 21 lines · Mike Rapoport
Quoted 8 lines · Oded Gabbay

+/**
+ * hl_device_release - release function for habanalabs device
+ *
+ * @inode: pointer to inode structure
+ * @filp: pointer to file structure
+ *
+ * Called when process closes an habanalabs device
+ */

It's nice to see docs coming along with the codei
I have some comments for the formatting.

kernel-doc won't be happy about missing return value descriptions, and although they are sometimes redundant or too obvious their absence makes 'make V=1 htmldocs' really noisy.

In general, it would be nice if you could link hanabnalabs driver kernel-doc somewhere in Documentation/ run 'make V=1 htmldocs'.

Quoted 1 line

+static int hl_device_release(struct inode *inode, struct file *filp)

Quoted 9 lines
Quoted 4 lines

There's no need for kerneldoc comments for static functions, as no one can call them and they are not part of any api.

So what would be better here is to just drop the /** line and use /*

Maybe it'd make sense to use /* for most of the comments in this driver as there are kernel-doc formatting issues in non-static functions as well, I was just too lazy to go over all of them.

Hi Mike,
That's what I'm going to do for v2, except for the comments in habanalabs.h, which we made sure are written according to kernel-doc. I promise that we will go over the entire code and make everything kernel-doc compatible (I'm opening a jira ticket now :) ) but it may take a couple of weeks or more.

In any case, I fixed all of your other comments for this patch. Thanks,
Oded

Quoted 9 lines
Quoted 4 lines

thanks,

greg k-h

--
Sincerely yours,
Mike.

#17 lore raw

Re: [PATCH 03/15] habanalabs: add basic Goya support

In reply to Mike Rapoport
Quoted 319 lines · Mike Rapoport
Quoted 317 lines · Oded Gabbay

This patch adds a basic support for the Goya device. The code initializes the device's PCI controller and PCI bars. It also initializes various S/W structures and adds some basic helper functions.

---
 drivers/misc/habanalabs/Makefile            |   5 +-
 drivers/misc/habanalabs/device.c            |  71 +++
 drivers/misc/habanalabs/goya/Makefile       |   3 +
 drivers/misc/habanalabs/goya/goya.c         | 633 ++++++++++++++++++++
 drivers/misc/habanalabs/goya/goyaP.h        | 125 ++++
 drivers/misc/habanalabs/habanalabs.h        | 131 ++++
 drivers/misc/habanalabs/habanalabs_drv.c    |   3 +
 drivers/misc/habanalabs/include/goya/goya.h | 115 ++++
 8 files changed, 1085 insertions(+), 1 deletion(-)
 create mode 100644 drivers/misc/habanalabs/goya/Makefile
 create mode 100644 drivers/misc/habanalabs/goya/goya.c
 create mode 100644 drivers/misc/habanalabs/goya/goyaP.h
 create mode 100644 drivers/misc/habanalabs/include/goya/goya.h
drivers/misc/habanalabs/Makefile +4 -1
index b41433a09e02..6f1ead69bd77 100644
@@ -4,4 +4,7 @@
 
 obj-m        := habanalabs.o
 
-habanalabs-y := habanalabs_drv.o device.o
\ No newline at end of file
+habanalabs-y := habanalabs_drv.o device.o
+
+include $(src)/goya/Makefile
+habanalabs-y += $(HL_GOYA_FILES)
drivers/misc/habanalabs/device.c +71 -0
index 376b55eb73d4..a4276ef559b3 100644
@@ -116,8 +116,11 @@ static int device_setup_cdev(struct hl_device *hdev, struct class *hclass,
  */
 static int device_early_init(struct hl_device *hdev)
 {
+     int rc;
+
      switch (hdev->asic_type) {
      case ASIC_GOYA:
+             goya_set_asic_funcs(hdev);
              sprintf(hdev->asic_name, "GOYA");
              break;
      default:
@@ -126,6 +129,10 @@ static int device_early_init(struct hl_device *hdev)
              return -EINVAL;
      }
 
+     rc = hdev->asic_funcs->early_init(hdev);
+     if (rc)
+             return rc;
+
      return 0;
 }
 
@@ -137,6 +144,10 @@ static int device_early_init(struct hl_device *hdev)
  */
 static void device_early_fini(struct hl_device *hdev)
 {
+
+     if (hdev->asic_funcs->early_fini)
+             hdev->asic_funcs->early_fini(hdev);
+
 }
 
 /**
@@ -150,8 +161,15 @@ static void device_early_fini(struct hl_device *hdev)
  */
 int hl_device_suspend(struct hl_device *hdev)
 {
+     int rc;
+
      pci_save_state(hdev->pdev);
 
+     rc = hdev->asic_funcs->suspend(hdev);
+     if (rc)
+             dev_err(hdev->dev,
+                     "Failed to disable PCI access of device CPU\n");
+
      /* Shut down the device */
      pci_disable_device(hdev->pdev);
      pci_set_power_state(hdev->pdev, PCI_D3hot);
@@ -181,6 +199,13 @@ int hl_device_resume(struct hl_device *hdev)
              return rc;
      }
 
+     rc = hdev->asic_funcs->resume(hdev);
+     if (rc) {
+             dev_err(hdev->dev,
+                     "Failed to enable PCI access from device CPU\n");
+             return rc;
+     }
+
      return 0;
 }
 
@@ -208,11 +233,21 @@ int hl_device_init(struct hl_device *hdev, struct class *hclass)
      if (rc)
              goto release_device;
 
+     /*
+      * Start calling ASIC initialization. First S/W then H/W and finally
+      * late init
+      */
+     rc = hdev->asic_funcs->sw_init(hdev);
+     if (rc)
+             goto early_fini;
+
      dev_notice(hdev->dev,
              "Successfully added device to habanalabs driver\n");
 
      return 0;
 
+early_fini:
+     device_early_fini(hdev);
 release_device:
      device_destroy(hclass, hdev->dev->devt);
      cdev_del(&hdev->cdev);
@@ -243,6 +278,9 @@ void hl_device_fini(struct hl_device *hdev)
      /* Mark device as disabled */
      hdev->disabled = true;
 
+     /* Call ASIC S/W finalize function */
+     hdev->asic_funcs->sw_fini(hdev);
+
      device_early_fini(hdev);
 
      /* Hide device from user */
@@ -329,3 +367,36 @@ int hl_poll_timeout_device_memory(struct hl_device *hdev, void __iomem *addr,
 
      return (*val ? 0 : -ETIMEDOUT);
 }
+
+/*
+ * MMIO register access helper functions.
+ */
+
+/**
+ * hl_rreg - Read an MMIO register
+ *
+ * @hdev: pointer to habanalabs device structure
+ * @reg: MMIO register offset (in bytes)
+ *
+ * Returns the value of the MMIO register we are asked to read
+ *
+ */
+inline u32 hl_rreg(struct hl_device *hdev, u32 reg)
+{
+     return readl(hdev->rmmio + reg);
+}
+
+/**
+ * hl_wreg - Write to an MMIO register
+ *
+ * @hdev: pointer to habanalabs device structure
+ * @reg: MMIO register offset (in bytes)
+ * @val: 32-bit value
+ *
+ * Writes the 32-bit value into the MMIO register
+ *
+ */
+inline void hl_wreg(struct hl_device *hdev, u32 reg, u32 val)
+{
+     writel(val, hdev->rmmio + reg);
+}
drivers/misc/habanalabs/goya/Makefile new file +3 -0
new file mode 100644
index 000000000000..5ebf3d0d5794
@@ -0,0 +1,3 @@
+subdir-ccflags-y += -I$(src)
+
+HL_GOYA_FILES :=  goya/goya.o
\ No newline at end of file
drivers/misc/habanalabs/goya/goya.c new file +130 -0
new file mode 100644
index 000000000000..b2952296b890
@@ -0,0 +1,633 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ */
+
+#include "goyaP.h"
+#include "include/goya/asic_reg/goya_masks.h"
+
+#include <linux/fs.h>
+#include <linux/delay.h>
+#include <linux/vmalloc.h>
+#include <linux/sched.h>
+#include <linux/genalloc.h>
+#include <linux/sysfs.h>
+#include <linux/kfifo.h>
+#include <linux/dma-mapping.h>
+#include <linux/firmware.h>
+#include <linux/log2.h>
+#include <linux/hwmon.h>
+#include <linux/string.h>
+#include <linux/io.h>
+
+/*
+ * GOYA security scheme:
+ *
+ * 1. Host is protected by:
+ *        - Range registers (When MMU is enabled, DMA RR does NOT protect host)
+ *        - MMU
+ *
+ * 2. DRAM is protected by:
+ *        - Range registers (protect the first 512MB)
+ *        - MMU (isolation between users)
+ *
+ * 3. Configuration is protected by:
+ *        - Range registers
+ *        - Protection bits
+ *
+ * When MMU is disabled:
+ *
+ * QMAN DMA: PQ, CQ, CP, DMA are secured.
+ * PQ, CB and the data are on the host.
+ *
+ * QMAN TPC/MME:
+ * PQ, CQ and CP are not secured.
+ * PQ, CB and the data are on the SRAM/DRAM.
+ *
+ * Since QMAN DMA is secured, KMD is parsing the DMA CB:
+ *     - KMD checks DMA pointer
+ *     - WREG, MSG_PROT are not allowed.
+ *     - MSG_LONG/SHORT are allowed.
+ *
+ * A read/write transaction by the QMAN to a protected area will succeed if
+ * and only if the QMAN's CP is secured and MSG_PROT is used
+ *
+ *
+ * When MMU is enabled:
+ *
+ * QMAN DMA: PQ, CQ and CP are secured.
+ * MMU is set to bypass on the Secure props register of the QMAN.
+ * The reasons we don't enable MMU for PQ, CQ and CP are:
+ *     - PQ entry is in kernel address space and KMD doesn't map it.
+ *     - CP writes to MSIX register and to kernel address space (completion
+ *       queue).
+ *
+ * DMA is not secured but because CP is secured, KMD still needs to parse the
+ * CB, but doesn't need to check the DMA addresses.
+ *
+ * For QMAN DMA 0, DMA is also secured because only KMD uses this DMA and KMD
+ * doesn't map memory in MMU.
+ *
+ * QMAN TPC/MME: PQ, CQ and CP aren't secured (no change from MMU disabled mode)
+ *
+ * DMA RR does NOT protect host because DMA is not secured
+ *
+ */
+
+#define GOYA_MMU_REGS_NUM            61
+
+#define GOYA_DMA_POOL_BLK_SIZE               0x100           /* 256 bytes */
+
+#define GOYA_RESET_TIMEOUT_MSEC              500             /* 500ms */
+#define GOYA_PLDM_RESET_TIMEOUT_MSEC 20000           /* 20s */
+#define GOYA_RESET_WAIT_MSEC         1               /* 1ms */
+#define GOYA_CPU_RESET_WAIT_MSEC     100             /* 100ms */
+#define GOYA_PLDM_RESET_WAIT_MSEC    1000            /* 1s */
+#define GOYA_CPU_TIMEOUT_USEC                10000000        /* 10s */
+#define GOYA_TEST_QUEUE_WAIT_USEC    100000          /* 100ms */
+
+#define GOYA_QMAN0_FENCE_VAL         0xD169B243
+
+#define GOYA_MAX_INITIATORS          20
+
+static void goya_get_fixed_properties(struct hl_device *hdev)
+{
+     struct asic_fixed_properties *prop = &hdev->asic_prop;
+
+     prop->completion_queues_count = NUMBER_OF_CMPLT_QUEUES;
+
+     prop->dram_base_address = DRAM_PHYS_BASE;
+     prop->dram_size = DRAM_PHYS_DEFAULT_SIZE;
+     prop->dram_end_address = prop->dram_base_address + prop->dram_size;
+     prop->dram_user_base_address = DRAM_BASE_ADDR_USER;
+
+     prop->sram_base_address = SRAM_BASE_ADDR;
+     prop->sram_size = SRAM_SIZE;
+     prop->sram_end_address = prop->sram_base_address + prop->sram_size;
+     prop->sram_user_base_address = prop->sram_base_address +
+                                             SRAM_USER_BASE_OFFSET;
+
+     prop->host_phys_base_address = HOST_PHYS_BASE;
+     prop->va_space_host_start_address = VA_HOST_SPACE_START;
+     prop->va_space_host_end_address = VA_HOST_SPACE_END;
+     prop->va_space_dram_start_address = VA_DDR_SPACE_START;
+     prop->va_space_dram_end_address = VA_DDR_SPACE_END;
+     prop->cfg_size = CFG_SIZE;
+     prop->max_asid = MAX_ASID;
+     prop->tpc_enabled_mask = TPC_ENABLED_MASK;
+
+     prop->high_pll = PLL_HIGH_DEFAULT;
+}
+
+/**
+ * goya_pci_bars_map - Map PCI BARS of Goya device
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ * Request PCI regions and map them to kernel virtual addresses.
+ * Returns 0 on success
Quoted 8 lines

drivers/misc/habanalabs/goya/goya.c line 136

Quoted 6 lines
drivers/misc/habanalabs/goya/goya.c new file +6 -0
+ *
+ */
+int goya_pci_bars_map(struct hl_device *hdev)
+{
+     struct pci_dev *pdev = hdev->pdev;
+     int rc;

You could just init rc= -ENODEV here and avoid the hassle below.

But the next line assigns rc the return value of pci_request_regions... I could do rc= -ENODEV before the calls to pci_ioremapbar but then if this function will change in the future and I will have another possibility of a different error, it will seem strange.
I honestly prefer to write code in drivers as explicitly as possible, even if that means a bit more code.

Quoted 97 lines
Quoted 97 lines
drivers/misc/habanalabs/goya/goya.c new file +97 -0
+
+     rc = pci_request_regions(pdev, HL_NAME);
+     if (rc) {
+             dev_err(hdev->dev, "Cannot obtain PCI resources\n");
+             return rc;
+     }
+
+     hdev->pcie_bar[SRAM_CFG_BAR_ID] =
+                     pci_ioremap_bar(pdev, SRAM_CFG_BAR_ID);
+     if (!hdev->pcie_bar[SRAM_CFG_BAR_ID]) {
+             dev_err(hdev->dev, "pci_ioremap_bar failed for CFG\n");
+             rc = -ENODEV;
+             goto err_release_regions;
+     }
+
+     hdev->pcie_bar[MSIX_BAR_ID] = pci_ioremap_bar(pdev, MSIX_BAR_ID);
+     if (!hdev->pcie_bar[MSIX_BAR_ID]) {
+             dev_err(hdev->dev, "pci_ioremap_bar failed for MSIX\n");
+             rc = -ENODEV;
+             goto err_unmap_sram_cfg;
+     }
+
+     hdev->pcie_bar[DDR_BAR_ID] = pci_ioremap_wc_bar(pdev, DDR_BAR_ID);
+     if (!hdev->pcie_bar[DDR_BAR_ID]) {
+             dev_err(hdev->dev, "pci_ioremap_bar failed for DDR\n");
+             rc = -ENODEV;
+             goto err_unmap_msix;
+     }
+
+     hdev->rmmio = hdev->pcie_bar[SRAM_CFG_BAR_ID] +
+                             (CFG_BASE - SRAM_BASE_ADDR);
+
+     return 0;
+
+err_unmap_msix:
+     iounmap(hdev->pcie_bar[MSIX_BAR_ID]);
+err_unmap_sram_cfg:
+     iounmap(hdev->pcie_bar[SRAM_CFG_BAR_ID]);
+err_release_regions:
+     pci_release_regions(pdev);
+
+     return rc;
+}
+
+/**
+ * goya_pci_bars_unmap - Unmap PCI BARS of Goya device
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ * Release all PCI BARS and unmap their virtual addresses
+ *
+ */
+static void goya_pci_bars_unmap(struct hl_device *hdev)
+{
+     struct pci_dev *pdev = hdev->pdev;
+
+     iounmap(hdev->pcie_bar[DDR_BAR_ID]);
+     iounmap(hdev->pcie_bar[MSIX_BAR_ID]);
+     iounmap(hdev->pcie_bar[SRAM_CFG_BAR_ID]);
+     pci_release_regions(pdev);
+}
+
+/**
+ * goya_elbi_write - Write through the ELBI interface
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ * return 0 on success, -1 on failure
+ *
+ */
+static int goya_elbi_write(struct hl_device *hdev, u64 addr, u32 data)
+{
+     struct pci_dev *pdev = hdev->pdev;
+     ktime_t timeout;
+     u32 val;
+
+     /* Clear previous status */
+     pci_write_config_dword(pdev, mmPCI_CONFIG_ELBI_STS, 0);
+
+     pci_write_config_dword(pdev, mmPCI_CONFIG_ELBI_ADDR, (u32) addr);
+     pci_write_config_dword(pdev, mmPCI_CONFIG_ELBI_DATA, data);
+     pci_write_config_dword(pdev, mmPCI_CONFIG_ELBI_CTRL,
+                             PCI_CONFIG_ELBI_CTRL_WRITE);
+
+     timeout = ktime_add_ms(ktime_get(), 10);
+     for (;;) {
+             pci_read_config_dword(pdev, mmPCI_CONFIG_ELBI_STS, &val);
+             if (val & PCI_CONFIG_ELBI_STS_MASK)
+                     break;
+             if (ktime_compare(ktime_get(), timeout) > 0) {
+                     pci_read_config_dword(pdev, mmPCI_CONFIG_ELBI_STS,
+                                             &val);
+                     break;
+             }
+             usleep_range(300, 500);
+     }
+
Quoted 8 lines

drivers/misc/habanalabs/goya/goya.c line 239

Quoted 6 lines
drivers/misc/habanalabs/goya/goya.c new file +6 -0
+     if ((val & PCI_CONFIG_ELBI_STS_MASK) == PCI_CONFIG_ELBI_STS_DONE)
+             return 0;
+
+     if (val & PCI_CONFIG_ELBI_STS_ERR) {
+             dev_err(hdev->dev, "Error writing to ELBI\n");o
+             return -1;

Please change -1 to an error code, say -EIO...

Of course, done.

Quoted 22 lines
Quoted 22 lines
drivers/misc/habanalabs/goya/goya.c new file +21 -0
+     }
+
+     if (!(val & PCI_CONFIG_ELBI_STS_MASK)) {
+             dev_err(hdev->dev, "ELBI write didn't finish in time\n");
+             return -1;
+     }
+
+     dev_err(hdev->dev, "ELBI write has undefined bits in status\n");
+     return -1;
+}
+
+/**
+ * goya_iatu_write - iatu write routine
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ */
+static int goya_iatu_write(struct hl_device *hdev, u32 addr, u32 data)
+{
+     u32 dbi_offset;
+     int rc;
Quoted 9 lines

drivers/misc/habanalabs/goya/goya.c line 265

Quoted 5 lines
drivers/misc/habanalabs/goya/goya.c new file +5 -0
+
+     dbi_offset = addr & 0xFFF;
+
+     rc = goya_elbi_write(hdev, CFG_BASE + mmPCIE_AUX_DBI, 0x00300000);
+     rc |= goya_elbi_write(hdev, mmPCIE_DBI_BASE + dbi_offset, data);

hmm, error code in goya_elbi_write probably won't work... Any reason to try the second write if the first failed?

You are correct it definitely won't work. But I didn't want to put an if() after each call to that function - it happens a few more times in the code.
And because the second write won't do any harm either, I thought this is a more elegant solution to make the code more readable.

Quoted 43 lines
Quoted 43 lines
drivers/misc/habanalabs/goya/goya.c new file +43 -0
+
+     return rc;
+}
+
+void goya_reset_link_through_bridge(struct hl_device *hdev)
+{
+     struct pci_dev *pdev = hdev->pdev;
+     struct pci_dev *parent_port;
+     u16 val;
+
+     parent_port = pdev->bus->self;
+     pci_read_config_word(parent_port, PCI_BRIDGE_CONTROL, &val);
+     val |= PCI_BRIDGE_CTL_BUS_RESET;
+     pci_write_config_word(parent_port, PCI_BRIDGE_CONTROL, val);
+     ssleep(1);
+
+     val &= ~(PCI_BRIDGE_CTL_BUS_RESET);
+     pci_write_config_word(parent_port, PCI_BRIDGE_CONTROL, val);
+     ssleep(3);
+}
+
+/**
+ * goya_set_ddr_bar_base - set DDR bar to map specific device address
+ *
+ * @hdev: pointer to hl_device structure
+ * @addr: address in DDR. Must be aligned to DDR bar size
+ *
+ * This function configures the iATU so that the DDR bar will start at the
+ * specified addr.
+ *
+ */
+static int goya_set_ddr_bar_base(struct hl_device *hdev, u64 addr)
+{
+     struct goya_device *goya = hdev->asic_specific;
+     int rc;
+
+     if ((goya) && (goya->ddr_bar_cur_addr == addr))
+             return 0;
+
+     /* Inbound Region 1 - Bar 4 - Point to DDR */
+     rc = goya_iatu_write(hdev, 0x314, lower_32_bits(addr));
+     rc |= goya_iatu_write(hdev, 0x318, upper_32_bits(addr));
+     rc |= goya_iatu_write(hdev, 0x300, 0);
Quoted 8 lines

drivers/misc/habanalabs/goya/goya.c line 314

Quoted 6 lines
drivers/misc/habanalabs/goya/goya.c new file +6 -0
+     /* Enable + Bar match + match enable + Bar 4 */
+     rc |= goya_iatu_write(hdev, 0x304, 0xC0080400);
+
+     /* Return the DBI window to the default location */
+     rc |= goya_elbi_write(hdev, CFG_BASE + mmPCIE_AUX_DBI, 0);
+     rc |= goya_elbi_write(hdev, CFG_BASE + mmPCIE_AUX_DBI_32, 0);

And here as well.

Same remark as the previous one

Quoted 7 lines

drivers/misc/habanalabs/goya/goya.c line 319

Quoted 5 lines
drivers/misc/habanalabs/goya/goya.c new file +5 -0
+
+     if (rc) {
+             dev_err(hdev->dev, "failed to map DDR bar to 0x%08llx\n", addr);
+             return rc;
+     }

I believe that at least here you'd want to return an error code.

Fixed

Quoted 43 lines
Quoted 43 lines
drivers/misc/habanalabs/goya/goya.c new file +42 -0
+
+     if (goya)
+             goya->ddr_bar_cur_addr = addr;
+
+     return 0;
+}
+
+/**
+ * goya_init_iatu - Initialize the iATU unit inside the PCI controller
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ * This is needed in case the firmware doesn't initialize the iATU
+ *
+ */
+static int goya_init_iatu(struct hl_device *hdev)
+{
+     int rc;
+
+     /* Inbound Region 0 - Bar 0 - Point to SRAM_BASE_ADDR */
+     rc  = goya_iatu_write(hdev, 0x114, lower_32_bits(SRAM_BASE_ADDR));
+     rc |= goya_iatu_write(hdev, 0x118, upper_32_bits(SRAM_BASE_ADDR));
+     rc |= goya_iatu_write(hdev, 0x100, 0);
+     /* Enable + Bar match + match enable */
+     rc |= goya_iatu_write(hdev, 0x104, 0xC0080000);
+
+     /* Inbound Region 1 - Bar 4 - Point to DDR */
+     rc |= goya_set_ddr_bar_base(hdev, DRAM_PHYS_BASE);
+
+     /* Outbound Region 0 - Point to Host */
+     rc |= goya_iatu_write(hdev, 0x008, lower_32_bits(HOST_PHYS_BASE));
+     rc |= goya_iatu_write(hdev, 0x00C, upper_32_bits(HOST_PHYS_BASE));
+     rc |= goya_iatu_write(hdev, 0x010,
+             lower_32_bits(HOST_PHYS_BASE + HOST_PHYS_SIZE - 1));
+     rc |= goya_iatu_write(hdev, 0x014, 0);
+     rc |= goya_iatu_write(hdev, 0x018, 0);
+     rc |= goya_iatu_write(hdev, 0x020,
+             upper_32_bits(HOST_PHYS_BASE + HOST_PHYS_SIZE - 1));
+     /* Increase region size */
+     rc |= goya_iatu_write(hdev, 0x000, 0x00002000);
+     /* Enable */
+     rc |= goya_iatu_write(hdev, 0x004, 0x80000000);
Quoted 8 lines

drivers/misc/habanalabs/goya/goya.c line 318

Quoted 6 lines
drivers/misc/habanalabs/goya/goya.c new file +6 -0
+
+     /* Return the DBI window to the default location */
+     rc |= goya_elbi_write(hdev, CFG_BASE + mmPCIE_AUX_DBI, 0);
+     rc |= goya_elbi_write(hdev, CFG_BASE + mmPCIE_AUX_DBI_32, 0);
+
+     return rc;

Ditto

Fixed

Quoted 130 lines
Quoted 130 lines
drivers/misc/habanalabs/goya/goya.c new file +129 -0
+}
+
+/**
+ * goya_early_init - GOYA early initialization code
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ * Verify PCI bars
+ * Set DMA masks
+ * PCI controller initialization
+ * Map PCI bars
+ *
+ */
+static int goya_early_init(struct hl_device *hdev)
+{
+     struct asic_fixed_properties *prop = &hdev->asic_prop;
+     struct pci_dev *pdev = hdev->pdev;
+     u32 val;
+     int rc;
+
+     goya_get_fixed_properties(hdev);
+
+     /* Check BAR sizes */
+     if (pci_resource_len(pdev, SRAM_CFG_BAR_ID) != CFG_BAR_SIZE) {
+             dev_err(hdev->dev,
+                     "Not " HL_NAME "? BAR %d size %llu, expecting %llu\n",
+                     SRAM_CFG_BAR_ID,
+                     pci_resource_len(pdev, SRAM_CFG_BAR_ID),
+                     CFG_BAR_SIZE);
+             return -ENODEV;
+     }
+
+     if (pci_resource_len(pdev, MSIX_BAR_ID) != MSIX_BAR_SIZE) {
+             dev_err(hdev->dev,
+                     "Not " HL_NAME "? BAR %d size %llu, expecting %llu\n",
+                     MSIX_BAR_ID, pci_resource_len(pdev, MSIX_BAR_ID),
+                     MSIX_BAR_SIZE);
+             return -ENODEV;
+     }
+
+     prop->dram_pci_bar_size = pci_resource_len(pdev, DDR_BAR_ID);
+
+     /* set DMA mask for GOYA */
+     rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(39));
+     if (rc) {
+             dev_warn(hdev->dev, "Unable to set pci dma mask to 39 bits\n");
+             rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
+             if (rc) {
+                     dev_err(hdev->dev,
+                             "Unable to set pci dma mask to 32 bits\n");
+                     return rc;
+             }
+     }
+
+     rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(39));
+     if (rc) {
+             dev_warn(hdev->dev,
+                     "Unable to set pci consistent dma mask to 39 bits\n");
+             rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
+             if (rc) {
+                     dev_err(hdev->dev,
+                             "Unable to set pci consistent dma mask to 32 bits\n");
+                     return rc;
+             }
+     }
+
+     if (hdev->reset_pcilink)
+             goya_reset_link_through_bridge(hdev);
+
+     rc = pci_enable_device_mem(pdev);
+     if (rc) {
+             dev_err(hdev->dev, "can't enable PCI device\n");
+             return rc;
+     }
+
+     pci_set_master(pdev);
+
+     rc = goya_init_iatu(hdev);
+     if (rc) {
+             dev_err(hdev->dev, "Failed to initialize iATU\n");
+             goto disable_device;
+     }
+
+     rc = goya_pci_bars_map(hdev);
+     if (rc) {
+             dev_err(hdev->dev, "Failed to initialize PCI BARS\n");
+             goto disable_device;
+     }
+
+     val = RREG32(mmPSOC_GLOBAL_CONF_BOOT_STRAP_PINS);
+     if (val & PSOC_GLOBAL_CONF_BOOT_STRAP_PINS_SRIOV_EN_MASK)
+             dev_warn(hdev->dev,
+                     "PCI strap is not configured correctly, PCI bus errors may occur\n");
+
+     return 0;
+
+disable_device:
+     pci_clear_master(pdev);
+     pci_disable_device(pdev);
+
+     return rc;
+}
+
+/**
+ * goya_early_fini - GOYA early finalization code
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ * Unmap PCI bars
+ *
+ */
+int goya_early_fini(struct hl_device *hdev)
+{
+     goya_pci_bars_unmap(hdev);
+
+     pci_clear_master(hdev->pdev);
+     pci_disable_device(hdev->pdev);
+
+     return 0;
+}
+
+/**
+ * goya_sw_init - Goya software initialization code
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ */
+static int goya_sw_init(struct hl_device *hdev)
+{
Quoted 8 lines

drivers/misc/habanalabs/goya/goya.c line 501

Quoted 5 lines
drivers/misc/habanalabs/goya/goya.c new file +5 -0
+     struct goya_device *goya;
+     int rc;
+
+     /* Allocate device structure */
+     goya = kzalloc(sizeof(*goya), GFP_KERNEL);

Consider using devm_k[mz]alloc() for memory allocations throughout the driver. I didn't check all the spots where it can be applicable.

I honestly wasn't aware of that. We never used that in AMD drivers (which where I spent most of my kernel time).
I'll look into that offline but for now I don't really want to change into it blindly in all locations, unless there is some hard kernel rule for using that in drivers.

Quoted 30 lines
Quoted 30 lines
drivers/misc/habanalabs/goya/goya.c new file +29 -0
+     if (!goya)
+             return -ENOMEM;
+
+     /* according to goya_init_iatu */
+     goya->ddr_bar_cur_addr = DRAM_PHYS_BASE;
+     hdev->asic_specific = goya;
+
+     /* Create DMA pool for small allocations */
+     hdev->dma_pool = dma_pool_create(dev_name(hdev->dev),
+                     &hdev->pdev->dev, GOYA_DMA_POOL_BLK_SIZE, 8, 0);
+     if (!hdev->dma_pool) {
+             dev_err(hdev->dev, "failed to create DMA pool\n");
+             rc = -ENOMEM;
+             goto free_goya_device;
+     }
+
+     hdev->cpu_accessible_dma_mem =
+                     hdev->asic_funcs->dma_alloc_coherent(hdev,
+                                     CPU_ACCESSIBLE_MEM_SIZE,
+                                     &hdev->cpu_accessible_dma_address,
+                                     GFP_KERNEL | __GFP_ZERO);
+
+     if (!hdev->cpu_accessible_dma_mem) {
+             dev_err(hdev->dev,
+                     "failed to allocate %d of dma memory for CPU accessible memory space\n",
+                     CPU_ACCESSIBLE_MEM_SIZE);
+             rc = -ENOMEM;
+             goto free_dma_pool;
+     }
Quoted 8 lines

drivers/misc/habanalabs/goya/goya.c line 536

Quoted 6 lines
drivers/misc/habanalabs/goya/goya.c new file +6 -0
+
+     hdev->cpu_accessible_dma_pool = gen_pool_create(CPU_PKT_SHIFT, -1);
+     if (!hdev->cpu_accessible_dma_pool) {
+             dev_err(hdev->dev,
+                     "Failed to create CPU accessible DMA pool\n");
+             rc = -ENOMEM;

You could init rc = -ENOMEM at the beginning and save the duplication.

Again, I don't agree with that programming paradigm. If I do that, and then I'll add code at the beginning of the function in the likes of:
rc = foo()
I will insert a bug.
So I prefer the duplication and make the code more robust to future changes.

Quoted 83 lines
Quoted 83 lines
drivers/misc/habanalabs/goya/goya.c new file +82 -0
+             goto free_cpu_pq_dma_mem;
+     }
+
+     rc = gen_pool_add(hdev->cpu_accessible_dma_pool,
+                             (u64) hdev->cpu_accessible_dma_mem,
+                             CPU_ACCESSIBLE_MEM_SIZE, -1);
+     if (rc) {
+             dev_err(hdev->dev,
+                     "Failed to add memory to CPU accessible DMA pool\n");
+             rc = -EFAULT;
+             goto free_cpu_pq_pool;
+     }
+
+     spin_lock_init(&goya->hw_queues_lock);
+
+     return 0;
+
+free_cpu_pq_pool:
+     gen_pool_destroy(hdev->cpu_accessible_dma_pool);
+free_cpu_pq_dma_mem:
+     hdev->asic_funcs->dma_free_coherent(hdev, CPU_ACCESSIBLE_MEM_SIZE,
+                     hdev->cpu_accessible_dma_mem,
+                     hdev->cpu_accessible_dma_address);
+free_dma_pool:
+     dma_pool_destroy(hdev->dma_pool);
+free_goya_device:
+     kfree(goya);
+
+     return rc;
+}
+
+/**
+ * goya_sw_fini - Goya software tear-down code
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ */
+int goya_sw_fini(struct hl_device *hdev)
+{
+     struct goya_device *goya = hdev->asic_specific;
+
+     gen_pool_destroy(hdev->cpu_accessible_dma_pool);
+
+     hdev->asic_funcs->dma_free_coherent(hdev, CPU_ACCESSIBLE_MEM_SIZE,
+                     hdev->cpu_accessible_dma_mem,
+                     hdev->cpu_accessible_dma_address);
+
+     dma_pool_destroy(hdev->dma_pool);
+
+     kfree(goya);
+
+     return 0;
+}
+
+int goya_suspend(struct hl_device *hdev)
+{
+     return 0;
+}
+
+int goya_resume(struct hl_device *hdev)
+{
+     return 0;
+}
+
+void *goya_dma_alloc_coherent(struct hl_device *hdev, size_t size,
+                                     dma_addr_t *dma_handle, gfp_t flags)
+{
+     return dma_alloc_coherent(&hdev->pdev->dev, size, dma_handle, flags);
+}
+
+void goya_dma_free_coherent(struct hl_device *hdev, size_t size, void *cpu_addr,
+                             dma_addr_t dma_handle)
+{
+     dma_free_coherent(&hdev->pdev->dev, size, cpu_addr, dma_handle);
+}
+
+static const struct hl_asic_funcs goya_funcs = {
+     .early_init = goya_early_init,
+     .early_fini = goya_early_fini,
+     .sw_init = goya_sw_init,
+     .sw_fini = goya_sw_fini,
+     .suspend = goya_suspend,
Quoted 8 lines

drivers/misc/habanalabs/goya/goya.c line 621

Quoted 3 lines
drivers/misc/habanalabs/goya/goya.c new file +3 -0
+     .resume = goya_resume,
+     .dma_alloc_coherent = goya_dma_alloc_coherent,
+     .dma_free_coherent = goya_dma_free_coherent,

Is there any additional functionality that is planned in goya or gaudi in these two functions?
It seems like they are not really needed, at least at the moment and for sure that don't need to be part of ASIC ops.

So this relates to the simulator support, because there the implementation of these two functions is totally different as I don't have pci device.

Quoted 473 lines
Quoted 466 lines
drivers/misc/habanalabs/goya/goya.c new file +12 -0
+};
+
+/**
+ * goya_set_asic_funcs - set Goya function pointers
+ *
+ * @*hdev: pointer to hl_device structure
+ *
+ */
+void goya_set_asic_funcs(struct hl_device *hdev)
+{
+     hdev->asic_funcs = &goya_funcs;
+}
drivers/misc/habanalabs/goya/goyaP.h new file +125 -0
new file mode 100644
index 000000000000..0e12c56472bd
@@ -0,0 +1,125 @@
+/* SPDX-License-Identifier: GPL-2.0
+ *
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ *
+ */
+
+#ifndef GOYAP_H_
+#define GOYAP_H_
+
+#include "habanalabs.h"
+#include "include/goya/goya.h"
+
+#define NUMBER_OF_CMPLT_QUEUES               5
+#define NUMBER_OF_EXT_HW_QUEUES              5
+#define NUMBER_OF_CPU_HW_QUEUES              1
+#define NUMBER_OF_INT_HW_QUEUES              9
+#define NUMBER_OF_HW_QUEUES          (NUMBER_OF_EXT_HW_QUEUES + \
+                                     NUMBER_OF_CPU_HW_QUEUES + \
+                                     NUMBER_OF_INT_HW_QUEUES)
+
+/*
+ * Number of MSIX interrupts IDS:
+ * Each completion queue has 1 ID
+ * The event queue has 1 ID
+ * ArmCP reset has 1 ID
+ */
+#define NUMBER_OF_INTERRUPTS         (NUMBER_OF_CMPLT_QUEUES + 2)
+
+#if (NUMBER_OF_HW_QUEUES >= HL_MAX_QUEUES)
+#error "Number of H/W queues must be smaller than HL_MAX_QUEUES"
+#endif
+
+#if (NUMBER_OF_INTERRUPTS > GOYA_MSIX_ENTRIES)
+#error "Number of MSIX interrupts must be smaller or equal to GOYA_MSIX_ENTRIES"
+#endif
+
+#define QMAN_FENCE_TIMEOUT_USEC              10000   /* 10 ms */
+
+#define QMAN_STOP_TIMEOUT_USEC               100000  /* 100 ms */
+
+#define TPC_MAX_NUM                  8
+#define TPC_ENABLED_MASK             0xFF
+
+#define DMA_MAX_NUM                  5
+
+#define PLL_HIGH_DEFAULT             1575000000      /* 1.575 GHz */
+
+#define GOYA_ARMCP_INFO_TIMEOUT              10000000        /* 10s */
+
+#define DRAM_PHYS_DEFAULT_SIZE               0x100000000ull  /* 4GB */
+
+/*
+ * SRAM Memory Map for KMD
+ *
+ * KMD occupies KMD_SRAM_SIZE bytes from the start of SRAM. It is used for
+ * MME/TPC QMANs
+ *
+ */
+
+#define MME_QMAN_BASE_OFFSET 0x000000        /* Must be 0 */
+#define MME_QMAN_LENGTH              64
+#define TPC_QMAN_LENGTH              64
+
+#define TPC0_QMAN_BASE_OFFSET        (MME_QMAN_BASE_OFFSET + \
+                             (MME_QMAN_LENGTH * QMAN_PQ_ENTRY_SIZE))
+#define TPC1_QMAN_BASE_OFFSET        (TPC0_QMAN_BASE_OFFSET + \
+                             (TPC_QMAN_LENGTH * QMAN_PQ_ENTRY_SIZE))
+#define TPC2_QMAN_BASE_OFFSET        (TPC1_QMAN_BASE_OFFSET + \
+                             (TPC_QMAN_LENGTH * QMAN_PQ_ENTRY_SIZE))
+#define TPC3_QMAN_BASE_OFFSET        (TPC2_QMAN_BASE_OFFSET + \
+                             (TPC_QMAN_LENGTH * QMAN_PQ_ENTRY_SIZE))
+#define TPC4_QMAN_BASE_OFFSET        (TPC3_QMAN_BASE_OFFSET + \
+                             (TPC_QMAN_LENGTH * QMAN_PQ_ENTRY_SIZE))
+#define TPC5_QMAN_BASE_OFFSET        (TPC4_QMAN_BASE_OFFSET + \
+                             (TPC_QMAN_LENGTH * QMAN_PQ_ENTRY_SIZE))
+#define TPC6_QMAN_BASE_OFFSET        (TPC5_QMAN_BASE_OFFSET + \
+                             (TPC_QMAN_LENGTH * QMAN_PQ_ENTRY_SIZE))
+#define TPC7_QMAN_BASE_OFFSET        (TPC6_QMAN_BASE_OFFSET + \
+                             (TPC_QMAN_LENGTH * QMAN_PQ_ENTRY_SIZE))
+
+#define SRAM_KMD_RES_OFFSET  (TPC7_QMAN_BASE_OFFSET + \
+                             (TPC_QMAN_LENGTH * QMAN_PQ_ENTRY_SIZE))
+
+#if (SRAM_KMD_RES_OFFSET >= KMD_SRAM_RESERVED_SIZE)
+#error "MME/TPC QMANs SRAM space exceeds limit"
+#endif
+
+#define SRAM_USER_BASE_OFFSET        KMD_SRAM_RESERVED_SIZE
+
+#define DMA_MAX_TRANSFER_SIZE        0xFFFFFFFF
+
+#define HW_CAP_PLL           0x00000001
+#define HW_CAP_DDR_0         0x00000002
+#define HW_CAP_DDR_1         0x00000004
+#define HW_CAP_MME           0x00000008
+#define HW_CAP_CPU           0x00000010
+#define HW_CAP_DMA           0x00000020
+#define HW_CAP_MSIX          0x00000040
+#define HW_CAP_CPU_Q         0x00000080
+#define HW_CAP_MMU           0x00000100
+#define HW_CAP_TPC_MBIST     0x00000200
+#define HW_CAP_GOLDEN                0x00000400
+#define HW_CAP_TPC           0x00000800
+
+#define CPU_PKT_SHIFT                5
+#define CPU_PKT_SIZE         (1 << CPU_PKT_SHIFT)
+#define CPU_PKT_MASK         (~((1 << CPU_PKT_SHIFT) - 1))
+#define CPU_MAX_PKTS_IN_CB   32
+#define CPU_CB_SIZE          (CPU_PKT_SIZE * CPU_MAX_PKTS_IN_CB)
+#define CPU_ACCESSIBLE_MEM_SIZE      (HL_QUEUE_LENGTH * CPU_CB_SIZE)
+
+enum goya_fw_component {
+     FW_COMP_UBOOT,
+     FW_COMP_PREBOOT
+};
+
+struct goya_device {
+     /* TODO: remove hw_queues_lock after moving to scheduler code */
+     spinlock_t      hw_queues_lock;
+     u64             ddr_bar_cur_addr;
+     u32             hw_cap_initialized;
+};
+
+#endif /* GOYAP_H_ */
drivers/misc/habanalabs/habanalabs.h +131 -0
index 7e1b088b677c..97844825f7a8 100644
@@ -21,11 +21,64 @@
 
 #define HL_NAME                              "habanalabs"
 
+#define HL_MAX_QUEUES                        128
+
 struct hl_device;
 
 
 
 
+/**
+ * struct asic_fixed_properties - ASIC specific immutable properties.
+ * @sram_base_address: SRAM physical start address.
+ * @sram_end_address: SRAM physical end address.
+ * @sram_user_base_address - SRAM physical start address for user access.
+ * @dram_base_address: DRAM physical start address.
+ * @dram_end_address: DRAM physical end address.
+ * @dram_user_base_address: DRAM physical start address for user access.
+ * @dram_size: DRAM total size.
+ * @dram_pci_bar_size: size of PCI bar towards DRAM.
+ * @host_phys_base_address: base physical address of host memory for
+ *                           transactions that the device generates.
+ * @va_space_host_start_address: base address of virtual memory range for
+ *                               mapping host memory.
+ * @va_space_host_end_address: end address of virtual memory range for
+ *                             mapping host memory.
+ * @va_space_dram_start_address: base address of virtual memory range for
+ *                               mapping DRAM memory.
+ * @va_space_dram_end_address: end address of virtual memory range for
+ *                             mapping DRAM memory.
+ * @cfg_size: configuration space size on SRAM.
+ * @sram_size: total size of SRAM.
+ * @max_asid: maximum number of open contexts (ASIDs).
+ * @completion_queues_count: number of completion queues.
+ * @high_pll: high PLL frequency used by the device.
+ * @tpc_enabled_mask: which TPCs are enabled.
+ */
+struct asic_fixed_properties {
+     u64                     sram_base_address;
+     u64                     sram_end_address;
+     u64                     sram_user_base_address;
+     u64                     dram_base_address;
+     u64                     dram_end_address;
+     u64                     dram_user_base_address;
+     u64                     dram_size;
+     u64                     dram_pci_bar_size;
+     u64                     host_phys_base_address;
+     u64                     va_space_host_start_address;
+     u64                     va_space_host_end_address;
+     u64                     va_space_dram_start_address;
+     u64                     va_space_dram_end_address;
+     u32                     cfg_size;
+     u32                     sram_size;
+     u32                     max_asid;
+     u32                     high_pll;
+     u8                      completion_queues_count;
+     u8                      tpc_enabled_mask;
+};
+
+
+#define HL_QUEUE_LENGTH                      256
 
 
 /*
@@ -47,6 +100,30 @@ enum hl_asic_type {
 
 
 
+/**
+ * struct hl_asic_funcs - ASIC specific functions that are can be called from
+ *                        common code.
+ * @early_init: sets up early driver state (pre sw_init), doesn't configure H/W.
+ * @early_fini: tears down what was done in early_init.
+ * @sw_init: sets up driver state, does not configure H/W.
+ * @sw_fini: tears down driver state, does not configure H/W.
+ * @suspend: handles IP specific H/W or SW changes for suspend.
+ * @resume: handles IP specific H/W or SW changes for resume.
+ * @dma_alloc_coherent: DMA allocate coherent memory.
+ * @dma_free_coherent: free DMA allocation.
+ */
+struct hl_asic_funcs {
+     int (*early_init)(struct hl_device *hdev);
+     int (*early_fini)(struct hl_device *hdev);
+     int (*sw_init)(struct hl_device *hdev);
+     int (*sw_fini)(struct hl_device *hdev);
+     int (*suspend)(struct hl_device *hdev);
+     int (*resume)(struct hl_device *hdev);
+     void* (*dma_alloc_coherent)(struct hl_device *hdev, size_t size,
+                                     dma_addr_t *dma_handle, gfp_t flag);
+     void (*dma_free_coherent)(struct hl_device *hdev, size_t size,
+                                     void *cpu_addr, dma_addr_t dma_handle);
+};
 
 /*
  * FILE PRIVATE STRUCTURE
@@ -78,26 +155,78 @@ struct hl_fpriv {
  */
 #define HL_MAX_MINORS        256
 
+/*
+ * Registers read & write functions.
+ */
+
+u32 hl_rreg(struct hl_device *hdev, u32 reg);
+void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
+
+#define hl_poll_timeout(hdev, addr, val, cond, sleep_us, timeout_us) \
+     readl_poll_timeout(hdev->rmmio + addr, val, cond, sleep_us, timeout_us)
+
+#define RREG32(reg) hl_rreg(hdev, (reg))
+#define WREG32(reg, v) hl_wreg(hdev, (reg), (v))
+#define DREG32(reg) pr_info("REGISTER: " #reg " : 0x%08X\n", \
+                             hl_rreg(hdev, (reg)))
+
+#define WREG32_P(reg, val, mask)                             \
+     do {                                                    \
+             u32 tmp_ = RREG32(reg);                         \
+             tmp_ &= (mask);                                 \
+             tmp_ |= ((val) & ~(mask));                      \
+             WREG32(reg, tmp_);                              \
+     } while (0)
+#define WREG32_AND(reg, and) WREG32_P(reg, 0, and)
+#define WREG32_OR(reg, or) WREG32_P(reg, or, ~(or))
+
+#define REG_FIELD_SHIFT(reg, field) reg##_##field##_SHIFT
+#define REG_FIELD_MASK(reg, field) reg##_##field##_MASK
+#define WREG32_FIELD(reg, field, val)        \
+     WREG32(mm##reg, (RREG32(mm##reg) & ~REG_FIELD_MASK(reg, field)) | \
+                     (val) << REG_FIELD_SHIFT(reg, field))
+
 /**
  * struct hl_device - habanalabs device structure.
  * @pdev: pointer to PCI device, can be NULL in case of simulator device.
+ * @pcie_bar: array of available PCIe bars.
+ * @rmmio: configuration area address on SRAM.
  * @cdev: related char device.
  * @dev: realted kernel basic device structure.
  * @asic_name: ASIC specific nmae.
  * @asic_type: ASIC specific type.
+ * @dma_pool: DMA pool for small allocations.
+ * @cpu_accessible_dma_mem: KMD <-> ArmCP shared memory CPU address.
+ * @cpu_accessible_dma_address: KMD <-> ArmCP shared memory DMA address.
+ * @cpu_accessible_dma_pool: KMD <-> ArmCP shared memory pool.
+ * @asic_prop: ASIC specific immutable properties.
+ * @asic_funcs: ASIC specific functions.
+ * @asic_specific: ASIC specific information to use only from ASIC files.
  * @major: habanalabs KMD major.
  * @id: device minor.
  * @disabled: is device disabled.
  */
 struct hl_device {
      struct pci_dev                  *pdev;
+     void __iomem                    *pcie_bar[6];
+     void __iomem                    *rmmio;
      struct cdev                     cdev;
      struct device                   *dev;
      char                            asic_name[16];
      enum hl_asic_type               asic_type;
+     struct dma_pool                 *dma_pool;
+     void                            *cpu_accessible_dma_mem;
+     dma_addr_t                      cpu_accessible_dma_address;
+     struct gen_pool                 *cpu_accessible_dma_pool;
+     struct asic_fixed_properties    asic_prop;
+     const struct hl_asic_funcs      *asic_funcs;
+     void                            *asic_specific;
      u32                             major;
      u16                             id;
      u8                              disabled;
+
+     /* Parameters for bring-up */
+     u8                              reset_pcilink;
 };
 
 /*
@@ -146,4 +275,6 @@ void hl_device_fini(struct hl_device *hdev);
 int hl_device_suspend(struct hl_device *hdev);
 int hl_device_resume(struct hl_device *hdev);
 
+void goya_set_asic_funcs(struct hl_device *hdev);
+
 #endif /* HABANALABSP_H_ */
drivers/misc/habanalabs/habanalabs_drv.c +3 -0
index 15217975327b..79545003b7c2 100644
@@ -136,6 +136,9 @@ int create_hdev(struct hl_device **dev, struct pci_dev *pdev,
 
      hdev->major = hl_major;
 
+     /* Parameters for bring-up - set them to defaults */
+     hdev->reset_pcilink = 0;
+
      hdev->disabled = true;
      hdev->pdev = pdev; /* can be NULL in case of simulator device */
 
drivers/misc/habanalabs/include/goya/goya.h new file +115 -1
new file mode 100644
index 000000000000..192a1450cbb1
@@ -0,0 +1,115 @@
+/* SPDX-License-Identifier: GPL-2.0
+ *
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ *
+ * Author: Oded Gabbay <[email protected]>
+ *
+ */
+
+#ifndef GOYA_H
+#define GOYA_H
+
+#include "asic_reg/goya_regs.h"
+
+#include <linux/types.h>
+
+#define SRAM_CFG_BAR_ID              0
+#define MSIX_BAR_ID          2
+#define DDR_BAR_ID           4
+
+#define CFG_BAR_SIZE         0x10000000ull           /* 256MB */
+#define MSIX_BAR_SIZE                0x1000ull               /* 4KB */
+
+#define CFG_BASE             0x7FFC000000ull
+#define CFG_SIZE             0x4000000               /* 32MB CFG + 32MB DBG*/
+
+#define SRAM_BASE_ADDR               0x7FF0000000ull
+#define SRAM_SIZE            0x32A0000               /* 50.625MB */
+#define KMD_SRAM_RESERVED_SIZE       0x8000                  /* 32KB */
+
+#define SRAM_BASE_ADDR_USER  (0x7FF0000000ull + KMD_SRAM_RESERVED_SIZE)
+#define SRAM_SIZE_USER               (SRAM_SIZE - KMD_SRAM_RESERVED_SIZE)
+
+#define DRAM_PHYS_BASE               0x0ull
+
+#define CPU_FW_IMAGE_SIZE    0x10000000      /* 256MB */
+#define MMU_PAGE_TABLES_SIZE 0x0E000000      /* 224MB */
+#define CPU_PQ_PKT_SIZE              0x00001000      /* 4KB */
+#define CPU_PQ_DATA_SIZE     0x01FFF000      /* 32MB - 4KB  */
+
+#define CPU_FW_IMAGE_ADDR    DRAM_PHYS_BASE
+#define MMU_PAGE_TABLES_ADDR (CPU_FW_IMAGE_ADDR + CPU_FW_IMAGE_SIZE)
+#define CPU_PQ_PKT_ADDR              (MMU_PAGE_TABLES_ADDR + MMU_PAGE_TABLES_SIZE)
+#define CPU_PQ_DATA_ADDR     (CPU_PQ_PKT_ADDR + CPU_PQ_PKT_SIZE)
+#define DRAM_BASE_ADDR_USER  (CPU_PQ_DATA_ADDR + CPU_PQ_DATA_SIZE)
+
+#define HOST_PHYS_BASE               0x8000000000ull         /* 0.5TB */
+#define HOST_PHYS_SIZE               0x1000000000000ull      /* 0.25PB (48 bits) */
+
+#define VA_HOST_SPACE_START  0x1000000000000ull      /* 256TB */
+#define VA_HOST_SPACE_END    0x3FF8000000000ull      /* 1PB - 1TB */
+#define VA_HOST_SPACE_SIZE   (VA_HOST_SPACE_END - \
+                                     VA_HOST_SPACE_START) /* 767TB */
+
+#define VA_DDR_SPACE_START   0x800000000ull          /* 32GB */
+#define VA_DDR_SPACE_END     0x2000000000ull         /* 128GB */
+#define VA_DDR_SPACE_SIZE    (VA_DDR_SPACE_END - \
+                                     VA_DDR_SPACE_START)     /* 128GB */
+
+#define CPU_BOOT_ADDR                0x7FF8040000ull
+
+#define UBOOT_FW_OFFSET              0x100000                /* 1MB in SRAM */
+#define LINUX_FW_OFFSET              0x800000                /* 8BM in DDR */
+
+#define GOYA_MSIX_ENTRIES    8
+#define EVENT_QUEUE_MSIX_IDX 5
+#define ARMCP_RESET_MSIX_IDX 6
+
+#define QMAN_PQ_ENTRY_SIZE   16                      /* Bytes */
+
+#define MAX_ASID             1024
+
+#define PROT_BITS_OFFS               0xF80
+
+/*
+ * Queue Numbering
+ *
+ * The external queues (DMA channels + CPU) MUST be before the internal queues
+ * and each group (DMA channels + CPU and internal) must be contiguous inside
+ * itself but there can be a gap between the two groups (although not
+ * recommended)
+ */
+
+enum goya_queue_id {
+     GOYA_QUEUE_ID_DMA_0 = 0,
+     GOYA_QUEUE_ID_DMA_1,
+     GOYA_QUEUE_ID_DMA_2,
+     GOYA_QUEUE_ID_DMA_3,
+     GOYA_QUEUE_ID_DMA_4,
+     GOYA_QUEUE_ID_CPU_PQ,
+     GOYA_QUEUE_ID_MME,
+     GOYA_QUEUE_ID_TPC0,
+     GOYA_QUEUE_ID_TPC1,
+     GOYA_QUEUE_ID_TPC2,
+     GOYA_QUEUE_ID_TPC3,
+     GOYA_QUEUE_ID_TPC4,
+     GOYA_QUEUE_ID_TPC5,
+     GOYA_QUEUE_ID_TPC6,
+     GOYA_QUEUE_ID_TPC7,
+     GOYA_QUEUE_ID_SIZE
+};
+
+enum goya_pll_index {
+     CPU_PLL = 0,
+     IC_PLL,
+     MC_PLL,
+     MME_PLL,
+     PCI_PLL,
+     EMMC_PLL,
+     TPC_PLL
+};
+
+#define GOYA_PLL_FREQ_LOW            50000000 /* 50 MHz */
+
+#endif /* GOYA_H */
--
Quoted 2 lines

2.17.1

--
Sincerely yours,
Mike.

#22 lore raw

Re: [PATCH 04/15] habanalabs: add context and ASID modules

In reply to Mike Rapoport
Quoted 582 lines · Mike Rapoport
Quoted 3 lines · Oded Gabbay

This patch adds two modules - ASID and context.

Each user process the opens a device's file must have at least one context

^that

Quoted 433 lines

before it is able to "work" with the device. Each context has its own device address-space and contains information about its runtime state (its active command submissions).

To have address-space separation between contexts, each context is assigned a unique ASID, which stands for "address-space id". Goya supports up to 1024 ASIDs.

Currently, the driver doesn't support multiple contexts. Therefore, the user doesn't need to actively create a context. A "primary context" is created automatically when the user opens the device's file.

---
 drivers/misc/habanalabs/Makefile         |   2 +-
 drivers/misc/habanalabs/asid.c           |  58 +++++++++
 drivers/misc/habanalabs/context.c        | 155 +++++++++++++++++++++++
 drivers/misc/habanalabs/device.c         |  47 +++++++
 drivers/misc/habanalabs/habanalabs.h     |  70 ++++++++++
 drivers/misc/habanalabs/habanalabs_drv.c |  46 ++++++-
 6 files changed, 375 insertions(+), 3 deletions(-)
 create mode 100644 drivers/misc/habanalabs/asid.c
 create mode 100644 drivers/misc/habanalabs/context.c
drivers/misc/habanalabs/Makefile +1 -1
index 6f1ead69bd77..3ffbadc2ca01 100644
@@ -4,7 +4,7 @@
 
 obj-m        := habanalabs.o
 
-habanalabs-y := habanalabs_drv.o device.o
+habanalabs-y := habanalabs_drv.o device.o context.o asid.o
 
 include $(src)/goya/Makefile
 habanalabs-y += $(HL_GOYA_FILES)
drivers/misc/habanalabs/asid.c new file +58 -0
new file mode 100644
index 000000000000..0ce84c8f5a47
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ */
+
+#include "habanalabs.h"
+
+#include <linux/slab.h>
+#include <linux/types.h>
+
+int hl_asid_init(struct hl_device *hdev)
+{
+     hdev->asid_bitmap = kcalloc(BITS_TO_LONGS(hdev->asic_prop.max_asid),
+                                     sizeof(*hdev->asid_bitmap), GFP_KERNEL);
+     if (!hdev->asid_bitmap)
+             return -ENOMEM;
+
+     mutex_init(&hdev->asid_mutex);
+
+     /* ASID 0 is reserved for KMD */
+     set_bit(0, hdev->asid_bitmap);
+
+     return 0;
+}
+
+void hl_asid_fini(struct hl_device *hdev)
+{
+     mutex_destroy(&hdev->asid_mutex);
+     kfree(hdev->asid_bitmap);
+}
+
+unsigned long hl_asid_alloc(struct hl_device *hdev)
+{
+     unsigned long found;
+
+     mutex_lock(&hdev->asid_mutex);
+
+     found = find_first_zero_bit(hdev->asid_bitmap,
+                                     hdev->asic_prop.max_asid);
+     if (found == hdev->asic_prop.max_asid)
+             found = 0;
+     else
+             set_bit(found, hdev->asid_bitmap);
+
+     mutex_unlock(&hdev->asid_mutex);
+
+     return found;
+}
+
+void hl_asid_free(struct hl_device *hdev, unsigned long asid)
+{
+     if (WARN((asid == 0 || asid >= hdev->asic_prop.max_asid),
+                                             "Invalid ASID %lu", asid))
+             return;
+     clear_bit(asid, hdev->asid_bitmap);
+}
drivers/misc/habanalabs/context.c new file +155 -0
new file mode 100644
index 000000000000..cdcad077e5cf
@@ -0,0 +1,155 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ */
+
+#include "habanalabs.h"
+
+#include <linux/sched.h>
+#include <linux/delay.h>
+
+static void hl_ctx_fini(struct hl_ctx *ctx)
+{
+     struct hl_device *hdev = ctx->hdev;
+
+     if (ctx->asid != HL_KERNEL_ASID_ID)
+             hl_asid_free(hdev, ctx->asid);
+}
+
+void hl_ctx_do_release(struct kref *ref)
+{
+     struct hl_ctx *ctx;
+
+     ctx = container_of(ref, struct hl_ctx, refcount);
+
+     dev_dbg(ctx->hdev->dev, "Now really releasing context %d\n", ctx->asid);
+
+     hl_ctx_fini(ctx);
+
+     if (ctx->hpriv)
+             hl_hpriv_put(ctx->hpriv);
+
+     kfree(ctx);
+}
+
+int hl_ctx_create(struct hl_device *hdev, struct hl_fpriv *hpriv)
+{
+     struct hl_ctx_mgr *mgr = &hpriv->ctx_mgr;
+     struct hl_ctx *ctx;
+     int rc;
+
+     ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
+     if (!ctx) {
+             rc = -ENOMEM;
+             goto out_err;
+     }
+
+     rc = hl_ctx_init(hdev, ctx, false);
+     if (rc)
+             goto free_ctx;
+
+     hl_hpriv_get(hpriv);
+     ctx->hpriv = hpriv;
+
+     /* TODO: remove for multiple contexts */
+     hpriv->ctx = ctx;
+     hdev->user_ctx = ctx;
+
+     mutex_lock(&mgr->ctx_lock);
+     rc = idr_alloc(&mgr->ctx_handles, ctx, 1, 0, GFP_KERNEL);
+     mutex_unlock(&mgr->ctx_lock);
+
+     if (rc < 0) {
+             dev_err(hdev->dev, "Failed to allocate IDR for a new CTX\n");
+             hl_ctx_free(hdev, ctx);
+             goto out_err;
+     }
+
+     return 0;
+
+free_ctx:
+     kfree(ctx);
+out_err:
+     return rc;
+}
+
+void hl_ctx_free(struct hl_device *hdev, struct hl_ctx *ctx)
+{
+     if (kref_put(&ctx->refcount, hl_ctx_do_release) == 1)
+             return;
+
+     dev_warn(hdev->dev,
+             "Context %d closed or terminated but its CS are executing\n",
+             ctx->asid);
+}
+
+int hl_ctx_init(struct hl_device *hdev, struct hl_ctx *ctx, bool is_kernel_ctx)
+{
+     ctx->hdev = hdev;
+
+     kref_init(&ctx->refcount);
+
+     if (is_kernel_ctx) {
+             ctx->asid = HL_KERNEL_ASID_ID; /* KMD gets ASID 0 */
+     } else {
+             ctx->asid = hl_asid_alloc(hdev);
+             if (!ctx->asid) {
+                     dev_err(hdev->dev, "No free ASID, failed to create context\n");
+                     return -ENOMEM;
+             }
+     }
+
+     dev_dbg(hdev->dev, "Created context with ASID %u\n", ctx->asid);
+
+     return 0;
+}
+
+void hl_ctx_get(struct hl_device *hdev, struct hl_ctx *ctx)
+{
+     kref_get(&ctx->refcount);
+}
+
+int hl_ctx_put(struct hl_ctx *ctx)
+{
+     return kref_put(&ctx->refcount, hl_ctx_do_release);
+}
+
+/**
+ * hl_ctx_mgr_init - initialize the context manager
+ *
+ * @mgr: pointer to context manager structure
+ *
+ * This manager is an object inside the hpriv object of the user process.
+ * The function is called when a user process opens the FD.
+ */
+void hl_ctx_mgr_init(struct hl_ctx_mgr *mgr)
+{
+     mutex_init(&mgr->ctx_lock);
+     idr_init(&mgr->ctx_handles);
+}
+
+/**
+ * hl_ctx_mgr_fini - finalize the context manager
+ *
+ * @hdev: pointer to device structure
+ * @mgr: pointer to context manager structure
+ *
+ * This function goes over all the contexts in the manager and frees them.
+ * It is called when a process closes the FD.
+ */
+void hl_ctx_mgr_fini(struct hl_device *hdev, struct hl_ctx_mgr *mgr)
+{
+     struct hl_ctx *ctx;
+     struct idr *idp;
+     u32 id;
+
+     idp = &mgr->ctx_handles;
+
+     idr_for_each_entry(idp, ctx, id)
+             hl_ctx_free(hdev, ctx);
+
+     idr_destroy(&mgr->ctx_handles);
+     mutex_destroy(&mgr->ctx_lock);
+}
drivers/misc/habanalabs/device.c +47 -0
index a4276ef559b3..84ce9fcb52da 100644
@@ -23,6 +23,12 @@ static void hpriv_release(struct kref *ref)
      put_pid(hpriv->taskpid);
 
      kfree(hpriv);
+
+     /* Now the FD is really closed */
+     atomic_dec(&hdev->fd_open_cnt);
+
+     /* This allows a new user context to open the device */
+     hdev->user_ctx = NULL;
 }
 
 void hl_hpriv_get(struct hl_fpriv *hpriv)
@@ -47,6 +53,8 @@ static int hl_device_release(struct inode *inode, struct file *filp)
 {
      struct hl_fpriv *hpriv = filp->private_data;
 
+     hl_ctx_mgr_fini(hpriv->hdev, &hpriv->ctx_mgr);
+
      filp->private_data = NULL;
 
      hl_hpriv_put(hpriv);
@@ -133,7 +141,20 @@ static int device_early_init(struct hl_device *hdev)
      if (rc)
              return rc;
 
+     rc = hl_asid_init(hdev);
+     if (rc)
+             goto early_fini;
+
+     mutex_init(&hdev->device_open);
+     atomic_set(&hdev->fd_open_cnt, 0);
+
      return 0;
+
+early_fini:
+     if (hdev->asic_funcs->early_fini)
+             hdev->asic_funcs->early_fini(hdev);
+
+     return rc;
 }
 
 /**
@@ -145,9 +166,12 @@ static int device_early_init(struct hl_device *hdev)
 static void device_early_fini(struct hl_device *hdev)
 {
 
+     hl_asid_fini(hdev);
+
      if (hdev->asic_funcs->early_fini)
              hdev->asic_funcs->early_fini(hdev);
 
+     mutex_destroy(&hdev->device_open);
 }
 
 /**
@@ -241,11 +265,30 @@ int hl_device_init(struct hl_device *hdev, struct class *hclass)
      if (rc)
              goto early_fini;
 
+     /* Allocate the kernel context */
+     hdev->kernel_ctx = kzalloc(sizeof(*hdev->kernel_ctx), GFP_KERNEL);
+     if (!hdev->kernel_ctx) {
+             rc = -ENOMEM;
+             goto sw_fini;
+     }
+
+     hdev->user_ctx = NULL;
+
+     rc = hl_ctx_init(hdev, hdev->kernel_ctx, true);
+     if (rc) {
+             dev_err(hdev->dev, "failed to initialize kernel context\n");
+             goto free_ctx;
+     }
+
      dev_notice(hdev->dev,
              "Successfully added device to habanalabs driver\n");
 
      return 0;
 
+free_ctx:
+     kfree(hdev->kernel_ctx);
+sw_fini:
+     hdev->asic_funcs->sw_fini(hdev);
 early_fini:
      device_early_fini(hdev);
 release_device:
@@ -278,6 +321,10 @@ void hl_device_fini(struct hl_device *hdev)
      /* Mark device as disabled */
      hdev->disabled = true;
 
+     /* Release kernel context */
+     if ((hdev->kernel_ctx) && (hl_ctx_put(hdev->kernel_ctx) != 1))
+             dev_err(hdev->dev, "kernel ctx is still alive\n");
+
      /* Call ASIC S/W finalize function */
      hdev->asic_funcs->sw_fini(hdev);
 
drivers/misc/habanalabs/habanalabs.h +43 -0
index 97844825f7a8..d003a6af2131 100644
@@ -125,6 +125,45 @@ struct hl_asic_funcs {
                                      void *cpu_addr, dma_addr_t dma_handle);
 };
 
+
+
+
+
+/*
+ * CONTEXTS
+ */
+
+#define HL_KERNEL_ASID_ID    0
+
+/**
+ * struct hl_ctx - user/kernel context.
+ * @hpriv: pointer to the private (KMD) data of the process (fd).
+ * @hdev: pointer to the device structure.
+ * @refcount: reference counter for the context. Context is released only when
+ *           this hits 0l. It is incremented on CS and CS_WAIT.
+ * @asid: context's unique address space ID in the device's MMU.
+ */
+struct hl_ctx {
+     struct hl_fpriv         *hpriv;
+     struct hl_device        *hdev;
+     struct kref             refcount;
+     u32                     asid;
+};
+
+/**
+ * struct hl_ctx_mgr - for handling multiple contexts.
+ * @ctx_lock: protects ctx_handles.
+ * @ctx_handles: idr to hold all ctx handles.
+ */
+struct hl_ctx_mgr {
+     struct mutex            ctx_lock;
+     struct idr              ctx_handles;
+};
+
+
+
+
+
 /*
  * FILE PRIVATE STRUCTURE
  */
@@ -134,12 +173,16 @@ struct hl_asic_funcs {
  * @hdev: habanalabs device structure.
  * @filp: pointer to the given file structure.
  * @taskpid: current process ID.
+ * @ctx: current executing context.
+ * @ctx_mgr: context manager to handle multiple context for this FD.
  * @refcount: number of related contexts.
  */
 struct hl_fpriv {
      struct hl_device        *hdev;
      struct file             *filp;
      struct pid              *taskpid;
+     struct hl_ctx           *ctx; /* TODO: remove for multiple ctx */
+     struct hl_ctx_mgr       ctx_mgr;
      struct kref             refcount;
 };
 
@@ -195,13 +238,19 @@ void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
  * @dev: realted kernel basic device structure.

drivers/misc/habanalabs/habanalabs.h void hl_wreg(struct hl_device *hdev, u32 reg, u32 val); · line 248

Quoted 10 lines
drivers/misc/habanalabs/habanalabs.h +4 -0
  * @asic_name: ASIC specific nmae.
  * @asic_type: ASIC specific type.
+ * @kernel_ctx: KMD context structure.
  * @dma_pool: DMA pool for small allocations.
  * @cpu_accessible_dma_mem: KMD <-> ArmCP shared memory CPU address.
  * @cpu_accessible_dma_address: KMD <-> ArmCP shared memory DMA address.
  * @cpu_accessible_dma_pool: KMD <-> ArmCP shared memory pool.
+ * @asid_bitmap: holds used/available ASIDs.
+ * @asid_mutex: protects asid_bitmap.
+ * @device_open: lock for sanity checks upon FD open.

device_open is an ambiguous name for a lock

Quoted 128 lines
drivers/misc/habanalabs/habanalabs.h +23 -0
  * @asic_prop: ASIC specific immutable properties.
  * @asic_funcs: ASIC specific functions.
  * @asic_specific: ASIC specific information to use only from ASIC files.
+ * @user_ctx: current user context executing.
+ * @fd_open_cnt: number of open context executing.
  * @major: habanalabs KMD major.
  * @id: device minor.
  * @disabled: is device disabled.
@@ -214,13 +263,21 @@ struct hl_device {
      struct device                   *dev;
      char                            asic_name[16];
      enum hl_asic_type               asic_type;
+     struct hl_ctx                   *kernel_ctx;
      struct dma_pool                 *dma_pool;
      void                            *cpu_accessible_dma_mem;
      dma_addr_t                      cpu_accessible_dma_address;
      struct gen_pool                 *cpu_accessible_dma_pool;
+     unsigned long                   *asid_bitmap;
+     struct mutex                    asid_mutex;
+     /* TODO: change to rw_sem for multiple contexts (same as other IOCTL) */
+     struct mutex                    device_open;
      struct asic_fixed_properties    asic_prop;
      const struct hl_asic_funcs      *asic_funcs;
      void                            *asic_specific;
+     /* TODO: The following fields should be moved for multi-context */
+     struct hl_ctx                   *user_ctx;
+     atomic_t                        fd_open_cnt;
      u32                             major;
      u16                             id;
      u8                              disabled;
@@ -270,10 +327,23 @@ int hl_poll_timeout_memory(struct hl_device *hdev, u64 addr, u32 timeout_us,
 int hl_poll_timeout_device_memory(struct hl_device *hdev, void __iomem *addr,
                              u32 timeout_us, u32 *val);
 
+int hl_asid_init(struct hl_device *hdev);
+void hl_asid_fini(struct hl_device *hdev);
+unsigned long hl_asid_alloc(struct hl_device *hdev);
+void hl_asid_free(struct hl_device *hdev, unsigned long asid);
+
+int hl_ctx_create(struct hl_device *hdev, struct hl_fpriv *hpriv);
+void hl_ctx_free(struct hl_device *hdev, struct hl_ctx *ctx);
+int hl_ctx_init(struct hl_device *hdev, struct hl_ctx *ctx, bool is_kernel_ctx);
+int hl_ctx_put(struct hl_ctx *ctx);
+void hl_ctx_mgr_init(struct hl_ctx_mgr *mgr);
+void hl_ctx_mgr_fini(struct hl_device *hdev, struct hl_ctx_mgr *mgr);
 int hl_device_init(struct hl_device *hdev, struct class *hclass);
 void hl_device_fini(struct hl_device *hdev);
 int hl_device_suspend(struct hl_device *hdev);
 int hl_device_resume(struct hl_device *hdev);
+void hl_hpriv_get(struct hl_fpriv *hpriv);
+void hl_hpriv_put(struct hl_fpriv *hpriv);
 
 void goya_set_asic_funcs(struct hl_device *hdev);
 
drivers/misc/habanalabs/habanalabs_drv.c +44 -2
index 79545003b7c2..0646da83eb53 100644
@@ -77,6 +77,7 @@ int hl_device_open(struct inode *inode, struct file *filp)
 {
      struct hl_device *hdev;
      struct hl_fpriv *hpriv;
+     int rc;
 
      mutex_lock(&hl_devs_idr_lock);
      hdev = idr_find(&hl_devs_idr, iminor(inode));
@@ -88,9 +89,33 @@ int hl_device_open(struct inode *inode, struct file *filp)
              return -ENXIO;
      }
 
+     mutex_lock(&hdev->device_open);
+
+     if (hdev->disabled) {
+             dev_err_ratelimited(hdev->dev,
+                     "Can't open %s because it is disabled\n",
+                     dev_name(hdev->dev));
+             mutex_unlock(&hdev->device_open);
+             return -EPERM;
+     }
+
+     if (hdev->user_ctx) {
+             dev_info_ratelimited(hdev->dev,
+                     "Device %s is already attached to application\n",
+                     dev_name(hdev->dev));
+             mutex_unlock(&hdev->device_open);
+             return -EBUSY;
+     }
+
+     atomic_inc(&hdev->fd_open_cnt);
+
+     mutex_unlock(&hdev->device_open);
+
      hpriv = kzalloc(sizeof(*hpriv), GFP_KERNEL);
-     if (!hpriv)
-             return -ENOMEM;
+     if (!hpriv) {
+             rc = -ENOMEM;
+             goto close_device;
+     }
 
      hpriv->hdev = hdev;
      filp->private_data = hpriv;
@@ -98,9 +123,26 @@ int hl_device_open(struct inode *inode, struct file *filp)
      kref_init(&hpriv->refcount);
      nonseekable_open(inode, filp);
 
+     hl_ctx_mgr_init(&hpriv->ctx_mgr);
+
+     rc = hl_ctx_create(hdev, hpriv);
+     if (rc) {
+             dev_err(hdev->dev, "Failed to open FD (CTX fail)\n");
+             goto out_err;
+     }
+
      hpriv->taskpid = find_get_pid(current->pid);
 
      return 0;
+
+out_err:
+     filp->private_data = NULL;
+     hl_ctx_mgr_fini(hpriv->hdev, &hpriv->ctx_mgr);
+     kfree(hpriv);
+
+close_device:
+     atomic_dec(&hdev->fd_open_cnt);
+     return rc;
 }
 
Quoted 9 lines
Quoted 4 lines
drivers/misc/habanalabs/habanalabs_drv.c +0 -1
 /**
--

2.17.1

--
Sincerely yours,
Mike.

Fixed, thanks.
Oded

#87 lore raw

PATCH v2 1/5 drivers/accel: Introduce subsystem

In reply to Olof Johansson

We're starting to see more of these kind of devices, the current upcoming wave will likely be around machine learning and inference engines. A few drivers have been added to drivers/misc for this, but it's timely to make it into a separate group of drivers/subsystem, to make it easier to find them, and to encourage collaboration between contributors.

Over time, we expect to build shared frameworks that the drivers will make use of, but how that framework needs to look like to fill the needs is still unclear, and the best way to gain that knowledge is to give the disparate implementations a shared location.

There has been some controversy around expectations for userspace stacks being open. The clear preference is to see that happen, and any driver and platform stack that is delivered like that will be given preferential treatment, and at some point in the future it might become the requirement. Until then, the bare minimum we need is an open low-level userspace such that the driver and HW interfaces can be exercised if someone is modifying the driver, even if the full details of the workload are not always available.

Bootstrapping this with myself and Greg as maintainers (since the current drivers will be moving out of drivers/misc). Looking forward to expanding that group over time.

Cc Greg Kroah-Hartman <[email protected]>

---

v2:
I had missed a git add of the Documentation/ piece, which is the most important piece of this anyway. Sigh.

 Documentation/accelerators/README.rst | 42 +++++++++++++++++++++++++++++++++++
 MAINTAINERS                           |  8 +++++++
 drivers/Kconfig                       |  2 ++
 drivers/Makefile                      |  1 +
 drivers/accel/Kconfig                 | 16 +++++++++++++
 drivers/accel/Makefile                |  5 +++++
 6 files changed, 74 insertions(+)
 create mode 100644 Documentation/accelerators/README.rst
 create mode 100644 drivers/accel/Kconfig
 create mode 100644 drivers/accel/Makefile
Documentation/accelerators/README.rst new file +42 -0
new file mode 100644
index 0000000000000..79049ff99e93e
@@ -0,0 +1,42 @@
+.. _readme:
+
+Hardware offload accelerator subsystem
+======================================
+
+This is a brief overview of the subsystem (grouping) of hardware
+accelerators kept under drivers/accel
+
+Types of hardware supported
+---------------------------
+
+  The general types of hardware supported are hardware devices that has
+  general interactions of sending commands and buffers to the hardware,
+  returning completions and possible filled buffers back, together
+  with the usual driver pieces around hardware control, setup, error
+  handling, etc.
+
+  Drivers that fit into other subsystems are expected to be merged
+  there, and use the appropriate userspace interfaces of said functional
+  areas. We don't expect to see drivers for network, storage, graphics
+  and similar hardware implemented by drivers here.
+
+Expectations for contributions
+------------------------------
+
+ - Platforms and hardware that has fully open stacks, from Firmware to
+   Userspace, are always going to be given preferential treatment. These
+   platforms give the best insight for behavior and interaction of all
+   layers, including ability to improve implementation across the stack
+   over time.
+
+ - If a platform is partially proprietary, it is still expected that the
+   portions that interact the driver can be shared in a form that allows
+   for exercising the hardware/driver and evolution of the interface over
+   time. This could be separated into a shared library and test/sample
+   programs, for example.
+
+ - Over time, there is an expectation to converge drivers over to shared
+   frameworks and interfaces. Until then, the general rule is that no
+   more than one driver per vendor will be acceptable. For vendors that
+   aren't participating in the work towards shared frameworks over time,
+   we reserve the right to phase out support for the hardware.
MAINTAINERS +8 -0
index ddcdc29dfe1f6..8a9bbaf8f6e90 100644
@@ -7033,6 +7033,14 @@ W:	https://linuxtv.org
 S:	Supported
 F:	drivers/media/platform/sti/hva
 
+HW ACCELERATOR OFFLOAD SUBSYSTEM
+M:	Olof Johansson <[email protected]>
+M:	Greg Kroah-Hartman <[email protected]>
+L:	[email protected]
+S:	Supported
+F:	drivers/accel/
+F:	Documentation/accelerators/
+
 HWPOISON MEMORY FAILURE HANDLING
 M:	Naoya Horiguchi <[email protected]>
 L:	[email protected]
drivers/Kconfig +2 -0
index 4f9f99057ff85..3cc461f325569 100644
@@ -228,4 +228,6 @@ source "drivers/siox/Kconfig"
 
 source "drivers/slimbus/Kconfig"
 
+source "drivers/accel/Kconfig"
+
 endmenu
drivers/Makefile +1 -0
index 04da7876032cc..e4be06579cc5d 100644
@@ -186,3 +186,4 @@ obj-$(CONFIG_MULTIPLEXER)	+= mux/
 obj-$(CONFIG_UNISYS_VISORBUS)	+= visorbus/
 obj-$(CONFIG_SIOX)		+= siox/
 obj-$(CONFIG_GNSS)		+= gnss/
+obj-$(CONFIG_ACCEL)		+= accel/
drivers/accel/Kconfig new file +16 -0
new file mode 100644
index 0000000000000..13b36c0398895
@@ -0,0 +1,16 @@
+#
+# Drivers for hardware offload accelerators
+# See Documentation/accel/README.rst for more details
+#
+
+menuconfig ACCEL
+	bool "Hardware offload accelerator support"
+        help
+	  HW offload accelerators are used for high-bandwidth workloads
+	  where a higher-level kernel/userspace interface isn't suitable.
+
+if ACCEL
+
+comment "HW Accellerator drivers"
+
+endif
drivers/accel/Makefile new file +5 -0
new file mode 100644
index 0000000000000..343bbb8f45a14
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Makefile for accel devices
+#
+
Signature · 1 line
2.11.0
#25 lore raw

Re: [PATCH 05/15] habanalabs: add command buffer module

In reply to Mike Rapoport
Quoted 6 lines · Mike Rapoport
Quoted 2 lines · Oded Gabbay

This patch adds the CB module, which allows the user to create and destroy CBs and to map them to the user's process address-space.

Can you please spell "command buffer" at least first time it's mentioned?

fixed

Quoted 67 lines
Quoted 67 lines

A command buffer is a memory blocks that reside in DMA-able address-space and is physically contiguous so it can be accessed by the device without MMU translation. The command buffer memory is allocated using the coherent DMA API.

When creating a new CB, the IOCTL returns a handle of it, and the user-space process needs to use that handle to mmap the buffer to get a VA in the user's address-space.

Before destroying (freeing) a CB, the user must unmap the CB's VA using the CB handle.

Each CB has a reference counter, which tracks its usage in command submissions and also its mmaps (only a single mmap is allowed).

The driver maintains a pool of pre-allocated CBs in order to reduce latency during command submissions. In case the pool is empty, the driver will go to the slow-path of allocating a new CB, i.e. calling dma_alloc_coherent.

---
 drivers/misc/habanalabs/Makefile           |   3 +-
 drivers/misc/habanalabs/command_buffer.c   | 414 +++++++++++++++++++++
 drivers/misc/habanalabs/device.c           |  43 ++-
 drivers/misc/habanalabs/goya/goya.c        |  28 ++
 drivers/misc/habanalabs/habanalabs.h       |  95 ++++-
 drivers/misc/habanalabs/habanalabs_drv.c   |   2 +
 drivers/misc/habanalabs/habanalabs_ioctl.c | 102 +++++
 include/uapi/misc/habanalabs.h             |  62 +++
 8 files changed, 746 insertions(+), 3 deletions(-)
 create mode 100644 drivers/misc/habanalabs/command_buffer.c
 create mode 100644 drivers/misc/habanalabs/habanalabs_ioctl.c
 create mode 100644 include/uapi/misc/habanalabs.h
drivers/misc/habanalabs/Makefile +2 -1
index 3ffbadc2ca01..2530c9b78ca4 100644
@@ -4,7 +4,8 @@
 
 obj-m        := habanalabs.o
 
-habanalabs-y := habanalabs_drv.o device.o context.o asid.o
+habanalabs-y := habanalabs_drv.o device.o context.o asid.o habanalabs_ioctl.o \
+             command_buffer.o
 
 include $(src)/goya/Makefile
 habanalabs-y += $(HL_GOYA_FILES)
drivers/misc/habanalabs/command_buffer.c new file +11 -0
new file mode 100644
index 000000000000..535ed6cc5bda
@@ -0,0 +1,414 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ */
+
+#include <uapi/misc/habanalabs.h>
+#include "habanalabs.h"
+
+#include <linux/dma-mapping.h>
Quoted 9 lines

drivers/misc/habanalabs/command_buffer.c line 16

Quoted 5 lines
drivers/misc/habanalabs/command_buffer.c new file +5 -0
+
+static void cb_fini(struct hl_device *hdev, struct hl_cb *cb)
+{
+     hdev->asic_funcs->dma_free_coherent(hdev, cb->size,
+                     (void *) cb->kernel_address, cb->bus_address);

As it seems, ASIC specific dma_free_coherent is a shortcut for a generic dma_free_coherent. Why not use it directly?

As I explained in a previous patch review, there is a different implementation when I'm working with a simulator.

Quoted 28 lines
Quoted 28 lines
drivers/misc/habanalabs/command_buffer.c new file +28 -0
+     kfree(cb);
+}
+
+static void cb_do_release(struct hl_device *hdev, struct hl_cb *cb)
+{
+     if (cb->is_pool) {
+             spin_lock(&hdev->cb_pool_lock);
+             list_add(&cb->pool_list, &hdev->cb_pool);
+             spin_unlock(&hdev->cb_pool_lock);
+     } else {
+             cb_fini(hdev, cb);
+     }
+}
+
+static void cb_release(struct kref *ref)
+{
+     struct hl_device *hdev;
+     struct hl_cb *cb;
+
+     cb = container_of(ref, struct hl_cb, refcount);
+     hdev = cb->hdev;
+
+     cb_do_release(hdev, cb);
+}
+
+static struct hl_cb *hl_cb_alloc(struct hl_device *hdev, u32 cb_size,
+                                     int ctx_id)
+{
Quoted 9 lines

drivers/misc/habanalabs/command_buffer.c line 49

Quoted 5 lines
drivers/misc/habanalabs/command_buffer.c new file +5 -0
+     struct hl_cb *cb;
+     void *p;
+
+     if (ctx_id == HL_KERNEL_ASID_ID)
+             cb = kzalloc(sizeof(*cb), GFP_ATOMIC);

The GFP_ATOMIC should be used when the caller cannot tolerate reclaim or sleep and it does not seem to be the case here.

Yes, I can see why this is misleading. The call of this function from latency-sensitive code comes in a much later patch (command submission).
In short, due to H/W limitations, I must copy the CB of the user to a kernel allocated CB (in case of an external queue) and this must be done during command submission. Hence the GFP_ATOMIC flag in all memory allocations in this function.
I will add a comment in this patch explaining this.

btw, we solved this problem in future ASICs.

Quoted 11 lines

drivers/misc/habanalabs/command_buffer.c line 58

Quoted 9 lines
drivers/misc/habanalabs/command_buffer.c new file +9 -0
+     else
+             cb = kzalloc(sizeof(*cb), GFP_KERNEL);
+
+     if (!cb)
+             return NULL;
+
+     if (ctx_id == HL_KERNEL_ASID_ID)
+             p = hdev->asic_funcs->dma_alloc_coherent(hdev, cb_size,
+                                             &cb->bus_address, GFP_ATOMIC);

GFP_KERNEL?

Same explanation as above.

Quoted 45 lines
Quoted 45 lines
drivers/misc/habanalabs/command_buffer.c new file +44 -0
+     else
+             p = hdev->asic_funcs->dma_alloc_coherent(hdev, cb_size,
+                                             &cb->bus_address,
+                                             GFP_USER | __GFP_ZERO);
+     if (!p) {
+             dev_err(hdev->dev,
+                     "failed to allocate %d of dma memory for CB\n",
+                     cb_size);
+             kfree(cb);
+             return NULL;
+     }
+
+     cb->kernel_address = (u64) p;
+     cb->size = cb_size;
+
+     return cb;
+}
+
+int hl_cb_create(struct hl_device *hdev, struct hl_cb_mgr *mgr,
+                     u32 cb_size, u64 *handle, int ctx_id)
+{
+     struct hl_cb *cb;
+     bool alloc_new_cb = true;
+     int rc;
+
+     if (hdev->disabled) {
+             dev_warn_ratelimited(hdev->dev,
+                     "Device is disabled !!! Can't create new CBs\n");
+             rc = -EBUSY;
+             goto out_err;
+     }
+
+     /* Minimum allocation must be PAGE SIZE */
+     if (cb_size < PAGE_SIZE)
+             cb_size = PAGE_SIZE;
+
+     if (ctx_id == HL_KERNEL_ASID_ID &&
+                     cb_size <= hdev->asic_prop.cb_pool_cb_size) {
+
+             spin_lock(&hdev->cb_pool_lock);
+             if (!list_empty(&hdev->cb_pool)) {
+                     cb = list_first_entry(&hdev->cb_pool, typeof(*cb),
+                                     pool_list);
+                     list_del(&cb->pool_list);
Quoted 8 lines

drivers/misc/habanalabs/command_buffer.c line 107

Quoted 5 lines
drivers/misc/habanalabs/command_buffer.c new file +5 -0
+                     spin_unlock(&hdev->cb_pool_lock);
+                     alloc_new_cb = false;
+             } else {
+                     spin_unlock(&hdev->cb_pool_lock);
+                     dev_warn_once(hdev->dev, "CB pool is empty\n");

Isn't it going to be a false alarm when you allocate the cb for the first time?

Why ?
The cb_pool list holds a list of available CBs. See hl_cb_pool_init()
- it adds newly allocated CBs to this pool list.

if (!list_empty(&hdev->cb_pool)) { - this checks whether the
pool is not empty so we can take an available CB from it. If the list is empty (hence the pool is empty), we print the warning.

Quoted 11 lines
Quoted 11 lines
drivers/misc/habanalabs/command_buffer.c new file +10 -0
+             }
+     }
+
+     if (alloc_new_cb) {
+             cb = hl_cb_alloc(hdev, cb_size, ctx_id);
+             if (!cb) {
+                     rc = -ENOMEM;
+                     goto out_err;
+             }
+     }
Quoted 8 lines

drivers/misc/habanalabs/command_buffer.c line 123

Quoted 6 lines
drivers/misc/habanalabs/command_buffer.c new file +6 -0
+
+     cb->hdev = hdev;
+     cb->ctx_id = ctx_id;
+
+     spin_lock(&mgr->cb_lock);
+     rc = idr_alloc(&mgr->cb_handles, cb, 1, 0, GFP_ATOMIC);

It seems the ID will remain dangling if the cb is reused.

I'm not sure what you mean by this comment. Reused by whom ? in how fashion it is reused ?

Quoted 116 lines
Quoted 116 lines
drivers/misc/habanalabs/command_buffer.c new file +115 -0
+     spin_unlock(&mgr->cb_lock);
+
+     if (rc < 0) {
+             dev_err(hdev->dev, "Failed to allocate IDR for a new CB\n");
+             goto release_cb;
+     }
+
+     cb->id = rc;
+
+     kref_init(&cb->refcount);
+     spin_lock_init(&cb->lock);
+
+     /*
+      * idr is 32-bit so we can safely OR it with a mask that is above
+      * 32 bit
+      */
+     *handle = cb->id | HL_MMAP_CB_MASK;
+     *handle <<= PAGE_SHIFT;
+
+     return 0;
+
+release_cb:
+     cb_do_release(hdev, cb);
+out_err:
+     *handle = 0;
+
+     return rc;
+}
+
+int hl_cb_destroy(struct hl_device *hdev, struct hl_cb_mgr *mgr, u64 cb_handle)
+{
+     struct hl_cb *cb;
+     u32 handle;
+     int rc = 0;
+
+     /*
+      * handle was given to user to do mmap, I need to shift it back to
+      * how the idr module gave it to me
+      */
+     cb_handle >>= PAGE_SHIFT;
+     handle = (u32) cb_handle;
+
+     spin_lock(&mgr->cb_lock);
+
+     cb = idr_find(&mgr->cb_handles, handle);
+     if (cb) {
+             idr_remove(&mgr->cb_handles, handle);
+             spin_unlock(&mgr->cb_lock);
+             kref_put(&cb->refcount, cb_release);
+     } else {
+             spin_unlock(&mgr->cb_lock);
+             dev_err(hdev->dev,
+                     "CB destroy failed, no match to handle 0x%x\n", handle);
+             rc = -EINVAL;
+     }
+
+     return rc;
+}
+
+int hl_cb_ioctl(struct hl_fpriv *hpriv, void *data)
+{
+     union hl_cb_args *args = data;
+     struct hl_device *hdev = hpriv->hdev;
+     u64 handle;
+     int rc;
+
+     switch (args->in.op) {
+     case HL_CB_OP_CREATE:
+             rc = hl_cb_create(hdev, &hpriv->cb_mgr, args->in.cb_size,
+                                     &handle, hpriv->ctx->asid);
+             memset(args, 0, sizeof(*args));
+             args->out.cb_handle = handle;
+             break;
+     case HL_CB_OP_DESTROY:
+             rc = hl_cb_destroy(hdev, &hpriv->cb_mgr,
+                                     args->in.cb_handle);
+             memset(args, 0, sizeof(*args));
+             break;
+     default:
+             rc = -EINVAL;
+             break;
+     }
+
+     return rc;
+}
+
+static void cb_vm_close(struct vm_area_struct *vma)
+{
+     struct hl_cb *cb = (struct hl_cb *) vma->vm_private_data;
+
+     hl_cb_put(cb);
+
+     spin_lock(&cb->lock);
+     cb->mmap = false;
+     cb->vm_start = 0;
+     cb->vm_end = 0;
+     spin_unlock(&cb->lock);
+
+     vma->vm_private_data = NULL;
+}
+
+static const struct vm_operations_struct cb_vm_ops = {
+     .close = cb_vm_close
+};
+
+int hl_cb_mmap(struct hl_fpriv *hpriv, struct vm_area_struct *vma)
+{
+     struct hl_device *hdev = hpriv->hdev;
+     struct hl_cb *cb;
+     phys_addr_t address;
+     u32 handle;
+     int rc;
+
+     handle = vma->vm_pgoff;
+
Quoted 9 lines

drivers/misc/habanalabs/command_buffer.c line 244

Quoted 6 lines
drivers/misc/habanalabs/command_buffer.c new file +6 -0
+     /* reference was taken here */
+     cb = hl_cb_get(hdev, &hpriv->cb_mgr, handle);
+     if (!cb) {
+             dev_err(hdev->dev,
+                     "CB mmap failed, no match to handle %d\n", handle);
+             goto err_out;

why no simply return -EINVAL?

fixed

Quoted 583 lines
Quoted 570 lines
drivers/misc/habanalabs/command_buffer.c new file +170 -0
+     }
+
+     /* Validation check */
+     if (vma->vm_end - vma->vm_start != cb->size) {
+             dev_err(hdev->dev,
+                     "CB mmap failed, mmap size 0x%lx != 0x%x cb size\n",
+                     vma->vm_end - vma->vm_start, cb->size);
+             goto put_cb;
+     }
+
+     spin_lock(&cb->lock);
+
+     if (cb->mmap) {
+             dev_err(hdev->dev,
+                     "CB mmap failed, CB already mmaped to user\n");
+             goto release_lock;
+     }
+
+     cb->mmap = true;
+
+     spin_unlock(&cb->lock);
+
+     vma->vm_ops = &cb_vm_ops;
+
+     /*
+      * Note: We're transferring the cb reference to
+      * vma->vm_private_data here.
+      */
+
+     vma->vm_private_data = cb;
+
+     /* Calculate address for CB */
+     address = virt_to_phys((void *) cb->kernel_address);
+
+     rc = hdev->asic_funcs->cb_mmap(hdev, vma, cb->kernel_address,
+                                     address, cb->size);
+
+     if (rc) {
+             spin_lock(&cb->lock);
+             cb->mmap = false;
+             goto release_lock;
+     }
+
+     cb->vm_start = vma->vm_start;
+     cb->vm_end = vma->vm_end;
+
+     return 0;
+
+release_lock:
+     spin_unlock(&cb->lock);
+put_cb:
+     hl_cb_put(cb);
+err_out:
+     return -EINVAL;
+}
+
+struct hl_cb *hl_cb_get(struct hl_device *hdev, struct hl_cb_mgr *mgr,
+                     u32 handle)
+{
+     struct hl_cb *cb;
+
+     spin_lock(&mgr->cb_lock);
+     cb = idr_find(&mgr->cb_handles, handle);
+
+     if (!cb) {
+             spin_unlock(&mgr->cb_lock);
+             dev_warn(hdev->dev,
+                     "CB get failed, no match to handle %d\n", handle);
+             return NULL;
+     }
+
+     kref_get(&cb->refcount);
+
+     spin_unlock(&mgr->cb_lock);
+
+     return cb;
+
+}
+
+void hl_cb_put(struct hl_cb *cb)
+{
+     kref_put(&cb->refcount, cb_release);
+}
+
+void hl_cb_mgr_init(struct hl_cb_mgr *mgr)
+{
+     spin_lock_init(&mgr->cb_lock);
+     idr_init(&mgr->cb_handles);
+}
+
+void hl_cb_mgr_fini(struct hl_device *hdev, struct hl_cb_mgr *mgr)
+{
+     struct hl_cb *cb;
+     struct idr *idp;
+     u32 id;
+
+     idp = &mgr->cb_handles;
+
+     idr_for_each_entry(idp, cb, id) {
+             if (kref_put(&cb->refcount, cb_release) != 1)
+                     dev_err(hdev->dev,
+                             "CB %d for CTX ID %d is still alive\n",
+                             id, cb->ctx_id);
+     }
+
+     idr_destroy(&mgr->cb_handles);
+}
+
+struct hl_cb *hl_cb_kernel_create(struct hl_device *hdev, u32 cb_size)
+{
+     u64 cb_handle;
+     struct hl_cb *cb;
+     int rc;
+
+     rc = hl_cb_create(hdev, &hdev->kernel_cb_mgr, cb_size, &cb_handle,
+                     HL_KERNEL_ASID_ID);
+     if (rc) {
+             dev_err(hdev->dev, "Failed to allocate CB for KMD %d\n", rc);
+             return NULL;
+     }
+
+     cb_handle >>= PAGE_SHIFT;
+     cb = hl_cb_get(hdev, &hdev->kernel_cb_mgr, (u32) cb_handle);
+     /* hl_cb_get should never fail here so use kernel WARN */
+     WARN(!cb, "Kernel CB handle invalid 0x%x\n", (u32) cb_handle);
+     if (!cb)
+             goto destroy_cb;
+
+     return cb;
+
+destroy_cb:
+     hl_cb_destroy(hdev, &hdev->kernel_cb_mgr, cb_handle << PAGE_SHIFT);
+
+     return NULL;
+}
+
+int hl_cb_pool_init(struct hl_device *hdev)
+{
+     struct hl_cb *cb;
+     int i;
+
+     INIT_LIST_HEAD(&hdev->cb_pool);
+     spin_lock_init(&hdev->cb_pool_lock);
+
+     for (i = 0 ; i < hdev->asic_prop.cb_pool_cb_cnt ; i++) {
+             cb = hl_cb_alloc(hdev, hdev->asic_prop.cb_pool_cb_size,
+                             HL_KERNEL_ASID_ID);
+             if (cb) {
+                     cb->is_pool = true;
+                     list_add(&cb->pool_list, &hdev->cb_pool);
+             } else {
+                     hl_cb_pool_fini(hdev);
+                     return -ENOMEM;
+             }
+     }
+
+     return 0;
+}
+
+int hl_cb_pool_fini(struct hl_device *hdev)
+{
+     struct hl_cb *cb, *tmp;
+
+     list_for_each_entry_safe(cb, tmp, &hdev->cb_pool, pool_list) {
+             list_del(&cb->pool_list);
+             cb_fini(hdev, cb);
+     }
+
+     return 0;
+}
drivers/misc/habanalabs/device.c +42 -1
index 84ce9fcb52da..0bd86a7d34db 100644
@@ -53,6 +53,7 @@ static int hl_device_release(struct inode *inode, struct file *filp)
 {
      struct hl_fpriv *hpriv = filp->private_data;
 
+     hl_cb_mgr_fini(hpriv->hdev, &hpriv->cb_mgr);
      hl_ctx_mgr_fini(hpriv->hdev, &hpriv->ctx_mgr);
 
      filp->private_data = NULL;
@@ -62,10 +63,34 @@ static int hl_device_release(struct inode *inode, struct file *filp)
      return 0;
 }
 
+/**
+ * hl_mmap - mmap function for habanalabs device
+ *
+ * @*filp: pointer to file structure
+ * @*vma: pointer to vm_area_struct of the process
+ *
+ * Called when process does an mmap on habanalabs device. Call the device's mmap
+ * function at the end of the common code.
+ */
+static int hl_mmap(struct file *filp, struct vm_area_struct *vma)
+{
+     struct hl_fpriv *hpriv = filp->private_data;
+
+     if ((vma->vm_pgoff & HL_MMAP_CB_MASK) == HL_MMAP_CB_MASK) {
+             vma->vm_pgoff ^= HL_MMAP_CB_MASK;
+             return hl_cb_mmap(hpriv, vma);
+     }
+
+     return hpriv->hdev->asic_funcs->mmap(hpriv, vma);
+}
+
 static const struct file_operations hl_ops = {
      .owner = THIS_MODULE,
      .open = hl_device_open,
-     .release = hl_device_release
+     .release = hl_device_release,
+     .mmap = hl_mmap,
+     .unlocked_ioctl = hl_ioctl,
+     .compat_ioctl = hl_ioctl
 };
 
 /**
@@ -145,6 +170,8 @@ static int device_early_init(struct hl_device *hdev)
      if (rc)
              goto early_fini;
 
+     hl_cb_mgr_init(&hdev->kernel_cb_mgr);
+
      mutex_init(&hdev->device_open);
      atomic_set(&hdev->fd_open_cnt, 0);
 
@@ -166,6 +193,8 @@ static int device_early_init(struct hl_device *hdev)
 static void device_early_fini(struct hl_device *hdev)
 {
 
+     hl_cb_mgr_fini(hdev, &hdev->kernel_cb_mgr);
+
      hl_asid_fini(hdev);
 
      if (hdev->asic_funcs->early_fini)
@@ -280,11 +309,21 @@ int hl_device_init(struct hl_device *hdev, struct class *hclass)
              goto free_ctx;
      }
 
+     rc = hl_cb_pool_init(hdev);
+     if (rc) {
+             dev_err(hdev->dev, "failed to initialize CB pool\n");
+             goto release_ctx;
+     }
+
      dev_notice(hdev->dev,
              "Successfully added device to habanalabs driver\n");
 
      return 0;
 
+release_ctx:
+     if (hl_ctx_put(hdev->kernel_ctx) != 1)
+             dev_err(hdev->dev,
+                     "kernel ctx is still alive on initialization failure\n");
 free_ctx:
      kfree(hdev->kernel_ctx);
 sw_fini:
@@ -321,6 +360,8 @@ void hl_device_fini(struct hl_device *hdev)
      /* Mark device as disabled */
      hdev->disabled = true;
 
+     hl_cb_pool_fini(hdev);
+
      /* Release kernel context */
      if ((hdev->kernel_ctx) && (hl_ctx_put(hdev->kernel_ctx) != 1))
              dev_err(hdev->dev, "kernel ctx is still alive\n");
drivers/misc/habanalabs/goya/goya.c +28 -0
index b2952296b890..341ac085af82 100644
@@ -92,6 +92,9 @@
 
 #define GOYA_MAX_INITIATORS          20
 
+#define GOYA_CB_POOL_CB_CNT          512
+#define GOYA_CB_POOL_CB_SIZE         0x20000         /* 128KB */
+
 static void goya_get_fixed_properties(struct hl_device *hdev)
 {
      struct asic_fixed_properties *prop = &hdev->asic_prop;
@@ -119,6 +122,8 @@ static void goya_get_fixed_properties(struct hl_device *hdev)
      prop->tpc_enabled_mask = TPC_ENABLED_MASK;
 
      prop->high_pll = PLL_HIGH_DEFAULT;
+     prop->cb_pool_cb_cnt = GOYA_CB_POOL_CB_CNT;
+     prop->cb_pool_cb_size = GOYA_CB_POOL_CB_SIZE;
 }
 
 /**
@@ -598,6 +603,27 @@ int goya_resume(struct hl_device *hdev)
      return 0;
 }
 
+int goya_mmap(struct hl_fpriv *hpriv, struct vm_area_struct *vma)
+{
+     return -EINVAL;
+}
+
+int goya_cb_mmap(struct hl_device *hdev, struct vm_area_struct *vma,
+             u64 kaddress, phys_addr_t paddress, u32 size)
+{
+     int rc;
+
+     vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP |
+                     VM_DONTCOPY | VM_NORESERVE;
+
+     rc = remap_pfn_range(vma, vma->vm_start, paddress >> PAGE_SHIFT,
+                             size, vma->vm_page_prot);
+     if (rc)
+             dev_err(hdev->dev, "remap_pfn_range error %d", rc);
+
+     return rc;
+}
+
 void *goya_dma_alloc_coherent(struct hl_device *hdev, size_t size,
                                      dma_addr_t *dma_handle, gfp_t flags)
 {
@@ -617,6 +643,8 @@ static const struct hl_asic_funcs goya_funcs = {
      .sw_fini = goya_sw_fini,
      .suspend = goya_suspend,
      .resume = goya_resume,
+     .mmap = goya_mmap,
+     .cb_mmap = goya_cb_mmap,
      .dma_alloc_coherent = goya_dma_alloc_coherent,
      .dma_free_coherent = goya_dma_free_coherent,
 };
drivers/misc/habanalabs/habanalabs.h +94 -1
index d003a6af2131..6ad476df65b0 100644
@@ -21,10 +21,12 @@
 
 #define HL_NAME                              "habanalabs"
 
+#define HL_MMAP_CB_MASK                      (0x8000000000000000ull >> PAGE_SHIFT)
+
 #define HL_MAX_QUEUES                        128
 
 struct hl_device;
-
+struct hl_fpriv;
 
 
 
@@ -53,6 +55,8 @@ struct hl_device;
  * @max_asid: maximum number of open contexts (ASIDs).
  * @completion_queues_count: number of completion queues.
  * @high_pll: high PLL frequency used by the device.
+ * @cb_pool_cb_cnt: number of CBs in the CB pool.
+ * @cb_pool_cb_size: size of each CB in the CB pool.
  * @tpc_enabled_mask: which TPCs are enabled.
  */
 struct asic_fixed_properties {
@@ -73,11 +77,68 @@ struct asic_fixed_properties {
      u32                     sram_size;
      u32                     max_asid;
      u32                     high_pll;
+     u32                     cb_pool_cb_cnt;
+     u32                     cb_pool_cb_size;
      u8                      completion_queues_count;
      u8                      tpc_enabled_mask;
 };
 
 
+
+
+
+
+/*
+ * Command Buffers
+ */
+
+/**
+ * struct hl_cb_mgr - describes a Command Buffer Manager.
+ * @cb_lock: protects cb_handles.
+ * @cb_handles: an idr to hold all command buffer handles.
+ */
+struct hl_cb_mgr {
+     spinlock_t              cb_lock;
+     struct idr              cb_handles; /* protected by cb_lock */
+};
+
+/**
+ * struct hl_cb - describes a Command Buffer.
+ * @refcount: reference counter for usage of the CB.
+ * @hdev: pointer to device this CB belongs to.
+ * @lock: spinlock to protect mmap/cs flows.
+ * @pool_list: node in pool list of command buffers.
+ * @kernel_address: Holds the CB's kernel virtual address.
+ * @bus_address: Holds the CB's DMA address.
+ * @vm_start: Holds the CB's user start virtual address (when mmaped).
+ * @vm_end: Holds the CB's user end virtual address (when mmaped).
+ * @size: holds the CB's size.
+ * @id: the CB's ID.
+ * @ctx_id: holds the ID of the owner's context.
+ * @mmap: true if the CB is currently mmaped to user.
+ * @is_pool: true if CB was acquired from the pool, false otherwise.
+ */
+struct hl_cb {
+     struct kref             refcount;
+     struct hl_device        *hdev;
+     spinlock_t              lock;
+     struct list_head        pool_list;
+     u64                     kernel_address;
+     dma_addr_t              bus_address;
+     u64                     vm_start;
+     u64                     vm_end;
+     u32                     size;
+     u32                     id;
+     u32                     ctx_id;
+     u8                      mmap;
+     u8                      is_pool;
+};
+
+
+
+
+
+
 #define HL_QUEUE_LENGTH                      256
 
 
@@ -109,6 +170,8 @@ enum hl_asic_type {
  * @sw_fini: tears down driver state, does not configure H/W.
  * @suspend: handles IP specific H/W or SW changes for suspend.
  * @resume: handles IP specific H/W or SW changes for resume.
+ * @mmap: mmap function, does nothing.
+ * @cb_mmap: maps a CB.
  * @dma_alloc_coherent: DMA allocate coherent memory.
  * @dma_free_coherent: free DMA allocation.
  */
@@ -119,6 +182,9 @@ struct hl_asic_funcs {
      int (*sw_fini)(struct hl_device *hdev);
      int (*suspend)(struct hl_device *hdev);
      int (*resume)(struct hl_device *hdev);
+     int (*mmap)(struct hl_fpriv *hpriv, struct vm_area_struct *vma);
+     int (*cb_mmap)(struct hl_device *hdev, struct vm_area_struct *vma,
+                     u64 kaddress, phys_addr_t paddress, u32 size);
      void* (*dma_alloc_coherent)(struct hl_device *hdev, size_t size,
                                      dma_addr_t *dma_handle, gfp_t flag);
      void (*dma_free_coherent)(struct hl_device *hdev, size_t size,
@@ -175,6 +241,7 @@ struct hl_ctx_mgr {
  * @taskpid: current process ID.
  * @ctx: current executing context.
  * @ctx_mgr: context manager to handle multiple context for this FD.
+ * @cb_mgr: command buffer manager to handle multiple buffers for this FD.
  * @refcount: number of related contexts.
  */
 struct hl_fpriv {
@@ -183,6 +250,7 @@ struct hl_fpriv {
      struct pid              *taskpid;
      struct hl_ctx           *ctx; /* TODO: remove for multiple ctx */
      struct hl_ctx_mgr       ctx_mgr;
+     struct hl_cb_mgr        cb_mgr;
      struct kref             refcount;
 };
 
@@ -239,6 +307,7 @@ void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
  * @asic_name: ASIC specific nmae.
  * @asic_type: ASIC specific type.
  * @kernel_ctx: KMD context structure.
+ * @kernel_cb_mgr: command buffer manager for creating/destroying/handling CGs.
  * @dma_pool: DMA pool for small allocations.
  * @cpu_accessible_dma_mem: KMD <-> ArmCP shared memory CPU address.
  * @cpu_accessible_dma_address: KMD <-> ArmCP shared memory DMA address.
@@ -249,6 +318,8 @@ void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
  * @asic_prop: ASIC specific immutable properties.
  * @asic_funcs: ASIC specific functions.
  * @asic_specific: ASIC specific information to use only from ASIC files.
+ * @cb_pool: list of preallocated CBs.
+ * @cb_pool_lock: protects the CB pool.
  * @user_ctx: current user context executing.
  * @fd_open_cnt: number of open context executing.
  * @major: habanalabs KMD major.
@@ -264,6 +335,7 @@ struct hl_device {
      char                            asic_name[16];
      enum hl_asic_type               asic_type;
      struct hl_ctx                   *kernel_ctx;
+     struct hl_cb_mgr                kernel_cb_mgr;
      struct dma_pool                 *dma_pool;
      void                            *cpu_accessible_dma_mem;
      dma_addr_t                      cpu_accessible_dma_address;
@@ -275,6 +347,10 @@ struct hl_device {
      struct asic_fixed_properties    asic_prop;
      const struct hl_asic_funcs      *asic_funcs;
      void                            *asic_specific;
+
+     struct list_head                cb_pool;
+     spinlock_t                      cb_pool_lock;
+
      /* TODO: The following fields should be moved for multi-context */
      struct hl_ctx                   *user_ctx;
      atomic_t                        fd_open_cnt;
@@ -345,6 +421,23 @@ int hl_device_resume(struct hl_device *hdev);
 void hl_hpriv_get(struct hl_fpriv *hpriv);
 void hl_hpriv_put(struct hl_fpriv *hpriv);
 
+int hl_cb_create(struct hl_device *hdev, struct hl_cb_mgr *mgr, u32 cb_size,
+             u64 *handle, int ctx_id);
+int hl_cb_destroy(struct hl_device *hdev, struct hl_cb_mgr *mgr, u64 cb_handle);
+int hl_cb_mmap(struct hl_fpriv *hpriv, struct vm_area_struct *vma);
+struct hl_cb *hl_cb_get(struct hl_device *hdev,      struct hl_cb_mgr *mgr,
+                     u32 handle);
+void hl_cb_put(struct hl_cb *cb);
+void hl_cb_mgr_init(struct hl_cb_mgr *mgr);
+void hl_cb_mgr_fini(struct hl_device *hdev, struct hl_cb_mgr *mgr);
+struct hl_cb *hl_cb_kernel_create(struct hl_device *hdev, u32 cb_size);
+int hl_cb_pool_init(struct hl_device *hdev);
+int hl_cb_pool_fini(struct hl_device *hdev);
+
 void goya_set_asic_funcs(struct hl_device *hdev);
 
+/* IOCTLs */
+long hl_ioctl(struct file *filep, unsigned int cmd, unsigned long arg);
+int hl_cb_ioctl(struct hl_fpriv *hpriv, void *data);
+
 #endif /* HABANALABSP_H_ */
drivers/misc/habanalabs/habanalabs_drv.c +2 -0
index 0646da83eb53..5c312dd3aa50 100644
@@ -123,6 +123,7 @@ int hl_device_open(struct inode *inode, struct file *filp)
      kref_init(&hpriv->refcount);
      nonseekable_open(inode, filp);
 
+     hl_cb_mgr_init(&hpriv->cb_mgr);
      hl_ctx_mgr_init(&hpriv->ctx_mgr);
 
      rc = hl_ctx_create(hdev, hpriv);
@@ -138,6 +139,7 @@ int hl_device_open(struct inode *inode, struct file *filp)
 out_err:
      filp->private_data = NULL;
      hl_ctx_mgr_fini(hpriv->hdev, &hpriv->ctx_mgr);
+     hl_cb_mgr_fini(hpriv->hdev, &hpriv->cb_mgr);
      kfree(hpriv);
 
 close_device:
drivers/misc/habanalabs/habanalabs_ioctl.c new file +26 -0
new file mode 100644
index 000000000000..fa2287569e0e
@@ -0,0 +1,102 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ */
+
+#include <uapi/misc/habanalabs.h>
+#include "habanalabs.h"
+
+#include <linux/fs.h>
+#include <linux/uaccess.h>
+#include <linux/cred.h>
+
+#define HL_IOCTL_DEF(ioctl, _func) \
+     [_IOC_NR(ioctl)] = {.cmd = ioctl, .func = _func}
+
+static const struct hl_ioctl_desc hl_ioctls[] = {
+     HL_IOCTL_DEF(HL_IOCTL_CB, hl_cb_ioctl)
+};
+
+#define HL_CORE_IOCTL_COUNT  ARRAY_SIZE(hl_ioctls)
+
+long hl_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
+{
+     struct hl_fpriv *hpriv = filep->private_data;

drivers/misc/habanalabs/habanalabs_ioctl.c line 36

Quoted 10 lines
drivers/misc/habanalabs/habanalabs_ioctl.c new file +10 -0
+     struct hl_device *hdev = hpriv->hdev;
+     hl_ioctl_t *func;
+     const struct hl_ioctl_desc *ioctl = NULL;
+     unsigned int nr = _IOC_NR(cmd);
+     char stack_kdata[128];
+     char *kdata = NULL;
+     unsigned int usize, asize;
+     int retcode = -EINVAL;
+
+     if (nr >= HL_CORE_IOCTL_COUNT)

nr > HL_CORE_IOCTL_COUNT, isn't it?

Quoted 3 lines

drivers/misc/habanalabs/habanalabs_ioctl.c line 37

Quoted 1 line
drivers/misc/habanalabs/habanalabs_ioctl.c new file +1 -0
+             goto err_i1;

err_i1 is not very meaningfull. Maybe invalid_ioctl?

Changed to out_err as this is used from other places in this function

Quoted 5 lines

drivers/misc/habanalabs/habanalabs_ioctl.c line 39

Quoted 3 lines
drivers/misc/habanalabs/habanalabs_ioctl.c new file +2 -0
+
+     if ((nr >= HL_COMMAND_START) && (nr < HL_COMMAND_END)) {

The HL_COMMAND_{START,END} do not seem to be defined.

They are defined in uapi/misc/habanalabs.h

Quoted 3 lines

Besides, this check seem to be overlapped with

if (nr > HL_CORE_IOCTL_COUNT)

Correct, removed the first if (HL_CORE_IOCTL_COUNT)

Quoted 30 lines
Quoted 30 lines
drivers/misc/habanalabs/habanalabs_ioctl.c new file +29 -0
+             u32 hl_size;
+
+             ioctl = &hl_ioctls[nr];
+
+             hl_size = _IOC_SIZE(ioctl->cmd);
+             usize = asize = _IOC_SIZE(cmd);
+             if (hl_size > asize)
+                     asize = hl_size;
+
+             cmd = ioctl->cmd;
+     } else {
+             goto err_i1;
+     }
+
+     /* Do not trust userspace, use our own definition */
+     func = ioctl->func;
+
+     if (unlikely(!func)) {
+             dev_dbg(hdev->dev, "no function\n");
+             retcode = -EINVAL;
+             goto err_i1;
+     }
+
+     if (cmd & (IOC_IN | IOC_OUT)) {
+             if (asize <= sizeof(stack_kdata)) {
+                     kdata = stack_kdata;
+             } else {
+                     kdata = kmalloc(asize, GFP_KERNEL);
+                     if (!kdata) {
Quoted 8 lines

drivers/misc/habanalabs/habanalabs_ioctl.c line 74

Quoted 6 lines
drivers/misc/habanalabs/habanalabs_ioctl.c new file +6 -0
+                             retcode = -ENOMEM;
+                             goto err_i1;
+                     }
+             }
+             if (asize > usize)
+                     memset(kdata + usize, 0, asize - usize);

Just init stack_kdata to 0 and use kzalloc instead of malloc.

fixed

Quoted 18 lines
Quoted 18 lines
drivers/misc/habanalabs/habanalabs_ioctl.c new file +17 -0
+     }
+
+     if (cmd & IOC_IN) {
+             if (copy_from_user(kdata, (void __user *)arg, usize)) {
+                     retcode = -EFAULT;
+                     goto err_i1;
+             }
+     } else if (cmd & IOC_OUT) {
+             memset(kdata, 0, usize);
+     }
+
+     retcode = func(hpriv, kdata);
+
+     if (cmd & IOC_OUT)
+             if (copy_to_user((void __user *)arg, kdata, usize))
+                     retcode = -EFAULT;
+
Quoted 8 lines

drivers/misc/habanalabs/habanalabs_ioctl.c line 96

Quoted 5 lines
drivers/misc/habanalabs/habanalabs_ioctl.c new file +5 -0
+err_i1:
+     if (!ioctl)
+             dev_dbg(hdev->dev,
+                     "invalid ioctl: pid=%d, cmd=0x%02x, nr=0x%02x\n",
+                       task_pid_nr(current), cmd, nr);

I think this can move right after the 'nr' sanity check and there you can simple return -EINVAL after dev_dbg().

But you reach here from many different places and I want to print the ioctl information for each case.
I think the real mistake here is if(!ioctl). This should actually be if (ioctl) because only then it is relevant for most of the places in this function that has an error.
And I'll add a dedicated print if the nr is not correct.

Quoted 83 lines
Quoted 76 lines
drivers/misc/habanalabs/habanalabs_ioctl.c new file +6 -0
+
+     if (kdata != stack_kdata)
+             kfree(kdata);
+
+     return retcode;
+}
include/uapi/misc/habanalabs.h new file +62 -1
new file mode 100644
index 000000000000..b3f9213d4709
@@ -0,0 +1,62 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note
+ *
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ *
+ * Author: Oded Gabbay <[email protected]>
+ *
+ */
+
+#ifndef HABANALABS_H_
+#define HABANALABS_H_
+
+#include <linux/types.h>
+#include <linux/ioctl.h>
+
+/* Opcode to create a new command buffer */
+#define HL_CB_OP_CREATE              0
+/* Opcode to destroy previously created command buffer */
+#define HL_CB_OP_DESTROY     1
+
+struct hl_cb_in {
+     /* Handle of CB or 0 if we want to create one */
+     __u64 cb_handle;
+     /* HL_CB_OP_* */
+     __u32 op;
+     /* Size of CB. Minimum requested size must be PAGE_SIZE */
+     __u32 cb_size;
+     /* Context ID - Currently not in use */
+     __u32 ctx_id;
+     __u32 pad;
+};
+
+struct hl_cb_out {
+     /* Handle of CB */
+     __u64 cb_handle;
+};
+
+union hl_cb_args {
+     struct hl_cb_in in;
+     struct hl_cb_out out;
+};
+
+/*
+ * Command Buffer
+ * - Request a Command Buffer
+ * - Destroy a Command Buffer
+ *
+ * The command buffers are memory blocks that reside in DMA-able address
+ * space and are physically contiguous so they can be accessed by the device
+ * directly. They are allocated using the coherent DMA API.
+ *
+ * When creating a new CB, the IOCTL returns a handle of it, and the user-space
+ * process needs to use that handle to mmap the buffer so it can access them.
+ *
+ */
+#define HL_IOCTL_CB          \
+             _IOWR('H', 0x02, union hl_cb_args)
+
+#define HL_COMMAND_START     0x02
+#define HL_COMMAND_END               0x03
+
+#endif /* HABANALABS_H_ */
--
Quoted 2 lines

2.17.1

--
Sincerely yours,
Mike.

#91 lore raw

Re: [PATCH 1/5] drivers/accel: Introduce subsystem

In reply to Olof Johansson
Quoted 21 lines · Olof Johansson

We're starting to see more of these kind of devices, the current upcoming wave will likely be around machine learning and inference engines. A few drivers have been added to drivers/misc for this, but it's timely to make it into a separate group of drivers/subsystem, to make it easier to find them, and to encourage collaboration between contributors.

Over time, we expect to build shared frameworks that the drivers will make use of, but how that framework needs to look like to fill the needs is still unclear, and the best way to gain that knowledge is to give the disparate implementations a shared location.

There has been some controversy around expectations for userspace stacks being open. The clear preference is to see that happen, and any driver and platform stack that is delivered like that will be given preferential treatment, and at some point in the future it might become the requirement. Until then, the bare minimum we need is an open low-level userspace such that the driver and HW interfaces can be exercised if someone is modifying the driver, even if the full details of the workload are not always available.

Quoted 6 lines

Bootstrapping this with myself and Greg as maintainers (since the current drivers will be moving out of drivers/misc). Looking forward to expanding that group over time.

Cc Greg Kroah-Hartman <[email protected]>

I spent a bit of time reading the proposed drivers, mostly just their uapi (habanalabs and ocxl&cxl), and there's really no technical difference I think between an accelaration driver sitting in drivers/gpu and an accelaration driver sitting in drivers/accel. Except:

- drivers/gpu already has common interfaces for the things you'll probably want to standardize (buffer sharing, syncronization primitives, scheduler - right now we're working on figuring out some common tracepoints).

- Maybe even more important, drivers/gpu has the lessons learned in its codebase about what not to standardize between drivers (everything else, you'll regret it, we've been there).

- drivers/gpu is the subsystem with 20 years of experience writing tiny shim drivers in the kernel for high performance accelarators that need a pretty huge stack in userspace to make them do anything useful. 20 years ago all the rage to make faster was graphics, now it's AI. Looks exactly the same from a kernel pov - command buffers, gigabytes of DMA and a security/long term support nightmare.

- drivers/gpu requires open source. The real thing, not some demo that does a few DMA operations.

And now we have drivers/accel and someone gets to explain to nvidia (or arm or whatever) how their exact same drivers (and well run engineering orgs really only invent command submission once) can be merged when they say it's for a TPU, and will get rejected when they say it's for a GPU. Or someone gets to explain to TPU+GPU vendors why their driver is not cool (because we'd end up with two), while their startup-competition only doing a TPU is totally fine and merged into upstream. Or we just stuff all the kernel drivers for blobby userspace into drivers/accel and otherwise ignore each another.

I guess that last option would at least somewhat help me, since I wont ever have to explain anymore why we're the radical commies on dri-devel :-)

Anyway, only reason I replied here again is because I accidentally started a private thread (well was too lazy to download the mbox to properly reply), and that's not good either. But I don't think anyone's going to change their opinion here, I think this reply is just for the record.

Cheers, Daniel

PS: Seen that there's a v2 of this now with Documentation, hasn't reached my inbox (yet). I don't think that one clarifies any of the tricky questions between drivers/gpu and drivers/accel, so figured won't harm if I leave the reply on v1.

Quoted 85 lines
---
 MAINTAINERS            |  8 ++++++++
 drivers/Kconfig        |  2 ++
 drivers/Makefile       |  1 +
 drivers/accel/Kconfig  | 16 ++++++++++++++++
 drivers/accel/Makefile |  5 +++++
 5 files changed, 32 insertions(+)
 create mode 100644 drivers/accel/Kconfig
 create mode 100644 drivers/accel/Makefile
MAINTAINERS +8 -0
index ddcdc29dfe1f6..8a9bbaf8f6e90 100644
@@ -7033,6 +7033,14 @@ W:	https://linuxtv.org
 S:	Supported
 F:	drivers/media/platform/sti/hva
 
+HW ACCELERATOR OFFLOAD SUBSYSTEM
+M:	Olof Johansson <[email protected]>
+M:	Greg Kroah-Hartman <[email protected]>
+L:	[email protected]
+S:	Supported
+F:	drivers/accel/
+F:	Documentation/accelerators/
+
 HWPOISON MEMORY FAILURE HANDLING
 M:	Naoya Horiguchi <[email protected]>
 L:	[email protected]
drivers/Kconfig +2 -0
index 4f9f99057ff85..3cc461f325569 100644
@@ -228,4 +228,6 @@ source "drivers/siox/Kconfig"
 
 source "drivers/slimbus/Kconfig"
 
+source "drivers/accel/Kconfig"
+
 endmenu
drivers/Makefile +1 -0
index 04da7876032cc..e4be06579cc5d 100644
@@ -186,3 +186,4 @@ obj-$(CONFIG_MULTIPLEXER)	+= mux/
 obj-$(CONFIG_UNISYS_VISORBUS)	+= visorbus/
 obj-$(CONFIG_SIOX)		+= siox/
 obj-$(CONFIG_GNSS)		+= gnss/
+obj-$(CONFIG_ACCEL)		+= accel/
drivers/accel/Kconfig new file +16 -0
new file mode 100644
index 0000000000000..13b36c0398895
@@ -0,0 +1,16 @@
+#
+# Drivers for hardware offload accelerators
+# See Documentation/accel/README.rst for more details
+#
+
+menuconfig ACCEL
+	bool "Hardware offload accelerator support"
+        help
+	  HW offload accelerators are used for high-bandwidth workloads
+	  where a higher-level kernel/userspace interface isn't suitable.
+
+if ACCEL
+
+comment "HW Accellerator drivers"
+
+endif
drivers/accel/Makefile new file +5 -0
new file mode 100644
index 0000000000000..343bbb8f45a14
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Makefile for accel devices
+#
+
Signature · 1 line
2.11.0
Signature · 3 lines
Daniel Vetter
Software Engineer, Intel Corporation
http://blog.ffwll.ch
#97 lore raw

Re: [PATCH 5/5] drivers/accel: ocxl: Move non-uapi include files

In reply to Olof Johansson
Quoted 1 line · Olof Johansson

Separate to expose the edits vs pure moves.

Ugh, putting the uapi files in misc/ was a mistake, sorry I never caught that before, my fault :(

greg k-h

#102 lore raw
In reply to Olof Johansson
Quoted 30 lines · Olof Johansson
Quoted 21 lines · Greg Kroah-Hartman
Quoted 15 lines · Olof Johansson

On Thu, Jan 24, 2019 at 11:37 PM Greg Kroah-Hartman

Quoted 5 lines

As for what directory the code should live in, I suggested "misc" as there was no other universal location, and I hate to see new subsystems be created with only one driver, as that's pretty sad. But it's just a name/location, I have no dog in the fight, so I really don't care where it ends up in the tree, just as long as it gets merged somewhere :)

I'm usually one to push back against new subsystems too, especially when I see a framework proposal with just one driver. In this case, given that we all know more vendors will come along, I think it makes sense to take the discussion and establish structure now. This should give some clarity to those who are out there that we haven't seen yet, and give them a chance to prepare for things such as the low-level userspace pieces mentioned above.

Quoted 3 lines

So I think setting this up now is the right thing to do, we know there will be more material here and having a common aggregation of it makes sense.

Quoted 6 lines

Ok, how about:
drivers/deep_thought/

as a first proposal.

Let the bikeshedding begin! :)

Quoted 7 lines

My original proposal upthread was driver/accel. I'm not sure whether Dave and/or anyone else wants to participate to start though, I hope they will at least join in once things are heading in the direction they want.

I'll post patches with the proposed moves and documentation of expectations shortly, hopefully to collect acks.

Patches all look good to me, I can merge them through my char-misc tree once we get the acks from the relevant driver maintainers.

thanks,

greg k-h

maintainer
#9 lore raw

Re: [PATCH 01/15] habanalabs: add skeleton driver

In reply to Oded Gabbay

drivers/misc/habanalabs/include/habanalabs_device_if.h

Quoted 5 lines · Oded Gabbay
drivers/misc/habanalabs/include/habanalabs_device_if.h new file +0 -0
new file mode 100644
index 000000000000..9dbb7077eabd

Since this is a apparently a user space ABI, the file should be in include/uapi/linux/,
not in the driver directory.

drivers/misc/habanalabs/include/habanalabs_device_if.h line 123

Quoted 12 lines
drivers/misc/habanalabs/include/habanalabs_device_if.h new file +12 -0
+/* must be aligned to 4 bytes */
+struct armcp_info {
+       struct armcp_sensor sensors[ARMCP_MAX_SENSORS];
+       __u8 kernel_version[VERSION_MAX_LEN];
+       __u32 reserved[3];
+       __u32 cpld_version;
+       __u32 infineon_version;
+       __u8 fuse_version[VERSION_MAX_LEN];
+       __u8 thermal_version[VERSION_MAX_LEN];
+       __u8 armcp_version[VERSION_MAX_LEN];
+       __u64 dram_size;
+};

The compiler will align this to 8 bytes on most architectures, and add another padding field before dram_size. Better remove the 'reserved' fields, or make them an even number.

Arnd

#10 lore raw

Re: [PATCH 01/15] habanalabs: add skeleton driver

Quoted 12 lines · Arnd Bergmann

drivers/misc/habanalabs/include/habanalabs_device_if.h

Quoted 5 lines · Oded Gabbay
drivers/misc/habanalabs/include/habanalabs_device_if.h new file +0 -0
new file mode 100644
index 000000000000..9dbb7077eabd

Since this is a apparently a user space ABI, the file should be in include/uapi/linux/,
not in the driver directory.

This is not a user space ABI. This is the ABI between the driver and the F/W.

Quoted 17 lines

drivers/misc/habanalabs/include/habanalabs_device_if.h line 123

Quoted 13 lines
drivers/misc/habanalabs/include/habanalabs_device_if.h new file +12 -0
+/* must be aligned to 4 bytes */
+struct armcp_info {
+       struct armcp_sensor sensors[ARMCP_MAX_SENSORS];
+       __u8 kernel_version[VERSION_MAX_LEN];
+       __u32 reserved[3];
+       __u32 cpld_version;
+       __u32 infineon_version;
+       __u8 fuse_version[VERSION_MAX_LEN];
+       __u8 thermal_version[VERSION_MAX_LEN];
+       __u8 armcp_version[VERSION_MAX_LEN];
+       __u64 dram_size;
+};

The compiler will align this to 8 bytes on most architectures, and add another padding field before dram_size. Better remove the 'reserved' fields, or make them an even number.

I can't do that, because those fields were once used by the F/W and if I will change the order here, or add/remove those fields then it will break compatibility with old F/W.

Thanks,
Oded

Quoted 2 lines

Arnd

reviewer
#88 lore raw

Re: [PATCH v2 1/5] drivers/accel: Introduce subsystem

In reply to Olof Johansson

Hi,

Please see a few corrections inline...

Quoted 20 lines · Olof Johansson
 Documentation/accelerators/README.rst | 42 +++++++++++++++++++++++++++++++++++
 MAINTAINERS                           |  8 +++++++
 drivers/Kconfig                       |  2 ++
 drivers/Makefile                      |  1 +
 drivers/accel/Kconfig                 | 16 +++++++++++++
 drivers/accel/Makefile                |  5 +++++
 6 files changed, 74 insertions(+)
 create mode 100644 Documentation/accelerators/README.rst
 create mode 100644 drivers/accel/Kconfig
 create mode 100644 drivers/accel/Makefile
Documentation/accelerators/README.rst new file +2 -0
new file mode 100644
index 0000000000000..79049ff99e93e
@@ -0,0 +1,42 @@
+.. _readme:
+

Documentation/accelerators/README.rst line 12

Quoted 10 lines
Documentation/accelerators/README.rst new file +10 -0
+Hardware offload accelerator subsystem
+======================================
+
+This is a brief overview of the subsystem (grouping) of hardware
+accelerators kept under drivers/accel
+
+Types of hardware supported
+---------------------------
+
+  The general types of hardware supported are hardware devices that has

that have

Quoted 4 lines
Documentation/accelerators/README.rst new file +4 -0
+  general interactions of sending commands and buffers to the hardware,
+  returning completions and possible filled buffers back, together
+  with the usual driver pieces around hardware control, setup, error
+  handling, etc.

Documentation/accelerators/README.rst line 26

Quoted 10 lines
Documentation/accelerators/README.rst new file +10 -0
+
+  Drivers that fit into other subsystems are expected to be merged
+  there, and use the appropriate userspace interfaces of said functional
+  areas. We don't expect to see drivers for network, storage, graphics
+  and similar hardware implemented by drivers here.
+
+Expectations for contributions
+------------------------------
+
+ - Platforms and hardware that has fully open stacks, from Firmware to

that have

Documentation/accelerators/README.rst line 33

Quoted 7 lines
Documentation/accelerators/README.rst new file +7 -0
+   Userspace, are always going to be given preferential treatment. These
+   platforms give the best insight for behavior and interaction of all
+   layers, including ability to improve implementation across the stack
+   over time.
+
+ - If a platform is partially proprietary, it is still expected that the
+   portions that interact the driver can be shared in a form that allows

that interact with the driver

Quoted 16 lines
Documentation/accelerators/README.rst new file +9 -0
+   for exercising the hardware/driver and evolution of the interface over
+   time. This could be separated into a shared library and test/sample
+   programs, for example.
+
+ - Over time, there is an expectation to converge drivers over to shared
+   frameworks and interfaces. Until then, the general rule is that no
+   more than one driver per vendor will be acceptable. For vendors that
+   aren't participating in the work towards shared frameworks over time,
+   we reserve the right to phase out support for the hardware.
drivers/accel/Kconfig new file +0 -0
new file mode 100644
index 0000000000000..13b36c0398895

drivers/accel/Kconfig line 8

Quoted 8 lines
drivers/accel/Kconfig new file +8 -0
@@ -0,0 +1,16 @@
+#
+# Drivers for hardware offload accelerators
+# See Documentation/accel/README.rst for more details
+#
+
+menuconfig ACCEL
+	bool "Hardware offload accelerator support"
+        help

Use tab instead of spaces above.

Quoted 8 lines
drivers/accel/Kconfig new file +8 -0
+	  HW offload accelerators are used for high-bandwidth workloads
+	  where a higher-level kernel/userspace interface isn't suitable.
+
+if ACCEL
+
+comment "HW Accellerator drivers"
+
+endif
Signature · 1 line
~Randy
maintainer
#98 lore raw

Re: [PATCH/RFC 0/5] HW accel subsystem

In reply to Olof Johansson
Quoted 6 lines · Olof Johansson

Per discussion in on the Habana Labs driver submission
(https://lore.kernel.org/lkml/[email protected]/),
there seems to be time to create a separate subsystem for hw accellerators instead of letting them proliferate around the tree (and/or in misc).

Quoted 6 lines

There's difference in opinion on how stringent the requirements are for a fully open stack for these kind of drivers. I've documented the middle road approach in the first patch (requiring some sort of open low-level userspace for the kernel interaction, and a way to use/test it).

Comments and suggestions for better approaches are definitely welcome.

We probably want to move drivers/misc/mic together with the others as well. We could even move arch/powerpc/platforms/cell/spu*/ for another historic example.

Arnd

maintainer
#11 lore raw

Re: [PATCH 01/15] habanalabs: add skeleton driver

In reply to Oded Gabbay
Quoted 15 lines · Oded Gabbay
Quoted 12 lines · Arnd Bergmann

drivers/misc/habanalabs/include/habanalabs_device_if.h

Quoted 5 lines · Oded Gabbay
drivers/misc/habanalabs/include/habanalabs_device_if.h new file +0 -0
new file mode 100644
index 000000000000..9dbb7077eabd

Since this is a apparently a user space ABI, the file should be in include/uapi/linux/,
not in the driver directory.

Quoted 1 line

This is not a user space ABI. This is the ABI between the driver and the F/W.

Ah, I see. In that case, you should get rid of all the bitfields and make the struct members all __le32/__le64/... to make it work on big-endian kernels.

Quoted 17 lines
Quoted 17 lines

drivers/misc/habanalabs/include/habanalabs_device_if.h line 123

Quoted 13 lines
drivers/misc/habanalabs/include/habanalabs_device_if.h new file +12 -0
+/* must be aligned to 4 bytes */
+struct armcp_info {
+       struct armcp_sensor sensors[ARMCP_MAX_SENSORS];
+       __u8 kernel_version[VERSION_MAX_LEN];
+       __u32 reserved[3];
+       __u32 cpld_version;
+       __u32 infineon_version;
+       __u8 fuse_version[VERSION_MAX_LEN];
+       __u8 thermal_version[VERSION_MAX_LEN];
+       __u8 armcp_version[VERSION_MAX_LEN];
+       __u64 dram_size;
+};

The compiler will align this to 8 bytes on most architectures, and add another padding field before dram_size. Better remove the 'reserved' fields, or make them an even number.

Quoted 3 lines

I can't do that, because those fields were once used by the F/W and if I will change the order here, or add/remove those fields then it will break compatibility with old F/W.

Ok, I see. Then you should add an explicit padding field and fix the comment to make the structure match the actual interface.

Arnd

#12 lore raw

Re: [PATCH 01/15] habanalabs: add skeleton driver

Quoted 17 lines · Arnd Bergmann
Quoted 15 lines · Oded Gabbay
Quoted 12 lines · Arnd Bergmann

drivers/misc/habanalabs/include/habanalabs_device_if.h

Quoted 5 lines · Oded Gabbay
drivers/misc/habanalabs/include/habanalabs_device_if.h new file +0 -0
new file mode 100644
index 000000000000..9dbb7077eabd

Since this is a apparently a user space ABI, the file should be in include/uapi/linux/,
not in the driver directory.

Quoted 5 lines
Quoted 1 line

This is not a user space ABI. This is the ABI between the driver and the F/W.

Ah, I see. In that case, you should get rid of all the bitfields and make the struct members all __le32/__le64/... to make it work on big-endian kernels.

I really don't want to start converting bitfields and structures to use __le32/64.
As I wrote in one of the previous reviews, we don't support big-endian architecture (what's left after POWER moved to support little endian ?). We actually do run on POWER9 but with ppc64le architecture In any case, our software stack is so big that this minor change in the driver won't have any impact on the overall ability to run something on our H/W

Quoted 17 lines
Quoted 17 lines
Quoted 17 lines

drivers/misc/habanalabs/include/habanalabs_device_if.h line 123

Quoted 13 lines
drivers/misc/habanalabs/include/habanalabs_device_if.h new file +12 -0
+/* must be aligned to 4 bytes */
+struct armcp_info {
+       struct armcp_sensor sensors[ARMCP_MAX_SENSORS];
+       __u8 kernel_version[VERSION_MAX_LEN];
+       __u32 reserved[3];
+       __u32 cpld_version;
+       __u32 infineon_version;
+       __u8 fuse_version[VERSION_MAX_LEN];
+       __u8 thermal_version[VERSION_MAX_LEN];
+       __u8 armcp_version[VERSION_MAX_LEN];
+       __u64 dram_size;
+};

The compiler will align this to 8 bytes on most architectures, and add another padding field before dram_size. Better remove the 'reserved' fields, or make them an even number.

Quoted 8 lines
Quoted 3 lines

I can't do that, because those fields were once used by the F/W and if I will change the order here, or add/remove those fields then it will break compatibility with old F/W.

Ok, I see. Then you should add an explicit padding field and fix the comment to make the structure match the actual interface.

Arnd

Understood, will be fixed.
Thanks,
Oded

#89 lore raw

Re: [PATCH v2 1/5] drivers/accel: Introduce subsystem

In reply to Olof Johansson

[+ linuxppc-dev, because cxl/ocxl are handled through powerpc - please cc on future versions of this series]

Quoted 25 lines · Olof Johansson

We're starting to see more of these kind of devices, the current upcoming wave will likely be around machine learning and inference engines. A few drivers have been added to drivers/misc for this, but it's timely to make it into a separate group of drivers/subsystem, to make it easier to find them, and to encourage collaboration between contributors.

Over time, we expect to build shared frameworks that the drivers will make use of, but how that framework needs to look like to fill the needs is still unclear, and the best way to gain that knowledge is to give the disparate implementations a shared location.

There has been some controversy around expectations for userspace stacks being open. The clear preference is to see that happen, and any driver and platform stack that is delivered like that will be given preferential treatment, and at some point in the future it might become the requirement. Until then, the bare minimum we need is an open low-level userspace such that the driver and HW interfaces can be exercised if someone is modifying the driver, even if the full details of the workload are not always available.

Bootstrapping this with myself and Greg as maintainers (since the current drivers will be moving out of drivers/misc). Looking forward to expanding that group over time.

[snip]

Quoted 31 lines
Documentation/accelerators/README.rst new file +31 -0
+
+Hardware offload accelerator subsystem
+======================================
+
+This is a brief overview of the subsystem (grouping) of hardware
+accelerators kept under drivers/accel
+
+Types of hardware supported
+---------------------------
+
+  The general types of hardware supported are hardware devices that has
+  general interactions of sending commands and buffers to the hardware,
+  returning completions and possible filled buffers back, together
+  with the usual driver pieces around hardware control, setup, error
+  handling, etc.
+
+  Drivers that fit into other subsystems are expected to be merged
+  there, and use the appropriate userspace interfaces of said functional
+  areas. We don't expect to see drivers for network, storage, graphics
+  and similar hardware implemented by drivers here.
+
+Expectations for contributions
+------------------------------
+
+ - Platforms and hardware that has fully open stacks, from Firmware to
+   Userspace, are always going to be given preferential treatment. These
+   platforms give the best insight for behavior and interaction of all
+   layers, including ability to improve implementation across the stack
+   over time.
+
+ - If a platform is partially proprietary, it is still expected that the

Documentation/accelerators/README.rst line 42

Quoted 10 lines
Documentation/accelerators/README.rst new file +10 -0
+   portions that interact the driver can be shared in a form that allows
+   for exercising the hardware/driver and evolution of the interface over
+   time. This could be separated into a shared library and test/sample
+   programs, for example.
+
+ - Over time, there is an expectation to converge drivers over to shared
+   frameworks and interfaces. Until then, the general rule is that no
+   more than one driver per vendor will be acceptable. For vendors that
+   aren't participating in the work towards shared frameworks over time,
+   we reserve the right to phase out support for the hardware.

How exactly do generic drivers for interconnect protocols, such as cxl/ocxl, fit in here?

cxl and ocxl are not drivers for a specific device, they are generic drivers which can be used with any device implementing the CAPI or OpenCAPI protocol respectively - many of which will be FPGA boards flashed with customer-designed accelerator cores for specific workloads, some will be accelerators using ASICs or using FPGA images supplied by vendors, some will be driven from userspace, others using the cxl/ocxl kernel API, etc.

Signature · 2 lines
Andrew Donnellan              OzLabs, ADL Canberra
[email protected]  IBM Australia Limited
#18 lore raw

Re: [PATCH 03/15] habanalabs: add basic Goya support

In reply to Oded Gabbay
Quoted 22 lines · Oded Gabbay
Quoted 21 lines · Mike Rapoport
Quoted 19 lines · Oded Gabbay

This patch adds a basic support for the Goya device. The code initializes the device's PCI controller and PCI bars. It also initializes various S/W structures and adds some basic helper functions.

---
 drivers/misc/habanalabs/Makefile            |   5 +-
 drivers/misc/habanalabs/device.c            |  71 +++
 drivers/misc/habanalabs/goya/Makefile       |   3 +
 drivers/misc/habanalabs/goya/goya.c         | 633 ++++++++++++++++++++
 drivers/misc/habanalabs/goya/goyaP.h        | 125 ++++
 drivers/misc/habanalabs/habanalabs.h        | 131 ++++
 drivers/misc/habanalabs/habanalabs_drv.c    |   3 +
 drivers/misc/habanalabs/include/goya/goya.h | 115 ++++
 8 files changed, 1085 insertions(+), 1 deletion(-)
 create mode 100644 drivers/misc/habanalabs/goya/Makefile
 create mode 100644 drivers/misc/habanalabs/goya/goya.c
 create mode 100644 drivers/misc/habanalabs/goya/goyaP.h
 create mode 100644 drivers/misc/habanalabs/include/goya/goya.h

[ ... ]

Quoted 17 lines
Quoted 9 lines
Quoted 9 lines
drivers/misc/habanalabs/goya/goya.c new file +9 -0
+
+/**
+ * goya_sw_init - Goya software initialization code
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ */
+static int goya_sw_init(struct hl_device *hdev)
+{
Quoted 8 lines

drivers/misc/habanalabs/goya/goya.c line 501

Quoted 5 lines
drivers/misc/habanalabs/goya/goya.c new file +5 -0
+     struct goya_device *goya;
+     int rc;
+
+     /* Allocate device structure */
+     goya = kzalloc(sizeof(*goya), GFP_KERNEL);

Consider using devm_k[mz]alloc() for memory allocations throughout the driver. I didn't check all the spots where it can be applicable.

Quoted 5 lines

I honestly wasn't aware of that. We never used that in AMD drivers (which where I spent most of my kernel time).
I'll look into that offline but for now I don't really want to change into it blindly in all locations, unless there is some hard kernel rule for using that in drivers.

AFAIK, there's no such rule. It's just supposed to make driver developer/maintainer life easier ;-)

Quoted 17 lines
Quoted 17 lines
Quoted 17 lines
drivers/misc/habanalabs/goya/goya.c new file +16 -0
+     if (!goya)
+             return -ENOMEM;
+
+     /* according to goya_init_iatu */
+     goya->ddr_bar_cur_addr = DRAM_PHYS_BASE;
+     hdev->asic_specific = goya;
+
+     /* Create DMA pool for small allocations */
+     hdev->dma_pool = dma_pool_create(dev_name(hdev->dev),
+                     &hdev->pdev->dev, GOYA_DMA_POOL_BLK_SIZE, 8, 0);
+     if (!hdev->dma_pool) {
+             dev_err(hdev->dev, "failed to create DMA pool\n");
+             rc = -ENOMEM;
+             goto free_goya_device;
+     }
+

[ ... ]

Quoted 16 lines
Quoted 7 lines
Quoted 7 lines
drivers/misc/habanalabs/goya/goya.c new file +7 -0
+
+static const struct hl_asic_funcs goya_funcs = {
+     .early_init = goya_early_init,
+     .early_fini = goya_early_fini,
+     .sw_init = goya_sw_init,
+     .sw_fini = goya_sw_fini,
+     .suspend = goya_suspend,
Quoted 8 lines

drivers/misc/habanalabs/goya/goya.c line 621

Quoted 3 lines
drivers/misc/habanalabs/goya/goya.c new file +3 -0
+     .resume = goya_resume,
+     .dma_alloc_coherent = goya_dma_alloc_coherent,
+     .dma_free_coherent = goya_dma_free_coherent,

Is there any additional functionality that is planned in goya or gaudi in these two functions?
It seems like they are not really needed, at least at the moment and for sure that don't need to be part of ASIC ops.

Quoted 3 lines

So this relates to the simulator support, because there the implementation of these two functions is totally different as I don't have pci device.

Can you please add a comment about it here?

Signature · 2 lines
Sincerely yours,
Mike.
#26 lore raw

Re: [PATCH 05/15] habanalabs: add command buffer module

In reply to Oded Gabbay
Quoted 43 lines · Oded Gabbay
Quoted 6 lines · Mike Rapoport
Quoted 2 lines · Oded Gabbay

This patch adds the CB module, which allows the user to create and destroy CBs and to map them to the user's process address-space.

Can you please spell "command buffer" at least first time it's mentioned?

fixed

Quoted 35 lines
Quoted 35 lines

A command buffer is a memory blocks that reside in DMA-able address-space and is physically contiguous so it can be accessed by the device without MMU translation. The command buffer memory is allocated using the coherent DMA API.

When creating a new CB, the IOCTL returns a handle of it, and the user-space process needs to use that handle to mmap the buffer to get a VA in the user's address-space.

Before destroying (freeing) a CB, the user must unmap the CB's VA using the CB handle.

Each CB has a reference counter, which tracks its usage in command submissions and also its mmaps (only a single mmap is allowed).

The driver maintains a pool of pre-allocated CBs in order to reduce latency during command submissions. In case the pool is empty, the driver will go to the slow-path of allocating a new CB, i.e. calling dma_alloc_coherent.

---
 drivers/misc/habanalabs/Makefile           |   3 +-
 drivers/misc/habanalabs/command_buffer.c   | 414 +++++++++++++++++++++
 drivers/misc/habanalabs/device.c           |  43 ++-
 drivers/misc/habanalabs/goya/goya.c        |  28 ++
 drivers/misc/habanalabs/habanalabs.h       |  95 ++++-
 drivers/misc/habanalabs/habanalabs_drv.c   |   2 +
 drivers/misc/habanalabs/habanalabs_ioctl.c | 102 +++++
 include/uapi/misc/habanalabs.h             |  62 +++
 8 files changed, 746 insertions(+), 3 deletions(-)
 create mode 100644 drivers/misc/habanalabs/command_buffer.c
 create mode 100644 drivers/misc/habanalabs/habanalabs_ioctl.c
 create mode 100644 include/uapi/misc/habanalabs.h

[ ... ]

Quoted 34 lines
Quoted 26 lines
Quoted 26 lines
drivers/misc/habanalabs/command_buffer.c new file +26 -0
+int hl_cb_create(struct hl_device *hdev, struct hl_cb_mgr *mgr,
+                     u32 cb_size, u64 *handle, int ctx_id)
+{
+     struct hl_cb *cb;
+     bool alloc_new_cb = true;
+     int rc;
+
+     if (hdev->disabled) {
+             dev_warn_ratelimited(hdev->dev,
+                     "Device is disabled !!! Can't create new CBs\n");
+             rc = -EBUSY;
+             goto out_err;
+     }
+
+     /* Minimum allocation must be PAGE SIZE */
+     if (cb_size < PAGE_SIZE)
+             cb_size = PAGE_SIZE;
+
+     if (ctx_id == HL_KERNEL_ASID_ID &&
+                     cb_size <= hdev->asic_prop.cb_pool_cb_size) {
+
+             spin_lock(&hdev->cb_pool_lock);
+             if (!list_empty(&hdev->cb_pool)) {
+                     cb = list_first_entry(&hdev->cb_pool, typeof(*cb),
+                                     pool_list);
+                     list_del(&cb->pool_list);
Quoted 8 lines

drivers/misc/habanalabs/command_buffer.c line 107

Quoted 5 lines
drivers/misc/habanalabs/command_buffer.c new file +5 -0
+                     spin_unlock(&hdev->cb_pool_lock);
+                     alloc_new_cb = false;
+             } else {
+                     spin_unlock(&hdev->cb_pool_lock);
+                     dev_warn_once(hdev->dev, "CB pool is empty\n");

Isn't it going to be a false alarm when you allocate the cb for the first time?

Quoted 7 lines

Why ?
The cb_pool list holds a list of available CBs. See hl_cb_pool_init()
- it adds newly allocated CBs to this pool list.

if (!list_empty(&hdev->cb_pool)) { - this checks whether the
pool is not empty so we can take an available CB from it. If the list is empty (hence the pool is empty), we print the warning.

Sorry if it's too much nitpicking, but why the allocation of the first cb should be a warning? There's nothing wrong there... Maybe dev_dbg() instead?

Quoted 19 lines
Quoted 10 lines
Quoted 10 lines
drivers/misc/habanalabs/command_buffer.c new file +10 -0
+             }
+     }
+
+     if (alloc_new_cb) {
+             cb = hl_cb_alloc(hdev, cb_size, ctx_id);
+             if (!cb) {
+                     rc = -ENOMEM;
+                     goto out_err;
+             }
+     }
Quoted 8 lines

drivers/misc/habanalabs/command_buffer.c line 123

Quoted 6 lines
drivers/misc/habanalabs/command_buffer.c new file +6 -0
+
+     cb->hdev = hdev;
+     cb->ctx_id = ctx_id;
+
+     spin_lock(&mgr->cb_lock);
+     rc = idr_alloc(&mgr->cb_handles, cb, 1, 0, GFP_ATOMIC);

It seems the ID will remain dangling if the cb is reused.

Quoted 2 lines

I'm not sure what you mean by this comment. Reused by whom ? in how fashion it is reused ?

Sorry if I didn't explain it more clearly.
If the case the cb is reused, you anyway call idr_alloc() and overwrite the previous value of cb->id and it never gets idr_remove()'ed

Quoted 30 lines
Quoted 30 lines
Quoted 30 lines
drivers/misc/habanalabs/command_buffer.c new file +29 -0
+     spin_unlock(&mgr->cb_lock);
+
+     if (rc < 0) {
+             dev_err(hdev->dev, "Failed to allocate IDR for a new CB\n");
+             goto release_cb;
+     }
+
+     cb->id = rc;
+
+     kref_init(&cb->refcount);
+     spin_lock_init(&cb->lock);
+
+     /*
+      * idr is 32-bit so we can safely OR it with a mask that is above
+      * 32 bit
+      */
+     *handle = cb->id | HL_MMAP_CB_MASK;
+     *handle <<= PAGE_SHIFT;
+
+     return 0;
+
+release_cb:
+     cb_do_release(hdev, cb);
+out_err:
+     *handle = 0;
+
+     return rc;
+}
+
Signature · 2 lines
Sincerely yours,
Mike.
#42 lore raw

Re: [PATCH 10/15] habanalabs: add device reset support

In reply to Oded Gabbay
Quoted 58 lines · Oded Gabbay

This patch adds support for doing various on-the-fly reset of Goya.

The driver supports two types of resets:
1. soft-reset
2. hard-reset

Soft-reset is done when the device detects a timeout of a command submission that was given to the device. The soft-reset process only resets the engines that are relevant for the submission of compute jobs, i.e. the DMA channels, the TPCs and the MME. The purpose is to bring the device as fast as possible to a working state.

Hard-reset is done in several cases:
1. After soft-reset is done but the device is not responding
2. When fatal errors occur inside the device, e.g. ECC error
3. When the driver is removed

Hard-reset performs a reset of the entire chip except for the PCI controller and the PLLs. It is a much longer process then soft-reset but it helps to recover the device without the need to reboot the Host.

After hard-reset, the driver will restore the max power attribute and in case of manual power management, the frequencies that were set.

This patch also adds two entries to the sysfs, which allows the root user to initiate a soft or hard reset.

---
 drivers/misc/habanalabs/command_buffer.c  |  11 +-
 drivers/misc/habanalabs/device.c          | 308 +++++++++++++++++++++-
 drivers/misc/habanalabs/goya/goya.c       | 201 ++++++++++++++
 drivers/misc/habanalabs/goya/goya_hwmgr.c |  18 +-
 drivers/misc/habanalabs/habanalabs.h      |  35 +++
 drivers/misc/habanalabs/habanalabs_drv.c  |   9 +-
 drivers/misc/habanalabs/hwmon.c           |   4 +-
 drivers/misc/habanalabs/irq.c             |  31 +++
 drivers/misc/habanalabs/sysfs.c           | 120 ++++++++-
 9 files changed, 712 insertions(+), 25 deletions(-)
drivers/misc/habanalabs/command_buffer.c +3 -2
index 535ed6cc5bda..700c6da01188 100644
@@ -81,9 +81,10 @@ int hl_cb_create(struct hl_device *hdev, struct hl_cb_mgr *mgr,
 	bool alloc_new_cb = true;
 	int rc;
 
-	if (hdev->disabled) {
+	if ((hdev->disabled) || ((atomic_read(&hdev->in_reset)) &&
+					(ctx_id != HL_KERNEL_ASID_ID))) {
 		dev_warn_ratelimited(hdev->dev,
-			"Device is disabled !!! Can't create new CBs\n");
+			"Device is disabled or in reset !!! Can't create new CBs\n");
 		rc = -EBUSY;
 		goto out_err;
 	}

drivers/misc/habanalabs/command_buffer.c int hl_cb_ioctl(struct hl_fpriv *hpriv, void *data) · line 195

Quoted 8 lines
drivers/misc/habanalabs/command_buffer.c +5 -0
@@ -187,6 +188,12 @@ int hl_cb_ioctl(struct hl_fpriv *hpriv, void *data)
 	u64 handle;
 	int rc;
 
+	if (hdev->hard_reset_pending) {
+		dev_crit_ratelimited(hdev->dev,
+			"Device HARD reset pending !!! Please close FD\n");
+		return -ENODEV;
+	}

Probably this check should be done at the top-level ioctl()? And, what will happen if the devices performs hard reset, but the used keeps the file descriptor open?

Quoted 20 lines
drivers/misc/habanalabs/command_buffer.c +1 -0
+
 	switch (args->in.op) {
 	case HL_CB_OP_CREATE:
 		rc = hl_cb_create(hdev, &hpriv->cb_mgr, args->in.cb_size,
drivers/misc/habanalabs/device.c +1 -0
index ff7b610f18c4..00fde57ce823 100644
@@ -188,6 +188,7 @@ static int device_early_init(struct hl_device *hdev)
 
 	mutex_init(&hdev->device_open);
 	mutex_init(&hdev->send_cpu_message_lock);
+	atomic_set(&hdev->in_reset, 0);
 	atomic_set(&hdev->fd_open_cnt, 0);
 
 	return 0;
@@ -238,6 +239,27 @@ static void set_freq_to_low_job(struct work_struct *work)
 			usecs_to_jiffies(HL_PLL_LOW_JOB_FREQ_USEC));
 }
 

drivers/misc/habanalabs/device.c static void set_freq_to_low_job(struct work_struct *work) · line 251

Quoted 10 lines
drivers/misc/habanalabs/device.c +10 -0
+static void hl_device_heartbeat(struct work_struct *work)
+{
+	struct hl_device *hdev = container_of(work, struct hl_device,
+						work_heartbeat.work);
+
+	if ((hdev->disabled) || (atomic_read(&hdev->in_reset)))
+		goto reschedule;
+
+	if (!hdev->asic_funcs->send_heartbeat(hdev))
+		goto reschedule;

AFAIU, asic_funcs->send_heartbeat() it set once at init time. The work should not be scheduled it it's NULL, I suppose.

Quoted 56 lines
drivers/misc/habanalabs/device.c +35 -0
+
+	dev_err(hdev->dev, "Device heartbeat failed !!!\n");
+	hl_device_reset(hdev, true, false);
+
+	return;
+
+reschedule:
+	schedule_delayed_work(&hdev->work_heartbeat,
+			usecs_to_jiffies(HL_HEARTBEAT_PER_USEC));
+}
+
 /**
  * device_late_init - do late stuff initialization for the habanalabs device
  *
@@ -273,6 +295,12 @@ static int device_late_init(struct hl_device *hdev)
 	schedule_delayed_work(&hdev->work_freq,
 			usecs_to_jiffies(HL_PLL_LOW_JOB_FREQ_USEC));
 
+	if (hdev->heartbeat) {
+		INIT_DELAYED_WORK(&hdev->work_heartbeat, hl_device_heartbeat);
+		schedule_delayed_work(&hdev->work_heartbeat,
+				usecs_to_jiffies(HL_HEARTBEAT_PER_USEC));
+	}
+
 	hdev->late_init_done = true;
 
 	return 0;
@@ -290,6 +318,8 @@ static void device_late_fini(struct hl_device *hdev)
 		return;
 
 	cancel_delayed_work_sync(&hdev->work_freq);
+	if (hdev->heartbeat)
+		cancel_delayed_work_sync(&hdev->work_heartbeat);
 
 	if (hdev->asic_funcs->late_fini)
 		hdev->asic_funcs->late_fini(hdev);
@@ -397,6 +427,254 @@ int hl_device_resume(struct hl_device *hdev)
 	return 0;
 }
 
+static void hl_device_hard_reset_pending(struct work_struct *work)
+{
+	struct hl_device_reset_work *device_reset_work =
+		container_of(work, struct hl_device_reset_work, reset_work);
+	struct hl_device *hdev = device_reset_work->hdev;
+	u16 pending_cnt = HL_PENDING_RESET_PER_SEC;
+	struct task_struct *task = NULL;
+
+	/* Flush all processes that are inside hl_open */
+	mutex_lock(&hdev->device_open);
+
+	while ((atomic_read(&hdev->fd_open_cnt)) && (pending_cnt)) {
+
+		pending_cnt--;
+
+		dev_info(hdev->dev,

drivers/misc/habanalabs/device.c int hl_device_resume(struct hl_device *hdev) · line 455

Quoted 10 lines
drivers/misc/habanalabs/device.c +10 -0
+			"Can't HARD reset, waiting for user to close FD\n");
+		ssleep(1);
+	}
+
+	if (atomic_read(&hdev->fd_open_cnt)) {
+		task = get_pid_task(hdev->user_ctx->hpriv->taskpid,
+					PIDTYPE_PID);
+		if (task) {
+			dev_info(hdev->dev, "Killing user processes\n");
+			send_sig(SIGKILL, task, 1);

Shouldn't the user get a chance for cleanup?

Quoted 13 lines
drivers/misc/habanalabs/device.c +13 -0
+			msleep(100);
+
+			put_task_struct(task);
+		}
+	}
+
+	mutex_unlock(&hdev->device_open);
+
+	hl_device_reset(hdev, true, true);
+
+	kfree(device_reset_work);
+}
+

[ ... ]

Quoted 14 lines
drivers/misc/habanalabs/goya/goya_hwmgr.c +1 -1
index 866d1774b2e4..9482dbb2e03a 100644
@@ -38,7 +38,7 @@ static ssize_t mme_clk_show(struct device *dev, struct device_attribute *attr,
 	struct hl_device *hdev = dev_get_drvdata(dev);
 	long value;
 
-	if (hdev->disabled)
+	if ((hdev->disabled) || (atomic_read(&hdev->in_reset)))
 		return -ENODEV;
 
 	value = hl_get_frequency(hdev, MME_PLL, false);

drivers/misc/habanalabs/goya/goya_hwmgr.c static ssize_t mme_clk_store(struct device *dev, struct device_attribute *attr, · line 60

Quoted 5 lines
drivers/misc/habanalabs/goya/goya_hwmgr.c +1 -1
@@ -57,7 +57,7 @@ static ssize_t mme_clk_store(struct device *dev, struct device_attribute *attr,
 	int rc;
 	long value;
 
-	if (hdev->disabled) {
+	if ((hdev->disabled) || (atomic_read(&hdev->in_reset))) {

There are quite a few of those, maybe split this check to a helper function?

Quoted 21 lines
drivers/misc/habanalabs/goya/goya_hwmgr.c +2 -2
 		count = -ENODEV;
 		goto fail;
 	}
@@ -87,7 +87,7 @@ static ssize_t tpc_clk_show(struct device *dev, struct device_attribute *attr,
 	struct hl_device *hdev = dev_get_drvdata(dev);
 	long value;
 
-	if (hdev->disabled)
+	if ((hdev->disabled) || (atomic_read(&hdev->in_reset)))
 		return -ENODEV;
 
 	value = hl_get_frequency(hdev, TPC_PLL, false);
@@ -106,7 +106,7 @@ static ssize_t tpc_clk_store(struct device *dev, struct device_attribute *attr,
 	int rc;
 	long value;
 
-	if (hdev->disabled) {
+	if ((hdev->disabled) || (atomic_read(&hdev->in_reset))) {
 		count = -ENODEV;
 		goto fail;
 	}
Signature · 2 lines
Sincerely yours,
Mike.
maintainer
#13 lore raw

Re: [PATCH 01/15] habanalabs: add skeleton driver

In reply to Oded Gabbay
Quoted 23 lines · Oded Gabbay
Quoted 17 lines · Arnd Bergmann
Quoted 15 lines · Oded Gabbay
Quoted 12 lines · Arnd Bergmann

drivers/misc/habanalabs/include/habanalabs_device_if.h

Quoted 5 lines · Oded Gabbay
drivers/misc/habanalabs/include/habanalabs_device_if.h new file +0 -0
new file mode 100644
index 000000000000..9dbb7077eabd

Since this is a apparently a user space ABI, the file should be in include/uapi/linux/,
not in the driver directory.

Quoted 5 lines
Quoted 1 line

This is not a user space ABI. This is the ABI between the driver and the F/W.

Ah, I see. In that case, you should get rid of all the bitfields and make the struct members all __le32/__le64/... to make it work on big-endian kernels.

Quoted 8 lines

I really don't want to start converting bitfields and structures to use __le32/64.
As I wrote in one of the previous reviews, we don't support big-endian architecture (what's left after POWER moved to support little endian ?). We actually do run on POWER9 but with ppc64le architecture In any case, our software stack is so big that this minor change in the driver won't have any impact on the overall ability to run something on our H/W

You don't have to do anything at the moment to "convert" to use a specific endian, but you do have to always mark such variables that are in a specific endian that this is the format they are expected in.

Then, when you run a tool like sparse, you will be notified if you happen to be making any assumptions that might not be correct about those variables, and it's trivial to usually fix it up at that time.

hope this helps,

greg k-h

#45 lore raw

Re: [PATCH 11/15] habanalabs: add command submission module

In reply to Oded Gabbay
Quoted 72 lines · Oded Gabbay

This patch adds the main flow for the user to submit work to the device.

Each work is described by a command submission object (CS). The CS contains 3 arrays of command buffers: One for execution, and two for context-switch (store and restore).

For each CB, the user specifies on which queue to put that CB. In case of an internal queue, the entry doesn't contain a pointer to the CB but the address in the on-chip memory that the CB resides at.

The driver parses some of the CBs to enforce security restrictions.

The user receives a sequence number that represents the CS object. The user can then query the driver regarding the status of the CS, using that sequence number.

In case the CS doesn't finish before the timeout expires, the driver will perform a soft-reset of the device.

---
 drivers/misc/habanalabs/Makefile             |    3 +-
 drivers/misc/habanalabs/command_submission.c |  787 +++++++++++++
 drivers/misc/habanalabs/context.c            |   52 +-
 drivers/misc/habanalabs/device.c             |   16 +
 drivers/misc/habanalabs/goya/goya.c          | 1082 ++++++++++++++++++
 drivers/misc/habanalabs/habanalabs.h         |  274 +++++
 drivers/misc/habanalabs/habanalabs_drv.c     |   23 +
 drivers/misc/habanalabs/habanalabs_ioctl.c   |    4 +-
 drivers/misc/habanalabs/hw_queue.c           |  250 ++++
 drivers/misc/habanalabs/memory.c             |  200 ++++
 include/uapi/misc/habanalabs.h               |  158 ++-
 11 files changed, 2842 insertions(+), 7 deletions(-)
 create mode 100644 drivers/misc/habanalabs/command_submission.c
 create mode 100644 drivers/misc/habanalabs/memory.c
drivers/misc/habanalabs/Makefile +2 -1
index b5607233d216..d2fd0e18b1eb 100644
@@ -5,7 +5,8 @@
 obj-m	:= habanalabs.o
 
 habanalabs-y := habanalabs_drv.o device.o context.o asid.o habanalabs_ioctl.o \
-		command_buffer.o hw_queue.o irq.o sysfs.o hwmon.o
+		command_buffer.o hw_queue.o irq.o sysfs.o hwmon.o memory.o \
+		command_submission.o
 
 include $(src)/goya/Makefile
 habanalabs-y += $(HL_GOYA_FILES)
drivers/misc/habanalabs/command_submission.c new file +16 -0
new file mode 100644
index 000000000000..0116c2262f17
@@ -0,0 +1,787 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ */
+
+#include <uapi/misc/habanalabs.h>
+#include "habanalabs.h"
+
+#include <linux/sched/mm.h>
+#include <linux/sched/task.h>
+#include <linux/sched/signal.h>
+#include <linux/wait.h>
+#include <linux/mm.h>
+#include <linux/highmem.h>

[ ... ]

Quoted 43 lines
drivers/misc/habanalabs/command_submission.c new file +43 -0
+static void cs_do_release(struct kref *ref)
+{
+	struct hl_cs *cs = container_of(ref, struct hl_cs,
+						refcount);
+	struct hl_device *hdev = cs->ctx->hdev;
+	struct hl_cs_job *job, *tmp;
+
+	cs->completed = true;
+
+	/*
+	 * Although if we reached here it means that all external jobs have
+	 * finished, because each one of them took refcnt to CS, we still
+	 * need to go over the internal jobs and free them. Otherwise, we
+	 * will have leaked memory and what's worse, the CS object (and
+	 * potentially the CTX object) could be released, while the JOB
+	 * still holds a pointer to them (but no reference).
+	 */
+	list_for_each_entry_safe(job, tmp, &cs->job_list, cs_node)
+		free_job(hdev, job);
+
+	/* We also need to update CI for internal queues */
+	if (cs->submitted) {
+		hl_int_hw_queue_update_ci(cs);
+
+		spin_lock(&hdev->hw_queues_mirror_lock);
+		/* remove CS from hw_queues mirror list */
+		list_del_init(&cs->mirror_node);
+		spin_unlock(&hdev->hw_queues_mirror_lock);
+
+		/*
+		 * Don't cancel TDR in case this CS was timedout because we
+		 * might be running from the TDR context
+		 */
+		if ((!cs->timedout) &&
+			(hdev->timeout_jiffies != MAX_SCHEDULE_TIMEOUT)) {
+			struct hl_cs *next;
+
+			if (cs->tdr_active)
+				cancel_delayed_work_sync(&cs->work_tdr);
+
+			spin_lock(&hdev->hw_queues_mirror_lock);
+			/* queue TDR for next CS */
+			next = list_first_entry_or_null(

drivers/misc/habanalabs/command_submission.c line 214

Quoted 10 lines
drivers/misc/habanalabs/command_submission.c new file +10 -0
+					&hdev->hw_queues_mirror_list,
+					struct hl_cs, mirror_node);
+			if ((next) && (!next->tdr_active)) {
+				next->tdr_active = true;
+				schedule_delayed_work(&next->work_tdr,
+							hdev->timeout_jiffies);
+				spin_unlock(&hdev->hw_queues_mirror_lock);
+			} else {
+				spin_unlock(&hdev->hw_queues_mirror_lock);
+			}

'else' can be dropped, just move spin_unlock() outside the 'if'

Quoted 15 lines
drivers/misc/habanalabs/command_submission.c new file +15 -0
+		}
+	}
+
+	hl_ctx_put(cs->ctx);
+
+	if (cs->timedout)
+		dma_fence_set_error(cs->fence, -ETIMEDOUT);
+	else if (cs->aborted)
+		dma_fence_set_error(cs->fence, -EIO);
+
+	dma_fence_signal(cs->fence);
+	dma_fence_put(cs->fence);
+
+	kfree(cs);
+}

[ ... ]

drivers/misc/habanalabs/command_submission.c line 271

Quoted 11 lines
drivers/misc/habanalabs/command_submission.c new file +11 -0
+static int allocate_cs(struct hl_device *hdev, struct hl_ctx *ctx,
+			struct hl_cs **cs_new)
+{
+	struct hl_dma_fence *fence;
+	struct dma_fence *other = NULL;
+	struct hl_cs *cs;
+	int rc;
+
+	cs = kzalloc(sizeof(*cs), GFP_ATOMIC);
+	if (!cs)
+		return -ENOMEM;

Does this ever run from a context that cannot use GFP_KERNEL? This applies to other allocations below.

drivers/misc/habanalabs/command_submission.c line 281

Quoted 10 lines
drivers/misc/habanalabs/command_submission.c new file +10 -0
+
+	cs->ctx = ctx;
+	cs->submitted = false;
+	cs->completed = false;
+	INIT_LIST_HEAD(&cs->job_list);
+	INIT_DELAYED_WORK(&cs->work_tdr, cs_timedout);
+	kref_init(&cs->refcount);
+	spin_lock_init(&cs->job_lock);
+
+	fence = kmalloc(sizeof(*fence), GFP_ATOMIC);

kzalloc?

Quoted 45 lines
drivers/misc/habanalabs/command_submission.c new file +45 -0
+	if (!fence) {
+		rc = -ENOMEM;
+		goto free_cs;
+	}
+
+	fence->hdev = hdev;
+	spin_lock_init(&fence->lock);
+	cs->fence = &fence->base_fence;
+
+	spin_lock(&ctx->cs_lock);
+
+	fence->cs_seq = ctx->cs_sequence;
+	other = ctx->cs_pending[fence->cs_seq & (HL_MAX_PENDING_CS - 1)];
+	if ((other) && (!dma_fence_is_signaled(other))) {
+		spin_unlock(&ctx->cs_lock);
+		rc = -EAGAIN;
+		goto free_fence;
+	}
+
+	dma_fence_init(&fence->base_fence, &hl_fence_ops, &fence->lock,
+			ctx->asid, ctx->cs_sequence);
+
+	cs->sequence = fence->cs_seq;
+
+	ctx->cs_pending[fence->cs_seq & (HL_MAX_PENDING_CS - 1)] =
+							&fence->base_fence;
+	ctx->cs_sequence++;
+
+	dma_fence_get(&fence->base_fence);
+
+	dma_fence_put(other);
+
+	spin_unlock(&ctx->cs_lock);
+
+	*cs_new = cs;
+
+	return 0;
+
+free_fence:
+	kfree(fence);
+free_cs:
+	kfree(cs);
+	return rc;
+}
+

[ ... ]

Quoted 19 lines
drivers/misc/habanalabs/command_submission.c new file +19 -0
+
+static int goya_validate_cb(struct hl_device *hdev,
+			struct hl_cs_parser *parser, bool is_mmu)
+{
+	u32 cb_parsed_length = 0;
+	int rc = 0;
+
+	parser->patched_cb_size = 0;
+
+	/* cb_user_size is more than 0 so loop will always be executed */
+	while ((cb_parsed_length < parser->user_cb_size) && (!rc)) {
+		enum packet_id pkt_id;
+		u16 pkt_size;
+		void *user_pkt;
+
+		user_pkt = (void *) (parser->user_cb->kernel_address +
+							cb_parsed_length);
+
+		pkt_id = (enum packet_id) (((*(u64 *) user_pkt) &

drivers/misc/habanalabs/command_submission.c

Quoted 10 lines
drivers/misc/habanalabs/command_submission.c new file +10 -0
+				PACKET_HEADER_PACKET_ID_MASK) >>
+					PACKET_HEADER_PACKET_ID_SHIFT);
+
+		pkt_size = goya_packet_sizes[pkt_id];
+		cb_parsed_length += pkt_size;
+		if (cb_parsed_length > parser->user_cb_size) {
+			dev_err(hdev->dev,
+				"packet 0x%x is out of CB boundary\n", pkt_id);
+			rc = -EINVAL;
+			continue;

For me !rc in the while statement was blind. Please consider break here and

	if (!rc)
		break;

after the switch

Quoted 67 lines
drivers/misc/habanalabs/command_submission.c new file +67 -0
+		}
+
+		switch (pkt_id) {
+		case PACKET_WREG_32:
+			/*
+			 * Although it is validated after copy in patch_cb(),
+			 * need to validate here as well because patch_cb() is
+			 * not called in MMU path while this function is called
+			 */
+			rc = goya_validate_wreg32(hdev, parser, user_pkt);
+			break;
+
+		case PACKET_WREG_BULK:
+			dev_err(hdev->dev,
+				"User not allowed to use WREG_BULK\n");
+			rc = -EPERM;
+			break;
+
+		case PACKET_MSG_PROT:
+			dev_err(hdev->dev,
+				"User not allowed to use MSG_PROT\n");
+			rc = -EPERM;
+			break;
+
+		case PACKET_CP_DMA:
+			dev_err(hdev->dev, "User not allowed to use CP_DMA\n");
+			rc = -EPERM;
+			break;
+
+		case PACKET_STOP:
+			dev_err(hdev->dev, "User not allowed to use STOP\n");
+			rc = -EPERM;
+			break;
+
+		case PACKET_LIN_DMA:
+			if (is_mmu)
+				rc = goya_validate_dma_pkt_mmu(hdev, parser,
+						user_pkt);
+			else
+				rc = goya_validate_dma_pkt_no_mmu(hdev, parser,
+						user_pkt);
+			break;
+
+		case PACKET_MSG_LONG:
+		case PACKET_MSG_SHORT:
+		case PACKET_FENCE:
+		case PACKET_NOP:
+			parser->patched_cb_size += pkt_size;
+			break;
+
+		default:
+			dev_err(hdev->dev, "Invalid packet header 0x%x\n",
+				pkt_id);
+			rc = -EINVAL;
+			break;
+		}
+	}
+
+	/*
+	 * The new CB should have space at the end for two MSG_PROT packets:
+	 * 1. A packet that will act as a completion packet
+	 * 2. A packet that will generate MSI-X interrupt
+	 */
+	parser->patched_cb_size += sizeof(struct packet_msg_prot) * 2;
+
+	return rc;
+}

[ ... ]

Quoted 20 lines
drivers/misc/habanalabs/command_submission.c new file +20 -0
+static int goya_patch_cb(struct hl_device *hdev,
+				struct hl_cs_parser *parser)
+{
+	u32 cb_parsed_length = 0;
+	u32 cb_patched_cur_length = 0;
+	int rc = 0;
+
+	/* cb_user_size is more than 0 so loop will always be executed */
+	while ((cb_parsed_length < parser->user_cb_size) && (!rc)) {
+		enum packet_id pkt_id;
+		u16 pkt_size;
+		u32 new_pkt_size = 0;
+		void *user_pkt, *kernel_pkt;
+
+		user_pkt = (void *) (parser->user_cb->kernel_address +
+							cb_parsed_length);
+		kernel_pkt = (void *) (parser->patched_cb->kernel_address +
+							cb_patched_cur_length);
+
+		pkt_id = (enum packet_id) (((*(u64 *) user_pkt) &

drivers/misc/habanalabs/command_submission.c

Quoted 10 lines
drivers/misc/habanalabs/command_submission.c new file +10 -0
+				PACKET_HEADER_PACKET_ID_MASK) >>
+					PACKET_HEADER_PACKET_ID_SHIFT);
+
+		pkt_size = goya_packet_sizes[pkt_id];
+		cb_parsed_length += pkt_size;
+		if (cb_parsed_length > parser->user_cb_size) {
+			dev_err(hdev->dev,
+				"packet 0x%x is out of CB boundary\n", pkt_id);
+			rc = -EINVAL;
+			continue;

Ditto

Quoted 55 lines
drivers/misc/habanalabs/command_submission.c new file +55 -0
+		}
+
+		switch (pkt_id) {
+		case PACKET_LIN_DMA:
+			rc = goya_patch_dma_packet(hdev, parser, user_pkt,
+						kernel_pkt, &new_pkt_size);
+			cb_patched_cur_length += new_pkt_size;
+			break;
+
+		case PACKET_WREG_32:
+			memcpy(kernel_pkt, user_pkt, pkt_size);
+			cb_patched_cur_length += pkt_size;
+			rc = goya_validate_wreg32(hdev, parser, kernel_pkt);
+			break;
+
+		case PACKET_WREG_BULK:
+			dev_err(hdev->dev,
+				"User not allowed to use WREG_BULK\n");
+			rc = -EPERM;
+			break;
+
+		case PACKET_MSG_PROT:
+			dev_err(hdev->dev,
+				"User not allowed to use MSG_PROT\n");
+			rc = -EPERM;
+			break;
+
+		case PACKET_CP_DMA:
+			dev_err(hdev->dev, "User not allowed to use CP_DMA\n");
+			rc = -EPERM;
+			break;
+
+		case PACKET_STOP:
+			dev_err(hdev->dev, "User not allowed to use STOP\n");
+			rc = -EPERM;
+			break;
+
+		case PACKET_MSG_LONG:
+		case PACKET_MSG_SHORT:
+		case PACKET_FENCE:
+		case PACKET_NOP:
+			memcpy(kernel_pkt, user_pkt, pkt_size);
+			cb_patched_cur_length += pkt_size;
+			break;
+
+		default:
+			dev_err(hdev->dev, "Invalid packet header 0x%x\n",
+				pkt_id);
+			rc = -EINVAL;
+			break;
+		}
+	}
+
+	return rc;
+}

[ ... ]

Quoted 35 lines

static void goya_get_axi_name(struct hl_device *hdev, u32 agent_id,

drivers/misc/habanalabs/command_submission.c new file +28 -0
 		u16 event_type, char *axi_name, int len)
 {
@@ -4645,6 +5677,48 @@ static void goya_disable_clock_gating(struct hl_device *hdev)
 
 }
 
+static bool goya_is_device_idle(struct hl_device *hdev)
+{
+	u64 offset, dma_qm_reg, tpc_qm_reg, tpc_cmdq_reg, tpc_cfg_reg;
+	bool val = true;
+	int i;
+
+	offset = mmDMA_QM_1_GLBL_STS0 - mmDMA_QM_0_GLBL_STS0;
+
+	for (i = 0 ; i < DMA_MAX_NUM ; i++) {
+		dma_qm_reg = mmDMA_QM_0_GLBL_STS0 + i * offset;
+
+		val = val && ((RREG32(dma_qm_reg) & DMA_QM_IDLE_MASK) ==
+				DMA_QM_IDLE_MASK);
+	}
+
+	offset = mmTPC1_QM_GLBL_STS0 - mmTPC0_QM_GLBL_STS0;
+
+	for (i = 0 ; i < TPC_MAX_NUM ; i++) {
+		tpc_qm_reg = mmTPC0_QM_GLBL_STS0 + i * offset;
+		tpc_cmdq_reg = mmTPC0_CMDQ_GLBL_STS0 + i * offset;
+		tpc_cfg_reg = mmTPC0_CFG_STATUS + i * offset;
+
+		val = val && ((RREG32(tpc_qm_reg) & TPC_QM_IDLE_MASK) ==
+				TPC_QM_IDLE_MASK);
+		val = val && ((RREG32(tpc_cmdq_reg) & TPC_CMDQ_IDLE_MASK) ==
+				TPC_CMDQ_IDLE_MASK);
+		val = val && ((RREG32(tpc_cfg_reg) & TPC_CFG_IDLE_MASK) ==
+				TPC_CFG_IDLE_MASK);

drivers/misc/habanalabs/command_submission.c static void goya_disable_clock_gating(struct hl_device *hdev) · line 5717

Quoted 10 lines
drivers/misc/habanalabs/command_submission.c new file +10 -0
+	}
+
+	val = val && ((RREG32(mmMME_QM_GLBL_STS0) & MME_QM_IDLE_MASK) ==
+			MME_QM_IDLE_MASK);
+	val = val && ((RREG32(mmMME_CMDQ_GLBL_STS0) & MME_CMDQ_IDLE_MASK) ==
+			MME_CMDQ_IDLE_MASK);
+	val = val && ((RREG32(mmMME_ARCH_STATUS) & MME_ARCH_IDLE_MASK) ==
+			MME_ARCH_IDLE_MASK);
+	val = val && ((RREG32(mmMME_SHADOW_0_STATUS) & MME_SHADOW_IDLE_MASK) ==
+			0);

Huh, these are neat, but IMHO plain

	if ((RREG(reg) & mask) != mask)
		return false;

are more readable...

Quoted 4 lines
drivers/misc/habanalabs/command_submission.c new file +4 -0
+
+	return val;
+}
+

[ ... ]

Signature · 2 lines
Sincerely yours,
Mike.
#48 lore raw

Re: [PATCH 12/15] habanalabs: add virtual memory and MMU modules

In reply to Oded Gabbay
Quoted 32 lines · Oded Gabbay

From: Omer Shpigelman <[email protected]>

This patch adds the Virtual Memory and MMU modules.

Goya has an internal MMU which provides process isolation on the internal DDR. The internal MMU also performs translations for transactions that go from Goya to the Host.

The driver is responsible for allocating and freeing memory on the DDR upon user request. It also provides an interface to map and unmap DDR and Host memory to the device address space.

---
 drivers/misc/habanalabs/Makefile              |    2 +-
 drivers/misc/habanalabs/context.c             |   19 +-
 drivers/misc/habanalabs/device.c              |   20 +-
 drivers/misc/habanalabs/goya/goya.c           |  391 +++++
 drivers/misc/habanalabs/habanalabs.h          |  195 +++
 drivers/misc/habanalabs/habanalabs_drv.c      |    2 +-
 drivers/misc/habanalabs/habanalabs_ioctl.c    |    3 +-
 drivers/misc/habanalabs/include/goya/goya.h   |    6 +-
 .../include/hw_ip/mmu/mmu_general.h           |   45 +
 .../habanalabs/include/hw_ip/mmu/mmu_v1_0.h   |   15 +
 drivers/misc/habanalabs/memory.c              | 1506 +++++++++++++++++
 drivers/misc/habanalabs/mmu.c                 |  604 +++++++
 include/uapi/misc/habanalabs.h                |  122 +-
 13 files changed, 2922 insertions(+), 8 deletions(-)
 create mode 100644 drivers/misc/habanalabs/include/hw_ip/mmu/mmu_general.h
 create mode 100644 drivers/misc/habanalabs/include/hw_ip/mmu/mmu_v1_0.h
 create mode 100644 drivers/misc/habanalabs/mmu.c

[ ... ]

Quoted 4 lines
drivers/misc/habanalabs/goya/goya.c +0 -0
index e3867615b974..94ee4cb00a49 100644

[ ... ]

drivers/misc/habanalabs/goya/goya.c static u32 goya_non_fatal_events[GOYA_ASYC_EVENT_GROUP_NON_FATAL_SIZE] = { · line 338

Quoted 8 lines
drivers/misc/habanalabs/goya/goya.c +4 -0
@@ -265,6 +332,10 @@ static u32 goya_non_fatal_events[GOYA_ASYC_EVENT_GROUP_NON_FATAL_SIZE] = {
 };
 
 static int goya_armcp_info_get(struct hl_device *hdev);
+static void goya_mmu_prepare(struct hl_device *hdev, u32 asid);
+static int goya_mmu_clear_pgt_range(struct hl_device *hdev);
+static int goya_mmu_update_asid_hop0_addr(struct hl_device *hdev, u32 asid,
+					u64 phys_addr);

Nit: are the static declarations are necessary? Or it's a matter of moving code around?

Quoted 20 lines
drivers/misc/habanalabs/goya/goya.c +10 -0
 static void goya_get_fixed_properties(struct hl_device *hdev)
 {
@@ -303,6 +374,16 @@ static void goya_get_fixed_properties(struct hl_device *hdev)
 	prop->sram_user_base_address = prop->sram_base_address +
 						SRAM_USER_BASE_OFFSET;
 
+	prop->mmu_pgt_addr = MMU_PAGE_TABLES_ADDR;
+	if (hdev->pldm)
+		prop->mmu_pgt_size = 0x800000; /* 8MB */
+	else
+		prop->mmu_pgt_size = MMU_PAGE_TABLES_SIZE;
+	prop->mmu_pte_size = PTE_SIZE;
+	prop->mmu_hop_table_size = HOP_TABLE_SIZE;
+	prop->mmu_hop0_tables_total_size = HOP0_TABLES_TOTAL_SIZE;
+	prop->dram_page_size = PAGE_SIZE_2MB;
+
 	prop->host_phys_base_address = HOST_PHYS_BASE;
 	prop->va_space_host_start_address = VA_HOST_SPACE_START;
 	prop->va_space_host_end_address = VA_HOST_SPACE_END;

[ ... ]

Quoted 32 lines
drivers/misc/habanalabs/include/hw_ip/mmu/mmu_general.h new file +26 -0
new file mode 100644
index 000000000000..8d61ee4f2d17
@@ -0,0 +1,45 @@
+/* SPDX-License-Identifier: GPL-2.0
+ *
+ * Copyright 2016-2018 HabanaLabs, Ltd.
+ * All Rights Reserved.
+ *
+ */
+
+#ifndef INCLUDE_MMU_GENERAL_H_
+#define INCLUDE_MMU_GENERAL_H_
+
+#define PAGE_SHIFT_4KB			12
+#define PAGE_SHIFT_2MB			21
+#define PAGE_SIZE_2MB			(_AC(1, UL) << PAGE_SHIFT_2MB)
+#define PAGE_SIZE_4KB			(_AC(1, UL) << PAGE_SHIFT_4KB)
+
+#define PAGE_PRESENT_MASK		0x0000000000001
+#define SWAP_OUT_MASK			0x0000000000004
+#define LAST_MASK			0x0000000000800
+#define PHYS_ADDR_MASK			0x3FFFFFFFFF000ull
+#define HOP0_MASK			0x3000000000000ull
+#define HOP1_MASK			0x0FF8000000000ull
+#define HOP2_MASK			0x0007FC0000000ull
+#define HOP3_MASK			0x000003FE00000
+#define HOP4_MASK			0x00000001FF000
+#define OFFSET_MASK			0x0000000000FFF
+

drivers/misc/habanalabs/include/hw_ip/mmu/mmu_general.h line 36

Quoted 10 lines
drivers/misc/habanalabs/include/hw_ip/mmu/mmu_general.h new file +10 -0
+#define HOP0_SHIFT			48
+#define HOP1_SHIFT			39
+#define HOP2_SHIFT			30
+#define HOP3_SHIFT			21
+#define HOP4_SHIFT			12
+
+#define PTE_PHYS_ADDR_SHIFT		12
+#define PTE_PHYS_ADDR_MASK		~0xFFF
+
+#define PTE_SIZE			sizeof(u64)

I suspect some architectures define PTE_SIZE in arch/*/include/asm Probably you'd want to namespace this.

Quoted 65 lines
drivers/misc/habanalabs/include/hw_ip/mmu/mmu_general.h new file +9 -0
+#define HOP_TABLE_SIZE			PAGE_SIZE_4KB
+#define HOP0_TABLES_TOTAL_SIZE		(HOP_TABLE_SIZE * MAX_ASID)
+
+#define MMU_HOP0_PA43_12_SHIFT		12
+#define MMU_HOP0_PA49_44_SHIFT		(12 + 32)
+
+#define MMU_CONFIG_TIMEOUT_USEC		2000 /* 2 ms */
+
+#endif /* INCLUDE_MMU_GENERAL_H_ */
drivers/misc/habanalabs/memory.c +42 -0
index 94cbb252656d..c41ea19502e5 100644
@@ -5,12 +5,1193 @@
  * All Rights Reserved.
  */
 
+#include <uapi/misc/habanalabs.h>
 #include "habanalabs.h"
+#include "include/hw_ip/mmu/mmu_general.h"
 
 #include <linux/sched.h>
 #include <linux/uaccess.h>
 #include <linux/genalloc.h>
 
+#define HL_MMU_DEBUG	0
+
+/*
+ * The va ranges in context object contain a list with the available chunks of
+ * device virtual memory.
+ * There is one range for host allocations and one for DRAM allocations.
+ *
+ * On initialization each range contains one chunk of all of its available
+ * virtual range which is a half of the total device virtual range.
+ *
+ * On each mapping of physical pages, a suitable virtual range chunk (with a
+ * minimum size) is selected from the list. If the chunk size equals the
+ * requested size, the chunk is returned. Otherwise, the chunk is split into
+ * two chunks - one to return as result and a remainder to stay in the list.
+ *
+ * On each Unmapping of a virtual address, the relevant virtual chunk is
+ * returned to the list. The chunk is added to the list and if its edges match
+ * the edges of the adjacent chunks (means a contiguous chunk can be created),
+ * the chunks are merged.
+ *
+ * On finish, the list is checked to have only one chunk of all the relevant
+ * virtual range (which is a half of the device total virtual range).
+ * If not (means not all mappings were unmapped), a warning is printed.
+ */
+
+/**
+ * alloc_device_memory - allocate device memory
+ *
+ * @ctx                 : current context
+ * @args                : host parameters containing the requested size
+ * @ret_handle          : result handle
+ *
+ * This function does the following:
+ * - Allocate the requested size rounded up to 2MB pages
+ * - Return unique handle
+ */
+static int alloc_device_memory(struct hl_ctx *ctx, struct hl_mem_in *args,
+				u32 *ret_handle)
+{
+	struct hl_device *hdev = ctx->hdev;

drivers/misc/habanalabs/memory.c line 65

Quoted 10 lines
drivers/misc/habanalabs/memory.c +10 -0
+	struct hl_vm *vm = &hdev->vm;
+	struct hl_vm_phys_pg_list *phys_pg_list;
+	struct hl_vm_phys_pg *phys_pg, *tmp;
+	u64 paddr = 0;
+	u32 total_size, num_pgs, page_size, page_shift;
+	int handle, rc, i;
+	bool contiguous;
+
+	page_size = hdev->asic_prop.dram_page_size;
+	page_shift = __ffs(page_size);

Maybe it's worth storing page_shift in the asi_prop and calculating page_size.

Quoted 20 lines
drivers/misc/habanalabs/memory.c +20 -0
+	num_pgs = (args->alloc.mem_size + (page_size - 1)) >> page_shift;
+	total_size = num_pgs << page_shift;
+
+	contiguous = args->flags & HL_MEM_CONTIGUOUS;
+
+	if (contiguous) {
+		paddr = (u64) gen_pool_alloc(vm->dram_pg_pool, total_size);
+		if (!paddr) {
+			dev_err(hdev->dev,
+				"failed to allocate %u huge contiguous pages\n",
+				num_pgs);
+			return -ENOMEM;
+		}
+	}
+
+	phys_pg_list = kzalloc(sizeof(*phys_pg_list), GFP_KERNEL);
+	if (!phys_pg_list) {
+		rc = -ENOMEM;
+		goto page_list_err;
+	}

drivers/misc/habanalabs/memory.c line 95

Quoted 10 lines
drivers/misc/habanalabs/memory.c +10 -0
+
+	phys_pg_list->vm_type = VM_TYPE_PHYS_LIST;
+	phys_pg_list->asid = ctx->asid;
+	phys_pg_list->total_size = total_size;
+	phys_pg_list->flags = args->flags;
+	phys_pg_list->contiguous = contiguous;
+	INIT_LIST_HEAD(&phys_pg_list->list);
+
+	for (i = 0 ; i < num_pgs ; i++) {
+		phys_pg = kzalloc(sizeof(*phys_pg), GFP_KERNEL);

Consider adding *phys_pgs to phys_pg_list using kcalloc() before the loop.

Quoted 65 lines
drivers/misc/habanalabs/memory.c +65 -0
+		if (!phys_pg) {
+			rc = -ENOMEM;
+			goto pb_err;
+		}
+
+		phys_pg->page_size = page_size;
+
+		if (phys_pg_list->contiguous) {
+			phys_pg->paddr = paddr + i * phys_pg->page_size;
+		} else {
+			phys_pg->paddr =
+				(u64) gen_pool_alloc(vm->dram_pg_pool,
+							phys_pg->page_size);
+			if (!phys_pg->paddr) {
+				dev_err(hdev->dev, "ioctl failed to allocate page\n");
+				kfree(phys_pg);
+				rc = -ENOMEM;
+				goto pb_err;
+			}
+		}
+
+		list_add_tail(&phys_pg->node, &phys_pg_list->list);
+	}
+
+	spin_lock(&vm->idr_lock);
+	handle = idr_alloc(&vm->phys_pg_list_handles, phys_pg_list, 1, 0,
+				GFP_ATOMIC);
+	spin_unlock(&vm->idr_lock);
+
+	if (handle < 0) {
+		dev_err(hdev->dev, "Failed to get handle for page\n");
+		rc = -EFAULT;
+		goto idr_err;
+	}
+
+	for (i = 0; i < num_pgs ; i++)
+		kref_get(&vm->dram_pg_pool_refcount);
+
+	phys_pg_list->handle = handle;
+
+	atomic64_add(phys_pg_list->total_size, &ctx->dram_phys_mem);
+	atomic64_add(phys_pg_list->total_size, &hdev->dram_used_mem);
+
+	*ret_handle = handle;
+
+	return 0;
+
+idr_err:
+pb_err:
+	list_for_each_entry_safe(phys_pg, tmp, &phys_pg_list->list, node) {
+		if (!phys_pg_list->contiguous)
+			gen_pool_free(vm->dram_pg_pool, phys_pg->paddr,
+					phys_pg->page_size);
+
+		list_del(&phys_pg->node);
+		kfree(phys_pg);
+	}
+
+	kfree(phys_pg_list);
+page_list_err:
+	if (contiguous)
+		gen_pool_free(vm->dram_pg_pool, paddr, total_size);
+
+	return rc;
+}

[ ... ]

Quoted 40 lines
drivers/misc/habanalabs/memory.c +40 -0
+/**
+ * free_phys_pg_list    - free physical page list
+ *
+ * @hdev                : habanalabs device structure
+ * @phys_pg_list        : physical page list to free
+ *
+ * This function does the following:
+ * - Iterate over the list and free each physical block structure
+ * - In case of allocated memory, return the physical memory to the general pool
+ * - Free the hl_vm_phys_pg_list structure
+ */
+static void free_phys_pg_list(struct hl_device *hdev,
+		struct hl_vm_phys_pg_list *phys_pg_list)
+{
+	struct hl_vm *vm = &hdev->vm;
+	struct hl_vm_phys_pg *phys_pg, *tmp;
+	u32 num_pgs;
+	bool first = true;
+	int i;
+
+	list_for_each_entry_safe(phys_pg, tmp, &phys_pg_list->list, node) {
+		/*
+		 * this if statement is relevant only when called from
+		 * hl_vm_ctx_fini() and free_device_memory()
+		 */
+		if (!phys_pg_list->created_from_userptr) {
+			if ((phys_pg_list->contiguous) && (first)) {
+				first = false;
+				gen_pool_free(vm->dram_pg_pool,
+						phys_pg->paddr,
+						phys_pg_list->total_size);
+
+				num_pgs = phys_pg_list->total_size >>
+					__ffs(hdev->asic_prop.dram_page_size);
+
+				for (i = 0; i < num_pgs ; i++)
+					kref_put(&vm->dram_pg_pool_refcount,
+						dram_pg_pool_do_release);
+
+			} else if (!phys_pg_list->contiguous) {

drivers/misc/habanalabs/memory.c line 305

Quoted 10 lines
drivers/misc/habanalabs/memory.c +10 -0
+				gen_pool_free(vm->dram_pg_pool, phys_pg->paddr,
+						phys_pg->page_size);
+				kref_put(&vm->dram_pg_pool_refcount,
+						dram_pg_pool_do_release);
+			}
+		}
+
+		list_del(&phys_pg->node);
+		kfree(phys_pg);
+	}

Unless I'm missing something this can be simplified a bit:

if (!phys_pg_list->created_from_userptr) {
	for (i = 0; i < num_pgs ; i++)
		kref_put(&vm->dram_pg_pool_refcount,
			 dram_pg_pool_do_release);
	if (phys_pg_list->contiguous)
		gen_pool_free(vm->dram_pg_pool, phys_pg->paddr,
			      phys_pg_list->total_size);
}
list_for_each_entry_safe(phys_pg, tmp, &phys_pg_list->list, node) {
	if (!phys_pg_list->created_from_userptr &&
	    !phys_pg_list->contiguous)
		gen_pool_free(vm->dram_pg_pool, phys_pg->paddr,
			      phys_pg->page_size);
	list_del(&phys_pg->node);
	kfree(phys_pg);
}

nd with phys_pg's array hanging from phys_pg_list it would be even simpler ;-)

Quoted 4 lines
drivers/misc/habanalabs/memory.c +4 -0
+
+	kfree(phys_pg_list);
+}
+
Signature · 2 lines
Sincerely yours,
Mike.
#92 lore raw

Re: [PATCH 1/5] drivers/accel: Introduce subsystem

In reply to Daniel Vetter

Hi Olof & Greg,

Ok I thought about what this means in practice a bit more over the w/e, and I think we need to drag this discussion on for a bit more.

Quoted 54 lines · Daniel Vetter
Quoted 21 lines · Olof Johansson

We're starting to see more of these kind of devices, the current upcoming wave will likely be around machine learning and inference engines. A few drivers have been added to drivers/misc for this, but it's timely to make it into a separate group of drivers/subsystem, to make it easier to find them, and to encourage collaboration between contributors.

Over time, we expect to build shared frameworks that the drivers will make use of, but how that framework needs to look like to fill the needs is still unclear, and the best way to gain that knowledge is to give the disparate implementations a shared location.

There has been some controversy around expectations for userspace stacks being open. The clear preference is to see that happen, and any driver and platform stack that is delivered like that will be given preferential treatment, and at some point in the future it might become the requirement. Until then, the bare minimum we need is an open low-level userspace such that the driver and HW interfaces can be exercised if someone is modifying the driver, even if the full details of the workload are not always available.

Quoted 6 lines

Bootstrapping this with myself and Greg as maintainers (since the current drivers will be moving out of drivers/misc). Looking forward to expanding that group over time.

Cc Greg Kroah-Hartman <[email protected]>

I spent a bit of time reading the proposed drivers, mostly just their uapi (habanalabs and ocxl&cxl), and there's really no technical difference I think between an accelaration driver sitting in drivers/gpu and an accelaration driver sitting in drivers/accel. Except:

- drivers/gpu already has common interfaces for the things you'll probably want to standardize (buffer sharing, syncronization primitives, scheduler - right now we're working on figuring out some common tracepoints).

- Maybe even more important, drivers/gpu has the lessons learned in its codebase about what not to standardize between drivers (everything else, you'll regret it, we've been there).

- drivers/gpu is the subsystem with 20 years of experience writing tiny shim drivers in the kernel for high performance accelarators that need a pretty huge stack in userspace to make them do anything useful. 20 years ago all the rage to make faster was graphics, now it's AI. Looks exactly the same from a kernel pov - command buffers, gigabytes of DMA and a security/long term support nightmare.

- drivers/gpu requires open source. The real thing, not some demo that does a few DMA operations.

Quoted 9 lines

And now we have drivers/accel and someone gets to explain to nvidia (or arm or whatever) how their exact same drivers (and well run engineering orgs really only invent command submission once) can be merged when they say it's for a TPU, and will get rejected when they say it's for a GPU. Or someone gets to explain to TPU+GPU vendors why their driver is not cool (because we'd end up with two), while their startup-competition only doing a TPU is totally fine and merged into upstream. Or we just stuff all the kernel drivers for blobby userspace into drivers/accel and otherwise ignore each another.

One awkward scenario I've missed is the following:
1. the fully open stack for accelarating glow/tensorflow/DNN that we're planning to make happen takes off. Rough idea is llvm+spriv+clover (in mesa) + gallium backends (also mesa3d) + drm.

2. if that's the case and someone writes an r/e'ed driver for such a TPU (and the vendor supporting only their blob stack) then the reasonable thing would be to write that stack on top of the existing open source accelarator infrastructure. So a new/2nd driver in the kernel, using the drm+mesa infrastructure.

3. this means to not block r/e efforts on we need to be ok with duplicated drivers between drivers/accel and drivers/gpu - not being able to share code with all the other programmable accelarators will make it nigh impossible to have a working r/e'ed stack. We already see this on the gl/vk/cl side, where the mesa drivers tend to be 1-2 orders of magnitude smaller than the proprietary/vendor stacks (whether open or closed).

Quoted 9 lines

I guess that last option would at least somewhat help me, since I wont ever have to explain anymore why we're the radical commies on dri-devel :-)

Anyway, only reason I replied here again is because I accidentally started a private thread (well was too lazy to download the mbox to properly reply), and that's not good either. But I don't think anyone's going to change their opinion here, I think this reply is just for the record.

Quoted 6 lines

Cheers, Daniel

PS: Seen that there's a v2 of this now with Documentation, hasn't reached my inbox (yet). I don't think that one clarifies any of the tricky questions between drivers/gpu and drivers/accel, so figured won't harm if I leave the reply on v1.

Given the above revising my stance, and I think your item to exclude overlap between drivers/accel and drivers/gpu is actually harmful. And we instead need a line that yes, there is overlap, and we do expect the occasional duplicated driver for the same hardware. I think that's going to have the best outcome:

- It's not going to piss off the drivers/gpu people any more than drivers/accel itself does, you already scored all the sighs you'll get I think. So won't make things worse.

- It's going to be the technically sound decision, since no more "is this a tpu or gpu" non-technical tricky questions that just depend upon what you market a chip for, instead of what it is.

- I think it's going to be much quicker to prove whether drivers/gpu is too strict with merging drivers and has harmed the overall ecosystem, since you'll have many more drivers to potentially merge. One argument in your favour is clearly that we've never tried to drop the open source userspace requirement. Imo if we're going to do this experiment, we should do it right.

- There's not going to be a problem for accelarators that need to work together with atomic modeset drivers or v4l drivers for displaying their computation results - all you need for that is dma-buf import, and you'll need that sooner or later anyway in drivers/accel. dma-buf compatibility extends all gfx userspace protocols (I think we rev'ed them all to add dma-buf support). There's also not going to be coordination problems due to this with drivers/gpu, since all the dma-buf bits you'll need are already in drivers/dma-buf.

- It might actually make r/e'ing gpus easier, since currently you need to boot 2 different kernels: One with the upstream drm stack, the other with downstream vendor stack. If you actually manage to get all these drivers merged in a useable state that would become better.

- Essentially this would make drivers/accel the -staging for drivers/gpu, at least from our pov. I don't think that's going to be an issue - with Greg you already have the residential expert for maintaining dumpster fires on the team. And as long as we don't try to share code (beyond stuff in drivers/dma-buf) I don't think this will result in the coordination pains we've had with display drivers in -staging.

- This is not going to set a new precedence - there's been plenty of duplicated subsystem, especially for drivers. Occasionally you just need to burn it all down and start over.

- Like with your proposal here for drivers/accel we can always change the rules in a few years, or whenever it's clear what to do. And I think the positions between the drivers/gpu and drivers/accel folks are fundamentally opposed, there's not really a room for a both ways compromise, best seems to decide this by actually trying it out.

- Plus, I can just point people at you instead of having to explain why we insist on open source for accelarators in drivers/gpu. That wasn't meant as a joke, not entirely at least, it's kinda tiring to have this discussion at least once every year ...

tldr; If you want to do this, do it right.

All we need is to drop your paragraph about avoiding overlap with drivers/gpu, and instead acknowledge that there is an overlap with the accelarator drivers in drivers/gpu and clearly state that both subsystems are going to be ok with that overlap and duplication. I'd ack that version.

Cheers, Daniel

Quoted 90 lines
Quoted 83 lines
---
 MAINTAINERS            |  8 ++++++++
 drivers/Kconfig        |  2 ++
 drivers/Makefile       |  1 +
 drivers/accel/Kconfig  | 16 ++++++++++++++++
 drivers/accel/Makefile |  5 +++++
 5 files changed, 32 insertions(+)
 create mode 100644 drivers/accel/Kconfig
 create mode 100644 drivers/accel/Makefile
MAINTAINERS +8 -0
index ddcdc29dfe1f6..8a9bbaf8f6e90 100644
@@ -7033,6 +7033,14 @@ W:     https://linuxtv.org
 S:   Supported
 F:   drivers/media/platform/sti/hva
 
+HW ACCELERATOR OFFLOAD SUBSYSTEM
+M:   Olof Johansson <[email protected]>
+M:   Greg Kroah-Hartman <[email protected]>
+L:   [email protected]
+S:   Supported
+F:   drivers/accel/
+F:   Documentation/accelerators/
+
 HWPOISON MEMORY FAILURE HANDLING
 M:   Naoya Horiguchi <[email protected]>
 L:   [email protected]
drivers/Kconfig +2 -0
index 4f9f99057ff85..3cc461f325569 100644
@@ -228,4 +228,6 @@ source "drivers/siox/Kconfig"
 
 source "drivers/slimbus/Kconfig"
 
+source "drivers/accel/Kconfig"
+
 endmenu
drivers/Makefile +1 -0
index 04da7876032cc..e4be06579cc5d 100644
@@ -186,3 +186,4 @@ obj-$(CONFIG_MULTIPLEXER) += mux/
 obj-$(CONFIG_UNISYS_VISORBUS)        += visorbus/
 obj-$(CONFIG_SIOX)           += siox/
 obj-$(CONFIG_GNSS)           += gnss/
+obj-$(CONFIG_ACCEL)          += accel/
drivers/accel/Kconfig new file +16 -0
new file mode 100644
index 0000000000000..13b36c0398895
@@ -0,0 +1,16 @@
+#
+# Drivers for hardware offload accelerators
+# See Documentation/accel/README.rst for more details
+#
+
+menuconfig ACCEL
+     bool "Hardware offload accelerator support"
+        help
+       HW offload accelerators are used for high-bandwidth workloads
+       where a higher-level kernel/userspace interface isn't suitable.
+
+if ACCEL
+
+comment "HW Accellerator drivers"
+
+endif
drivers/accel/Makefile new file +5 -1
new file mode 100644
index 0000000000000..343bbb8f45a14
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Makefile for accel devices
+#
+
--
Quoted 2 lines

2.11.0

--
Daniel Vetter
Software Engineer, Intel Corporation
http://blog.ffwll.ch

Signature · 3 lines
Daniel Vetter
Software Engineer, Intel Corporation
+41 (0) 79 365 57 48 - http://blog.ffwll.ch
#19 lore raw

Re: [PATCH 03/15] habanalabs: add basic Goya support

In reply to Mike Rapoport
Quoted 89 lines · Mike Rapoport
Quoted 22 lines · Oded Gabbay
Quoted 21 lines · Mike Rapoport
Quoted 19 lines · Oded Gabbay

This patch adds a basic support for the Goya device. The code initializes the device's PCI controller and PCI bars. It also initializes various S/W structures and adds some basic helper functions.

---
 drivers/misc/habanalabs/Makefile            |   5 +-
 drivers/misc/habanalabs/device.c            |  71 +++
 drivers/misc/habanalabs/goya/Makefile       |   3 +
 drivers/misc/habanalabs/goya/goya.c         | 633 ++++++++++++++++++++
 drivers/misc/habanalabs/goya/goyaP.h        | 125 ++++
 drivers/misc/habanalabs/habanalabs.h        | 131 ++++
 drivers/misc/habanalabs/habanalabs_drv.c    |   3 +
 drivers/misc/habanalabs/include/goya/goya.h | 115 ++++
 8 files changed, 1085 insertions(+), 1 deletion(-)
 create mode 100644 drivers/misc/habanalabs/goya/Makefile
 create mode 100644 drivers/misc/habanalabs/goya/goya.c
 create mode 100644 drivers/misc/habanalabs/goya/goyaP.h
 create mode 100644 drivers/misc/habanalabs/include/goya/goya.h

[ ... ]

Quoted 17 lines
Quoted 9 lines
Quoted 9 lines
drivers/misc/habanalabs/goya/goya.c new file +9 -0
+
+/**
+ * goya_sw_init - Goya software initialization code
+ *
+ * @hdev: pointer to hl_device structure
+ *
+ */
+static int goya_sw_init(struct hl_device *hdev)
+{
Quoted 8 lines

drivers/misc/habanalabs/goya/goya.c line 501

Quoted 5 lines
drivers/misc/habanalabs/goya/goya.c new file +5 -0
+     struct goya_device *goya;
+     int rc;
+
+     /* Allocate device structure */
+     goya = kzalloc(sizeof(*goya), GFP_KERNEL);

Consider using devm_k[mz]alloc() for memory allocations throughout the driver. I didn't check all the spots where it can be applicable.

Quoted 5 lines

I honestly wasn't aware of that. We never used that in AMD drivers (which where I spent most of my kernel time).
I'll look into that offline but for now I don't really want to change into it blindly in all locations, unless there is some hard kernel rule for using that in drivers.

AFAIK, there's no such rule. It's just supposed to make driver developer/maintainer life easier ;-)

Quoted 17 lines
Quoted 17 lines
Quoted 17 lines
drivers/misc/habanalabs/goya/goya.c new file +16 -0
+     if (!goya)
+             return -ENOMEM;
+
+     /* according to goya_init_iatu */
+     goya->ddr_bar_cur_addr = DRAM_PHYS_BASE;
+     hdev->asic_specific = goya;
+
+     /* Create DMA pool for small allocations */
+     hdev->dma_pool = dma_pool_create(dev_name(hdev->dev),
+                     &hdev->pdev->dev, GOYA_DMA_POOL_BLK_SIZE, 8, 0);
+     if (!hdev->dma_pool) {
+             dev_err(hdev->dev, "failed to create DMA pool\n");
+             rc = -ENOMEM;
+             goto free_goya_device;
+     }
+

[ ... ]

Quoted 16 lines
Quoted 15 lines

drivers/misc/habanalabs/goya/goya.c line 621

Quoted 10 lines
drivers/misc/habanalabs/goya/goya.c new file +10 -0
+
+static const struct hl_asic_funcs goya_funcs = {
+     .early_init = goya_early_init,
+     .early_fini = goya_early_fini,
+     .sw_init = goya_sw_init,
+     .sw_fini = goya_sw_fini,
+     .suspend = goya_suspend,
+     .resume = goya_resume,
+     .dma_alloc_coherent = goya_dma_alloc_coherent,
+     .dma_free_coherent = goya_dma_free_coherent,

Is there any additional functionality that is planned in goya or gaudi in these two functions?
It seems like they are not really needed, at least at the moment and for sure that don't need to be part of ASIC ops.

Quoted 5 lines
Quoted 3 lines

So this relates to the simulator support, because there the implementation of these two functions is totally different as I don't have pci device.

Can you please add a comment about it here?

Of course, done.
Thanks,
Oded

Quoted 5 lines

--
Sincerely yours,
Mike.

#27 lore raw

Re: [PATCH 05/15] habanalabs: add command buffer module

In reply to Mike Rapoport
Quoted 86 lines · Mike Rapoport
Quoted 43 lines · Oded Gabbay
Quoted 6 lines · Mike Rapoport
Quoted 2 lines · Oded Gabbay

This patch adds the CB module, which allows the user to create and destroy CBs and to map them to the user's process address-space.

Can you please spell "command buffer" at least first time it's mentioned?

fixed

Quoted 35 lines
Quoted 35 lines

A command buffer is a memory blocks that reside in DMA-able address-space and is physically contiguous so it can be accessed by the device without MMU translation. The command buffer memory is allocated using the coherent DMA API.

When creating a new CB, the IOCTL returns a handle of it, and the user-space process needs to use that handle to mmap the buffer to get a VA in the user's address-space.

Before destroying (freeing) a CB, the user must unmap the CB's VA using the CB handle.

Each CB has a reference counter, which tracks its usage in command submissions and also its mmaps (only a single mmap is allowed).

The driver maintains a pool of pre-allocated CBs in order to reduce latency during command submissions. In case the pool is empty, the driver will go to the slow-path of allocating a new CB, i.e. calling dma_alloc_coherent.

---
 drivers/misc/habanalabs/Makefile           |   3 +-
 drivers/misc/habanalabs/command_buffer.c   | 414 +++++++++++++++++++++
 drivers/misc/habanalabs/device.c           |  43 ++-
 drivers/misc/habanalabs/goya/goya.c        |  28 ++
 drivers/misc/habanalabs/habanalabs.h       |  95 ++++-
 drivers/misc/habanalabs/habanalabs_drv.c   |   2 +
 drivers/misc/habanalabs/habanalabs_ioctl.c | 102 +++++
 include/uapi/misc/habanalabs.h             |  62 +++
 8 files changed, 746 insertions(+), 3 deletions(-)
 create mode 100644 drivers/misc/habanalabs/command_buffer.c
 create mode 100644 drivers/misc/habanalabs/habanalabs_ioctl.c
 create mode 100644 include/uapi/misc/habanalabs.h

[ ... ]

Quoted 38 lines
Quoted 26 lines
Quoted 26 lines
drivers/misc/habanalabs/command_buffer.c new file +26 -0
+int hl_cb_create(struct hl_device *hdev, struct hl_cb_mgr *mgr,
+                     u32 cb_size, u64 *handle, int ctx_id)
+{
+     struct hl_cb *cb;
+     bool alloc_new_cb = true;
+     int rc;
+
+     if (hdev->disabled) {
+             dev_warn_ratelimited(hdev->dev,
+                     "Device is disabled !!! Can't create new CBs\n");
+             rc = -EBUSY;
+             goto out_err;
+     }
+
+     /* Minimum allocation must be PAGE SIZE */
+     if (cb_size < PAGE_SIZE)
+             cb_size = PAGE_SIZE;
+
+     if (ctx_id == HL_KERNEL_ASID_ID &&
+                     cb_size <= hdev->asic_prop.cb_pool_cb_size) {
+
+             spin_lock(&hdev->cb_pool_lock);
+             if (!list_empty(&hdev->cb_pool)) {
+                     cb = list_first_entry(&hdev->cb_pool, typeof(*cb),
+                                     pool_list);
+                     list_del(&cb->pool_list);
Quoted 8 lines

drivers/misc/habanalabs/command_buffer.c line 107

Quoted 5 lines
drivers/misc/habanalabs/command_buffer.c new file +5 -0
+                     spin_unlock(&hdev->cb_pool_lock);
+                     alloc_new_cb = false;
+             } else {
+                     spin_unlock(&hdev->cb_pool_lock);
+                     dev_warn_once(hdev->dev, "CB pool is empty\n");

Isn't it going to be a false alarm when you allocate the cb for the first time?

Why ?
The cb_pool list holds a list of available CBs. See hl_cb_pool_init()
- it adds newly allocated CBs to this pool list.

Quoted 7 lines
Quoted 3 lines

if (!list_empty(&hdev->cb_pool)) { - this checks whether the
pool is not empty so we can take an available CB from it. If the list is empty (hence the pool is empty), we print the warning.

Sorry if it's too much nitpicking, but why the allocation of the first cb should be a warning? There's nothing wrong there... Maybe dev_dbg() instead?

Yeah, that's a fair point. The issue is I would like to know if we reach to this state and dev_dbg isn't usually enabled. Still, I get what you are saying and I'll change this to dev_dbg.

Quoted 20 lines
Quoted 20 lines
Quoted 19 lines
Quoted 7 lines
drivers/misc/habanalabs/command_buffer.c new file +6 -0
+             }
+     }
+
+     if (alloc_new_cb) {
+             cb = hl_cb_alloc(hdev, cb_size, ctx_id);
+             if (!cb) {

drivers/misc/habanalabs/command_buffer.c line 123

Quoted 10 lines
drivers/misc/habanalabs/command_buffer.c new file +10 -0
+                     rc = -ENOMEM;
+                     goto out_err;
+             }
+     }
+
+     cb->hdev = hdev;
+     cb->ctx_id = ctx_id;
+
+     spin_lock(&mgr->cb_lock);
+     rc = idr_alloc(&mgr->cb_handles, cb, 1, 0, GFP_ATOMIC);

It seems the ID will remain dangling if the cb is reused.

Quoted 6 lines
Quoted 2 lines

I'm not sure what you mean by this comment. Reused by whom ? in how fashion it is reused ?

Sorry if I didn't explain it more clearly.
If the case the cb is reused, you anyway call idr_alloc() and overwrite the previous value of cb->id and it never gets idr_remove()'ed

I don't think that is the case.
Please look at hl_cb_destroy(). There, we do the idr_remove and then we kref_put the CB. In it's release code path, we check if this is a CB from pool, and if so, we return it to the pool. When it will be alloc'ed again, it will get a new id.
The problem in this patch is that hl_cb_destroy is not used yet for CB's from the pool because the command submission code which use that comes at a later patch, so indeed it might be confusing. But if you will take a look at the entire code and check when hl_cb_destroy is called I think you will agree with me.
But if you still think otherwise, please tell me. I might be missing something here.

Thanks,
Oded

Quoted 36 lines
Quoted 23 lines
Quoted 23 lines
Quoted 23 lines
drivers/misc/habanalabs/command_buffer.c new file +21 -0
+     spin_unlock(&mgr->cb_lock);
+
+     if (rc < 0) {
+             dev_err(hdev->dev, "Failed to allocate IDR for a new CB\n");
+             goto release_cb;
+     }
+
+     cb->id = rc;
+
+     kref_init(&cb->refcount);
+     spin_lock_init(&cb->lock);
+
+     /*
+      * idr is 32-bit so we can safely OR it with a mask that is above
+      * 32 bit
+      */
+     *handle = cb->id | HL_MMAP_CB_MASK;
+     *handle <<= PAGE_SHIFT;
+
+     return 0;
+
Quoted 8 lines
Quoted 8 lines

drivers/misc/habanalabs/command_buffer.c line 152

Quoted 8 lines
drivers/misc/habanalabs/command_buffer.c new file +8 -0
+release_cb:
+     cb_do_release(hdev, cb);
+out_err:
+     *handle = 0;
+
+     return rc;
+}
+

--
Sincerely yours,
Mike.