habanalabs: initialize hpriv fields before adding new node
authorMoti Haimovski <mhaimovski@habana.ai>
Mon, 16 Aug 2021 11:39:46 +0000 (14:39 +0300)
committerOded Gabbay <ogabbay@kernel.org>
Mon, 18 Oct 2021 09:05:47 +0000 (12:05 +0300)
When adding a new node to the hpriv list, the driver should
initialize its fields before adding the new node.

Otherwise, there may be some small chance of another thread traversing
that list and accessing the new node's fields without them being
initialized.

Signed-off-by: Moti Haimovski <mhaimovski@habana.ai>
Reviewed-by: Oded Gabbay <ogabbay@kernel.org>
Signed-off-by: Oded Gabbay <ogabbay@kernel.org>
drivers/misc/habanalabs/common/habanalabs_drv.c

index 1da56069750a3944201779888e1ae37590f13c13..949d1b5c5c41cc86c01c7b0ca623fa4e67ec3e89 100644 (file)
@@ -225,6 +225,17 @@ int hl_device_open_ctrl(struct inode *inode, struct file *filp)
        if (!hpriv)
                return -ENOMEM;
 
+       /* Prevent other routines from reading partial hpriv data by
+        * initializing hpriv fields before inserting it to the list
+        */
+       hpriv->hdev = hdev;
+       filp->private_data = hpriv;
+       hpriv->filp = filp;
+       hpriv->is_control = true;
+       nonseekable_open(inode, filp);
+
+       hpriv->taskpid = find_get_pid(current->pid);
+
        mutex_lock(&hdev->fpriv_list_lock);
 
        if (!hl_device_operational(hdev, NULL)) {
@@ -238,19 +249,15 @@ int hl_device_open_ctrl(struct inode *inode, struct file *filp)
        list_add(&hpriv->dev_node, &hdev->fpriv_list);
        mutex_unlock(&hdev->fpriv_list_lock);
 
-       hpriv->hdev = hdev;
-       filp->private_data = hpriv;
-       hpriv->filp = filp;
-       hpriv->is_control = true;
-       nonseekable_open(inode, filp);
-
-       hpriv->taskpid = find_get_pid(current->pid);
-
        return 0;
 
 out_err:
        mutex_unlock(&hdev->fpriv_list_lock);
+       filp->private_data = NULL;
+       put_pid(hpriv->taskpid);
+
        kfree(hpriv);
+
        return rc;
 }