1 // SPDX-License-Identifier: GPL-2.0
4 * Copyright 2016-2019 HabanaLabs, Ltd.
8 #define pr_fmt(fmt) "habanalabs: " fmt
10 #include "habanalabs.h"
12 #include <linux/pci.h>
13 #include <linux/hwmon.h>
14 #include <uapi/misc/habanalabs.h>
16 enum hl_device_status hl_device_status(struct hl_device *hdev)
18 enum hl_device_status status;
20 if (atomic_read(&hdev->in_reset))
21 status = HL_DEVICE_STATUS_IN_RESET;
22 else if (hdev->needs_reset)
23 status = HL_DEVICE_STATUS_NEEDS_RESET;
24 else if (hdev->disabled)
25 status = HL_DEVICE_STATUS_MALFUNCTION;
27 status = HL_DEVICE_STATUS_OPERATIONAL;
32 bool hl_device_operational(struct hl_device *hdev,
33 enum hl_device_status *status)
35 enum hl_device_status current_status;
37 current_status = hl_device_status(hdev);
39 *status = current_status;
41 switch (current_status) {
42 case HL_DEVICE_STATUS_IN_RESET:
43 case HL_DEVICE_STATUS_MALFUNCTION:
44 case HL_DEVICE_STATUS_NEEDS_RESET:
46 case HL_DEVICE_STATUS_OPERATIONAL:
52 static void hpriv_release(struct kref *ref)
54 struct hl_fpriv *hpriv;
55 struct hl_device *hdev;
57 hpriv = container_of(ref, struct hl_fpriv, refcount);
61 put_pid(hpriv->taskpid);
63 hl_debugfs_remove_file(hpriv);
65 mutex_destroy(&hpriv->restore_phase_mutex);
67 mutex_lock(&hdev->fpriv_list_lock);
68 list_del(&hpriv->dev_node);
69 hdev->compute_ctx = NULL;
70 mutex_unlock(&hdev->fpriv_list_lock);
75 void hl_hpriv_get(struct hl_fpriv *hpriv)
77 kref_get(&hpriv->refcount);
80 void hl_hpriv_put(struct hl_fpriv *hpriv)
82 kref_put(&hpriv->refcount, hpriv_release);
86 * hl_device_release - release function for habanalabs device
88 * @inode: pointer to inode structure
89 * @filp: pointer to file structure
91 * Called when process closes an habanalabs device
93 static int hl_device_release(struct inode *inode, struct file *filp)
95 struct hl_fpriv *hpriv = filp->private_data;
97 hl_cb_mgr_fini(hpriv->hdev, &hpriv->cb_mgr);
98 hl_ctx_mgr_fini(hpriv->hdev, &hpriv->ctx_mgr);
100 filp->private_data = NULL;
107 static int hl_device_release_ctrl(struct inode *inode, struct file *filp)
109 struct hl_fpriv *hpriv = filp->private_data;
110 struct hl_device *hdev;
112 filp->private_data = NULL;
116 mutex_lock(&hdev->fpriv_list_lock);
117 list_del(&hpriv->dev_node);
118 mutex_unlock(&hdev->fpriv_list_lock);
126 * hl_mmap - mmap function for habanalabs device
128 * @*filp: pointer to file structure
129 * @*vma: pointer to vm_area_struct of the process
131 * Called when process does an mmap on habanalabs device. Call the device's mmap
132 * function at the end of the common code.
134 static int hl_mmap(struct file *filp, struct vm_area_struct *vma)
136 struct hl_fpriv *hpriv = filp->private_data;
137 unsigned long vm_pgoff;
139 vm_pgoff = vma->vm_pgoff;
140 vma->vm_pgoff = HL_MMAP_OFFSET_VALUE_GET(vm_pgoff);
142 switch (vm_pgoff & HL_MMAP_TYPE_MASK) {
143 case HL_MMAP_TYPE_CB:
144 return hl_cb_mmap(hpriv, vma);
150 static const struct file_operations hl_ops = {
151 .owner = THIS_MODULE,
152 .open = hl_device_open,
153 .release = hl_device_release,
155 .unlocked_ioctl = hl_ioctl,
156 .compat_ioctl = hl_ioctl
159 static const struct file_operations hl_ctrl_ops = {
160 .owner = THIS_MODULE,
161 .open = hl_device_open_ctrl,
162 .release = hl_device_release_ctrl,
163 .unlocked_ioctl = hl_ioctl_control,
164 .compat_ioctl = hl_ioctl_control
167 static void device_release_func(struct device *dev)
173 * device_init_cdev - Initialize cdev and device for habanalabs device
175 * @hdev: pointer to habanalabs device structure
176 * @hclass: pointer to the class object of the device
177 * @minor: minor number of the specific device
178 * @fpos: file operations to install for this device
179 * @name: name of the device as it will appear in the filesystem
180 * @cdev: pointer to the char device object that will be initialized
181 * @dev: pointer to the device object that will be initialized
183 * Initialize a cdev and a Linux device for habanalabs's device.
185 static int device_init_cdev(struct hl_device *hdev, struct class *hclass,
186 int minor, const struct file_operations *fops,
187 char *name, struct cdev *cdev,
190 cdev_init(cdev, fops);
191 cdev->owner = THIS_MODULE;
193 *dev = kzalloc(sizeof(**dev), GFP_KERNEL);
197 device_initialize(*dev);
198 (*dev)->devt = MKDEV(hdev->major, minor);
199 (*dev)->class = hclass;
200 (*dev)->release = device_release_func;
201 dev_set_drvdata(*dev, hdev);
202 dev_set_name(*dev, "%s", name);
207 static int device_cdev_sysfs_add(struct hl_device *hdev)
211 rc = cdev_device_add(&hdev->cdev, hdev->dev);
214 "failed to add a char device to the system\n");
218 rc = cdev_device_add(&hdev->cdev_ctrl, hdev->dev_ctrl);
221 "failed to add a control char device to the system\n");
222 goto delete_cdev_device;
225 /* hl_sysfs_init() must be done after adding the device to the system */
226 rc = hl_sysfs_init(hdev);
228 dev_err(hdev->dev, "failed to initialize sysfs\n");
229 goto delete_ctrl_cdev_device;
232 hdev->cdev_sysfs_created = true;
236 delete_ctrl_cdev_device:
237 cdev_device_del(&hdev->cdev_ctrl, hdev->dev_ctrl);
239 cdev_device_del(&hdev->cdev, hdev->dev);
243 static void device_cdev_sysfs_del(struct hl_device *hdev)
245 if (!hdev->cdev_sysfs_created)
249 cdev_device_del(&hdev->cdev_ctrl, hdev->dev_ctrl);
250 cdev_device_del(&hdev->cdev, hdev->dev);
253 put_device(hdev->dev);
254 put_device(hdev->dev_ctrl);
257 static void device_hard_reset_pending(struct work_struct *work)
259 struct hl_device_reset_work *device_reset_work =
260 container_of(work, struct hl_device_reset_work,
262 struct hl_device *hdev = device_reset_work->hdev;
265 rc = hl_device_reset(hdev, true, true);
266 if ((rc == -EBUSY) && !hdev->device_fini_pending) {
268 "Could not reset device. will try again in %u seconds",
269 HL_PENDING_RESET_PER_SEC);
271 queue_delayed_work(device_reset_work->wq,
272 &device_reset_work->reset_work,
273 msecs_to_jiffies(HL_PENDING_RESET_PER_SEC * 1000));
278 * device_early_init - do some early initialization for the habanalabs device
280 * @hdev: pointer to habanalabs device structure
282 * Install the relevant function pointers and call the early_init function,
283 * if such a function exists
285 static int device_early_init(struct hl_device *hdev)
290 switch (hdev->asic_type) {
292 goya_set_asic_funcs(hdev);
293 strlcpy(hdev->asic_name, "GOYA", sizeof(hdev->asic_name));
296 gaudi_set_asic_funcs(hdev);
297 sprintf(hdev->asic_name, "GAUDI");
300 dev_err(hdev->dev, "Unrecognized ASIC type %d\n",
305 rc = hdev->asic_funcs->early_init(hdev);
309 rc = hl_asid_init(hdev);
313 if (hdev->asic_prop.completion_queues_count) {
314 hdev->cq_wq = kcalloc(hdev->asic_prop.completion_queues_count,
315 sizeof(*hdev->cq_wq),
323 for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++) {
324 snprintf(workq_name, 32, "hl-free-jobs-%u", (u32) i);
325 hdev->cq_wq[i] = create_singlethread_workqueue(workq_name);
326 if (hdev->cq_wq[i] == NULL) {
327 dev_err(hdev->dev, "Failed to allocate CQ workqueue\n");
333 hdev->eq_wq = alloc_workqueue("hl-events", WQ_UNBOUND, 0);
334 if (hdev->eq_wq == NULL) {
335 dev_err(hdev->dev, "Failed to allocate EQ workqueue\n");
340 hdev->hl_chip_info = kzalloc(sizeof(struct hwmon_chip_info),
342 if (!hdev->hl_chip_info) {
347 hdev->idle_busy_ts_arr = kmalloc_array(HL_IDLE_BUSY_TS_ARR_SIZE,
348 sizeof(struct hl_device_idle_busy_ts),
349 (GFP_KERNEL | __GFP_ZERO));
350 if (!hdev->idle_busy_ts_arr) {
355 rc = hl_mmu_if_set_funcs(hdev);
357 goto free_idle_busy_ts_arr;
359 hl_cb_mgr_init(&hdev->kernel_cb_mgr);
361 hdev->device_reset_work.wq =
362 create_singlethread_workqueue("hl_device_reset");
363 if (!hdev->device_reset_work.wq) {
365 dev_err(hdev->dev, "Failed to create device reset WQ\n");
369 INIT_DELAYED_WORK(&hdev->device_reset_work.reset_work,
370 device_hard_reset_pending);
371 hdev->device_reset_work.hdev = hdev;
372 hdev->device_fini_pending = 0;
374 mutex_init(&hdev->send_cpu_message_lock);
375 mutex_init(&hdev->debug_lock);
376 INIT_LIST_HEAD(&hdev->cs_mirror_list);
377 spin_lock_init(&hdev->cs_mirror_lock);
378 INIT_LIST_HEAD(&hdev->fpriv_list);
379 mutex_init(&hdev->fpriv_list_lock);
380 atomic_set(&hdev->in_reset, 0);
385 hl_cb_mgr_fini(hdev, &hdev->kernel_cb_mgr);
386 free_idle_busy_ts_arr:
387 kfree(hdev->idle_busy_ts_arr);
389 kfree(hdev->hl_chip_info);
391 destroy_workqueue(hdev->eq_wq);
393 for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
395 destroy_workqueue(hdev->cq_wq[i]);
400 if (hdev->asic_funcs->early_fini)
401 hdev->asic_funcs->early_fini(hdev);
407 * device_early_fini - finalize all that was done in device_early_init
409 * @hdev: pointer to habanalabs device structure
412 static void device_early_fini(struct hl_device *hdev)
416 mutex_destroy(&hdev->debug_lock);
417 mutex_destroy(&hdev->send_cpu_message_lock);
419 mutex_destroy(&hdev->fpriv_list_lock);
421 hl_cb_mgr_fini(hdev, &hdev->kernel_cb_mgr);
423 kfree(hdev->idle_busy_ts_arr);
424 kfree(hdev->hl_chip_info);
426 destroy_workqueue(hdev->eq_wq);
427 destroy_workqueue(hdev->device_reset_work.wq);
429 for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
430 destroy_workqueue(hdev->cq_wq[i]);
435 if (hdev->asic_funcs->early_fini)
436 hdev->asic_funcs->early_fini(hdev);
439 static void set_freq_to_low_job(struct work_struct *work)
441 struct hl_device *hdev = container_of(work, struct hl_device,
444 mutex_lock(&hdev->fpriv_list_lock);
446 if (!hdev->compute_ctx)
447 hl_device_set_frequency(hdev, PLL_LOW);
449 mutex_unlock(&hdev->fpriv_list_lock);
451 schedule_delayed_work(&hdev->work_freq,
452 usecs_to_jiffies(HL_PLL_LOW_JOB_FREQ_USEC));
455 static void hl_device_heartbeat(struct work_struct *work)
457 struct hl_device *hdev = container_of(work, struct hl_device,
458 work_heartbeat.work);
460 if (!hl_device_operational(hdev, NULL))
463 if (!hdev->asic_funcs->send_heartbeat(hdev))
466 dev_err(hdev->dev, "Device heartbeat failed!\n");
467 hl_device_reset(hdev, true, false);
472 schedule_delayed_work(&hdev->work_heartbeat,
473 usecs_to_jiffies(HL_HEARTBEAT_PER_USEC));
477 * device_late_init - do late stuff initialization for the habanalabs device
479 * @hdev: pointer to habanalabs device structure
481 * Do stuff that either needs the device H/W queues to be active or needs
482 * to happen after all the rest of the initialization is finished
484 static int device_late_init(struct hl_device *hdev)
488 if (hdev->asic_funcs->late_init) {
489 rc = hdev->asic_funcs->late_init(hdev);
492 "failed late initialization for the H/W\n");
497 hdev->high_pll = hdev->asic_prop.high_pll;
499 /* force setting to low frequency */
500 hdev->curr_pll_profile = PLL_LOW;
502 if (hdev->pm_mng_profile == PM_AUTO)
503 hdev->asic_funcs->set_pll_profile(hdev, PLL_LOW);
505 hdev->asic_funcs->set_pll_profile(hdev, PLL_LAST);
507 INIT_DELAYED_WORK(&hdev->work_freq, set_freq_to_low_job);
508 schedule_delayed_work(&hdev->work_freq,
509 usecs_to_jiffies(HL_PLL_LOW_JOB_FREQ_USEC));
511 if (hdev->heartbeat) {
512 INIT_DELAYED_WORK(&hdev->work_heartbeat, hl_device_heartbeat);
513 schedule_delayed_work(&hdev->work_heartbeat,
514 usecs_to_jiffies(HL_HEARTBEAT_PER_USEC));
517 hdev->late_init_done = true;
523 * device_late_fini - finalize all that was done in device_late_init
525 * @hdev: pointer to habanalabs device structure
528 static void device_late_fini(struct hl_device *hdev)
530 if (!hdev->late_init_done)
533 cancel_delayed_work_sync(&hdev->work_freq);
535 cancel_delayed_work_sync(&hdev->work_heartbeat);
537 if (hdev->asic_funcs->late_fini)
538 hdev->asic_funcs->late_fini(hdev);
540 hdev->late_init_done = false;
543 uint32_t hl_device_utilization(struct hl_device *hdev, uint32_t period_ms)
545 struct hl_device_idle_busy_ts *ts;
546 ktime_t zero_ktime, curr = ktime_get();
547 u32 overlap_cnt = 0, last_index = hdev->idle_busy_ts_idx;
548 s64 period_us, last_start_us, last_end_us, last_busy_time_us,
549 total_busy_time_us = 0, total_busy_time_ms;
551 zero_ktime = ktime_set(0, 0);
552 period_us = period_ms * USEC_PER_MSEC;
553 ts = &hdev->idle_busy_ts_arr[last_index];
555 /* check case that device is currently in idle */
556 if (!ktime_compare(ts->busy_to_idle_ts, zero_ktime) &&
557 !ktime_compare(ts->idle_to_busy_ts, zero_ktime)) {
560 /* Handle case idle_busy_ts_idx was 0 */
561 if (last_index > HL_IDLE_BUSY_TS_ARR_SIZE)
562 last_index = HL_IDLE_BUSY_TS_ARR_SIZE - 1;
564 ts = &hdev->idle_busy_ts_arr[last_index];
567 while (overlap_cnt < HL_IDLE_BUSY_TS_ARR_SIZE) {
568 /* Check if we are in last sample case. i.e. if the sample
569 * begun before the sampling period. This could be a real
570 * sample or 0 so need to handle both cases
572 last_start_us = ktime_to_us(
573 ktime_sub(curr, ts->idle_to_busy_ts));
575 if (last_start_us > period_us) {
577 /* First check two cases:
578 * 1. If the device is currently busy
579 * 2. If the device was idle during the whole sampling
583 if (!ktime_compare(ts->busy_to_idle_ts, zero_ktime)) {
584 /* Check if the device is currently busy */
585 if (ktime_compare(ts->idle_to_busy_ts,
589 /* We either didn't have any activity or we
590 * reached an entry which is 0. Either way,
591 * exit and return what was accumulated so far
596 /* If sample has finished, check it is relevant */
597 last_end_us = ktime_to_us(
598 ktime_sub(curr, ts->busy_to_idle_ts));
600 if (last_end_us > period_us)
603 /* It is relevant so add it but with adjustment */
604 last_busy_time_us = ktime_to_us(
605 ktime_sub(ts->busy_to_idle_ts,
606 ts->idle_to_busy_ts));
607 total_busy_time_us += last_busy_time_us -
608 (last_start_us - period_us);
612 /* Check if the sample is finished or still open */
613 if (ktime_compare(ts->busy_to_idle_ts, zero_ktime))
614 last_busy_time_us = ktime_to_us(
615 ktime_sub(ts->busy_to_idle_ts,
616 ts->idle_to_busy_ts));
618 last_busy_time_us = ktime_to_us(
619 ktime_sub(curr, ts->idle_to_busy_ts));
621 total_busy_time_us += last_busy_time_us;
624 /* Handle case idle_busy_ts_idx was 0 */
625 if (last_index > HL_IDLE_BUSY_TS_ARR_SIZE)
626 last_index = HL_IDLE_BUSY_TS_ARR_SIZE - 1;
628 ts = &hdev->idle_busy_ts_arr[last_index];
633 total_busy_time_ms = DIV_ROUND_UP_ULL(total_busy_time_us,
636 return DIV_ROUND_UP_ULL(total_busy_time_ms * 100, period_ms);
640 * hl_device_set_frequency - set the frequency of the device
642 * @hdev: pointer to habanalabs device structure
643 * @freq: the new frequency value
645 * Change the frequency if needed. This function has no protection against
646 * concurrency, therefore it is assumed that the calling function has protected
647 * itself against the case of calling this function from multiple threads with
650 * Returns 0 if no change was done, otherwise returns 1
652 int hl_device_set_frequency(struct hl_device *hdev, enum hl_pll_frequency freq)
654 if ((hdev->pm_mng_profile == PM_MANUAL) ||
655 (hdev->curr_pll_profile == freq))
658 dev_dbg(hdev->dev, "Changing device frequency to %s\n",
659 freq == PLL_HIGH ? "high" : "low");
661 hdev->asic_funcs->set_pll_profile(hdev, freq);
663 hdev->curr_pll_profile = freq;
668 int hl_device_set_debug_mode(struct hl_device *hdev, bool enable)
672 mutex_lock(&hdev->debug_lock);
675 if (!hdev->in_debug) {
677 "Failed to disable debug mode because device was not in debug mode\n");
682 if (!hdev->hard_reset_pending)
683 hdev->asic_funcs->halt_coresight(hdev);
687 if (!hdev->hard_reset_pending)
688 hdev->asic_funcs->set_clock_gating(hdev);
693 if (hdev->in_debug) {
695 "Failed to enable debug mode because device is already in debug mode\n");
700 hdev->asic_funcs->disable_clock_gating(hdev);
704 mutex_unlock(&hdev->debug_lock);
710 * hl_device_suspend - initiate device suspend
712 * @hdev: pointer to habanalabs device structure
714 * Puts the hw in the suspend state (all asics).
715 * Returns 0 for success or an error on failure.
716 * Called at driver suspend.
718 int hl_device_suspend(struct hl_device *hdev)
722 pci_save_state(hdev->pdev);
724 /* Block future CS/VM/JOB completion operations */
725 rc = atomic_cmpxchg(&hdev->in_reset, 0, 1);
727 dev_err(hdev->dev, "Can't suspend while in reset\n");
731 /* This blocks all other stuff that is not blocked by in_reset */
732 hdev->disabled = true;
735 * Flush anyone that is inside the critical section of enqueue
738 hdev->asic_funcs->hw_queues_lock(hdev);
739 hdev->asic_funcs->hw_queues_unlock(hdev);
741 /* Flush processes that are sending message to CPU */
742 mutex_lock(&hdev->send_cpu_message_lock);
743 mutex_unlock(&hdev->send_cpu_message_lock);
745 rc = hdev->asic_funcs->suspend(hdev);
748 "Failed to disable PCI access of device CPU\n");
750 /* Shut down the device */
751 pci_disable_device(hdev->pdev);
752 pci_set_power_state(hdev->pdev, PCI_D3hot);
758 * hl_device_resume - initiate device resume
760 * @hdev: pointer to habanalabs device structure
762 * Bring the hw back to operating state (all asics).
763 * Returns 0 for success or an error on failure.
764 * Called at driver resume.
766 int hl_device_resume(struct hl_device *hdev)
770 pci_set_power_state(hdev->pdev, PCI_D0);
771 pci_restore_state(hdev->pdev);
772 rc = pci_enable_device_mem(hdev->pdev);
775 "Failed to enable PCI device in resume\n");
779 pci_set_master(hdev->pdev);
781 rc = hdev->asic_funcs->resume(hdev);
783 dev_err(hdev->dev, "Failed to resume device after suspend\n");
788 hdev->disabled = false;
789 atomic_set(&hdev->in_reset, 0);
791 rc = hl_device_reset(hdev, true, false);
793 dev_err(hdev->dev, "Failed to reset device during resume\n");
800 pci_clear_master(hdev->pdev);
801 pci_disable_device(hdev->pdev);
806 static int device_kill_open_processes(struct hl_device *hdev, u32 timeout)
808 struct hl_fpriv *hpriv;
809 struct task_struct *task = NULL;
813 /* Giving time for user to close FD, and for processes that are inside
814 * hl_device_open to finish
816 if (!list_empty(&hdev->fpriv_list))
820 pending_cnt = timeout;
822 if (hdev->process_kill_trial_cnt) {
823 /* Processes have been already killed */
825 goto wait_for_processes;
827 /* Wait a small period after process kill */
828 pending_cnt = HL_PENDING_RESET_PER_SEC;
832 mutex_lock(&hdev->fpriv_list_lock);
834 /* This section must be protected because we are dereferencing
835 * pointers that are freed if the process exits
837 list_for_each_entry(hpriv, &hdev->fpriv_list, dev_node) {
838 task = get_pid_task(hpriv->taskpid, PIDTYPE_PID);
840 dev_info(hdev->dev, "Killing user process pid=%d\n",
842 send_sig(SIGKILL, task, 1);
843 usleep_range(1000, 10000);
845 put_task_struct(task);
849 mutex_unlock(&hdev->fpriv_list_lock);
852 * We killed the open users, but that doesn't mean they are closed.
853 * It could be that they are running a long cleanup phase in the driver
854 * e.g. MMU unmappings, or running other long teardown flow even before
856 * Therefore we need to wait again to make sure they are closed before
857 * continuing with the reset.
861 while ((!list_empty(&hdev->fpriv_list)) && (pending_cnt)) {
863 "Waiting for all unmap operations to finish before hard reset\n");
870 /* All processes exited successfully */
871 if (list_empty(&hdev->fpriv_list))
874 /* Give up waiting for processes to exit */
875 if (hdev->process_kill_trial_cnt == HL_PENDING_RESET_MAX_TRIALS)
878 hdev->process_kill_trial_cnt++;
884 * hl_device_reset - reset the device
886 * @hdev: pointer to habanalabs device structure
887 * @hard_reset: should we do hard reset to all engines or just reset the
888 * compute/dma engines
889 * @from_hard_reset_thread: is the caller the hard-reset thread
891 * Block future CS and wait for pending CS to be enqueued
893 * Flush all completions
894 * Re-initialize all internal data structures
895 * Call ASIC H/W init, late_init
899 * Returns 0 for success or an error on failure.
901 int hl_device_reset(struct hl_device *hdev, bool hard_reset,
902 bool from_hard_reset_thread)
906 if (!hdev->init_done) {
908 "Can't reset before initialization is done\n");
912 if ((!hard_reset) && (!hdev->supports_soft_reset)) {
913 dev_dbg(hdev->dev, "Doing hard-reset instead of soft-reset\n");
917 /* Re-entry of reset thread */
918 if (from_hard_reset_thread && hdev->process_kill_trial_cnt)
922 * Prevent concurrency in this function - only one reset should be
923 * done at any given time. Only need to perform this if we didn't
924 * get from the dedicated hard reset thread
926 if (!from_hard_reset_thread) {
927 /* Block future CS/VM/JOB completion operations */
928 rc = atomic_cmpxchg(&hdev->in_reset, 0, 1);
933 /* Disable PCI access from device F/W so he won't send
934 * us additional interrupts. We disable MSI/MSI-X at
935 * the halt_engines function and we can't have the F/W
936 * sending us interrupts after that. We need to disable
937 * the access here because if the device is marked
938 * disable, the message won't be send. Also, in case
939 * of heartbeat, the device CPU is marked as disable
940 * so this message won't be sent
942 if (hl_fw_send_pci_access_msg(hdev,
943 CPUCP_PACKET_DISABLE_PCI_ACCESS))
945 "Failed to disable PCI access by F/W\n");
948 /* This also blocks future CS/VM/JOB completion operations */
949 hdev->disabled = true;
951 /* Flush anyone that is inside the critical section of enqueue
954 hdev->asic_funcs->hw_queues_lock(hdev);
955 hdev->asic_funcs->hw_queues_unlock(hdev);
957 /* Flush anyone that is inside device open */
958 mutex_lock(&hdev->fpriv_list_lock);
959 mutex_unlock(&hdev->fpriv_list_lock);
961 dev_err(hdev->dev, "Going to RESET device!\n");
965 if ((hard_reset) && (!from_hard_reset_thread)) {
966 hdev->hard_reset_pending = true;
968 hdev->process_kill_trial_cnt = 0;
971 * Because the reset function can't run from interrupt or
972 * from heartbeat work, we need to call the reset function
973 * from a dedicated work
975 queue_delayed_work(hdev->device_reset_work.wq,
976 &hdev->device_reset_work.reset_work, 0);
982 device_late_fini(hdev);
985 * Now that the heartbeat thread is closed, flush processes
986 * which are sending messages to CPU
988 mutex_lock(&hdev->send_cpu_message_lock);
989 mutex_unlock(&hdev->send_cpu_message_lock);
993 * Halt the engines and disable interrupts so we won't get any more
994 * completions from H/W and we won't have any accesses from the
995 * H/W to the host machine
997 hdev->asic_funcs->halt_engines(hdev, hard_reset);
999 /* Go over all the queues, release all CS and their jobs */
1000 hl_cs_rollback_all(hdev);
1004 /* Kill processes here after CS rollback. This is because the
1005 * process can't really exit until all its CSs are done, which
1006 * is what we do in cs rollback
1008 rc = device_kill_open_processes(hdev, 0);
1011 if (hdev->device_fini_pending) {
1013 "Failed to kill all open processes, stopping hard reset\n");
1017 /* signal reset thread to reschedule */
1023 "Failed to kill all open processes, stopping hard reset\n");
1027 /* Flush the Event queue workers to make sure no other thread is
1028 * reading or writing to registers during the reset
1030 flush_workqueue(hdev->eq_wq);
1033 /* Reset the H/W. It will be in idle state after this returns */
1034 hdev->asic_funcs->hw_fini(hdev, hard_reset);
1037 /* Release kernel context */
1038 if (hdev->kernel_ctx && hl_ctx_put(hdev->kernel_ctx) == 1)
1039 hdev->kernel_ctx = NULL;
1042 hl_eq_reset(hdev, &hdev->event_queue);
1045 /* Re-initialize PI,CI to 0 in all queues (hw queue, cq) */
1046 hl_hw_queue_reset(hdev, hard_reset);
1047 for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
1048 hl_cq_reset(hdev, &hdev->completion_queue[i]);
1050 hdev->idle_busy_ts_idx = 0;
1051 hdev->idle_busy_ts_arr[0].busy_to_idle_ts = ktime_set(0, 0);
1052 hdev->idle_busy_ts_arr[0].idle_to_busy_ts = ktime_set(0, 0);
1054 if (hdev->cs_active_cnt)
1055 dev_crit(hdev->dev, "CS active cnt %d is not 0 during reset\n",
1056 hdev->cs_active_cnt);
1058 mutex_lock(&hdev->fpriv_list_lock);
1060 /* Make sure the context switch phase will run again */
1061 if (hdev->compute_ctx) {
1062 atomic_set(&hdev->compute_ctx->thread_ctx_switch_token, 1);
1063 hdev->compute_ctx->thread_ctx_switch_wait_token = 0;
1066 mutex_unlock(&hdev->fpriv_list_lock);
1068 /* Finished tear-down, starting to re-initialize */
1071 hdev->device_cpu_disabled = false;
1072 hdev->hard_reset_pending = false;
1074 if (hdev->kernel_ctx) {
1076 "kernel ctx was alive during hard reset, something is terribly wrong\n");
1081 rc = hl_mmu_init(hdev);
1084 "Failed to initialize MMU S/W after hard reset\n");
1088 /* Allocate the kernel context */
1089 hdev->kernel_ctx = kzalloc(sizeof(*hdev->kernel_ctx),
1091 if (!hdev->kernel_ctx) {
1097 hdev->compute_ctx = NULL;
1099 rc = hl_ctx_init(hdev, hdev->kernel_ctx, true);
1102 "failed to init kernel ctx in hard reset\n");
1103 kfree(hdev->kernel_ctx);
1104 hdev->kernel_ctx = NULL;
1110 /* Device is now enabled as part of the initialization requires
1111 * communication with the device firmware to get information that
1112 * is required for the initialization itself
1114 hdev->disabled = false;
1116 rc = hdev->asic_funcs->hw_init(hdev);
1119 "failed to initialize the H/W after reset\n");
1123 /* Check that the communication with the device is working */
1124 rc = hdev->asic_funcs->test_queues(hdev);
1127 "Failed to detect if device is alive after reset\n");
1132 rc = device_late_init(hdev);
1135 "Failed late init after hard reset\n");
1139 rc = hl_vm_init(hdev);
1142 "Failed to init memory module after hard reset\n");
1146 hl_set_max_power(hdev);
1148 rc = hdev->asic_funcs->soft_reset_late_init(hdev);
1151 "Failed late init after soft reset\n");
1156 atomic_set(&hdev->in_reset, 0);
1157 hdev->needs_reset = false;
1160 hdev->hard_reset_cnt++;
1162 hdev->soft_reset_cnt++;
1164 dev_warn(hdev->dev, "Successfully finished resetting the device\n");
1169 hdev->disabled = true;
1173 "Failed to reset! Device is NOT usable\n");
1174 hdev->hard_reset_cnt++;
1177 "Failed to do soft-reset, trying hard reset\n");
1178 hdev->soft_reset_cnt++;
1183 atomic_set(&hdev->in_reset, 0);
1189 * hl_device_init - main initialization function for habanalabs device
1191 * @hdev: pointer to habanalabs device structure
1193 * Allocate an id for the device, do early initialization and then call the
1194 * ASIC specific initialization functions. Finally, create the cdev and the
1195 * Linux device to expose it to the user
1197 int hl_device_init(struct hl_device *hdev, struct class *hclass)
1199 int i, rc, cq_cnt, cq_ready_cnt;
1201 bool add_cdev_sysfs_on_err = false;
1203 name = kasprintf(GFP_KERNEL, "hl%d", hdev->id / 2);
1209 /* Initialize cdev and device structures */
1210 rc = device_init_cdev(hdev, hclass, hdev->id, &hl_ops, name,
1211 &hdev->cdev, &hdev->dev);
1218 name = kasprintf(GFP_KERNEL, "hl_controlD%d", hdev->id / 2);
1224 /* Initialize cdev and device structures for control device */
1225 rc = device_init_cdev(hdev, hclass, hdev->id_control, &hl_ctrl_ops,
1226 name, &hdev->cdev_ctrl, &hdev->dev_ctrl);
1233 /* Initialize ASIC function pointers and perform early init */
1234 rc = device_early_init(hdev);
1239 * Start calling ASIC initialization. First S/W then H/W and finally
1242 rc = hdev->asic_funcs->sw_init(hdev);
1247 * Initialize the H/W queues. Must be done before hw_init, because
1248 * there the addresses of the kernel queue are being written to the
1249 * registers of the device
1251 rc = hl_hw_queues_create(hdev);
1253 dev_err(hdev->dev, "failed to initialize kernel queues\n");
1257 cq_cnt = hdev->asic_prop.completion_queues_count;
1260 * Initialize the completion queues. Must be done before hw_init,
1261 * because there the addresses of the completion queues are being
1262 * passed as arguments to request_irq
1265 hdev->completion_queue = kcalloc(cq_cnt,
1266 sizeof(*hdev->completion_queue),
1269 if (!hdev->completion_queue) {
1271 "failed to allocate completion queues\n");
1273 goto hw_queues_destroy;
1277 for (i = 0, cq_ready_cnt = 0 ; i < cq_cnt ; i++, cq_ready_cnt++) {
1278 rc = hl_cq_init(hdev, &hdev->completion_queue[i],
1279 hdev->asic_funcs->get_queue_id_for_cq(hdev, i));
1282 "failed to initialize completion queue\n");
1285 hdev->completion_queue[i].cq_idx = i;
1289 * Initialize the event queue. Must be done before hw_init,
1290 * because there the address of the event queue is being
1291 * passed as argument to request_irq
1293 rc = hl_eq_init(hdev, &hdev->event_queue);
1295 dev_err(hdev->dev, "failed to initialize event queue\n");
1299 /* MMU S/W must be initialized before kernel context is created */
1300 rc = hl_mmu_init(hdev);
1302 dev_err(hdev->dev, "Failed to initialize MMU S/W structures\n");
1306 /* Allocate the kernel context */
1307 hdev->kernel_ctx = kzalloc(sizeof(*hdev->kernel_ctx), GFP_KERNEL);
1308 if (!hdev->kernel_ctx) {
1313 hdev->compute_ctx = NULL;
1315 hl_debugfs_add_device(hdev);
1317 /* debugfs nodes are created in hl_ctx_init so it must be called after
1318 * hl_debugfs_add_device.
1320 rc = hl_ctx_init(hdev, hdev->kernel_ctx, true);
1322 dev_err(hdev->dev, "failed to initialize kernel context\n");
1323 kfree(hdev->kernel_ctx);
1324 goto remove_device_from_debugfs;
1327 rc = hl_cb_pool_init(hdev);
1329 dev_err(hdev->dev, "failed to initialize CB pool\n");
1334 * From this point, in case of an error, add char devices and create
1335 * sysfs nodes as part of the error flow, to allow debugging.
1337 add_cdev_sysfs_on_err = true;
1339 /* Device is now enabled as part of the initialization requires
1340 * communication with the device firmware to get information that
1341 * is required for the initialization itself
1343 hdev->disabled = false;
1345 rc = hdev->asic_funcs->hw_init(hdev);
1347 dev_err(hdev->dev, "failed to initialize the H/W\n");
1352 /* Check that the communication with the device is working */
1353 rc = hdev->asic_funcs->test_queues(hdev);
1355 dev_err(hdev->dev, "Failed to detect if device is alive\n");
1360 rc = device_late_init(hdev);
1362 dev_err(hdev->dev, "Failed late initialization\n");
1367 dev_info(hdev->dev, "Found %s device with %lluGB DRAM\n",
1369 hdev->asic_prop.dram_size / 1024 / 1024 / 1024);
1371 rc = hl_vm_init(hdev);
1373 dev_err(hdev->dev, "Failed to initialize memory module\n");
1379 * Expose devices and sysfs nodes to user.
1380 * From here there is no need to add char devices and create sysfs nodes
1381 * in case of an error.
1383 add_cdev_sysfs_on_err = false;
1384 rc = device_cdev_sysfs_add(hdev);
1387 "Failed to add char devices and sysfs nodes\n");
1392 /* Need to call this again because the max power might change,
1393 * depending on card type for certain ASICs
1395 hl_set_max_power(hdev);
1398 * hl_hwmon_init() must be called after device_late_init(), because only
1399 * there we get the information from the device about which
1400 * hwmon-related sensors the device supports.
1401 * Furthermore, it must be done after adding the device to the system.
1403 rc = hl_hwmon_init(hdev);
1405 dev_err(hdev->dev, "Failed to initialize hwmon\n");
1410 dev_notice(hdev->dev,
1411 "Successfully added device to habanalabs driver\n");
1413 hdev->init_done = true;
1418 if (hl_ctx_put(hdev->kernel_ctx) != 1)
1420 "kernel ctx is still alive on initialization failure\n");
1421 remove_device_from_debugfs:
1422 hl_debugfs_remove_device(hdev);
1426 hl_eq_fini(hdev, &hdev->event_queue);
1428 for (i = 0 ; i < cq_ready_cnt ; i++)
1429 hl_cq_fini(hdev, &hdev->completion_queue[i]);
1430 kfree(hdev->completion_queue);
1432 hl_hw_queues_destroy(hdev);
1434 hdev->asic_funcs->sw_fini(hdev);
1436 device_early_fini(hdev);
1438 put_device(hdev->dev_ctrl);
1440 put_device(hdev->dev);
1442 hdev->disabled = true;
1443 if (add_cdev_sysfs_on_err)
1444 device_cdev_sysfs_add(hdev);
1446 dev_err(&hdev->pdev->dev,
1447 "Failed to initialize hl%d. Device is NOT usable !\n",
1450 pr_err("Failed to initialize hl%d. Device is NOT usable !\n",
1457 * hl_device_fini - main tear-down function for habanalabs device
1459 * @hdev: pointer to habanalabs device structure
1461 * Destroy the device, call ASIC fini functions and release the id
1463 void hl_device_fini(struct hl_device *hdev)
1468 dev_info(hdev->dev, "Removing device\n");
1470 hdev->device_fini_pending = 1;
1471 flush_delayed_work(&hdev->device_reset_work.reset_work);
1474 * This function is competing with the reset function, so try to
1475 * take the reset atomic and if we are already in middle of reset,
1476 * wait until reset function is finished. Reset function is designed
1477 * to always finish. However, in Gaudi, because of all the network
1478 * ports, the hard reset could take between 10-30 seconds
1481 timeout = ktime_add_us(ktime_get(),
1482 HL_HARD_RESET_MAX_TIMEOUT * 1000 * 1000);
1483 rc = atomic_cmpxchg(&hdev->in_reset, 0, 1);
1485 usleep_range(50, 200);
1486 rc = atomic_cmpxchg(&hdev->in_reset, 0, 1);
1487 if (ktime_compare(ktime_get(), timeout) > 0) {
1489 "Failed to remove device because reset function did not finish\n");
1494 /* Disable PCI access from device F/W so it won't send us additional
1495 * interrupts. We disable MSI/MSI-X at the halt_engines function and we
1496 * can't have the F/W sending us interrupts after that. We need to
1497 * disable the access here because if the device is marked disable, the
1498 * message won't be send. Also, in case of heartbeat, the device CPU is
1499 * marked as disable so this message won't be sent
1501 hl_fw_send_pci_access_msg(hdev, CPUCP_PACKET_DISABLE_PCI_ACCESS);
1503 /* Mark device as disabled */
1504 hdev->disabled = true;
1506 /* Flush anyone that is inside the critical section of enqueue
1509 hdev->asic_funcs->hw_queues_lock(hdev);
1510 hdev->asic_funcs->hw_queues_unlock(hdev);
1512 /* Flush anyone that is inside device open */
1513 mutex_lock(&hdev->fpriv_list_lock);
1514 mutex_unlock(&hdev->fpriv_list_lock);
1516 hdev->hard_reset_pending = true;
1518 hl_hwmon_fini(hdev);
1520 device_late_fini(hdev);
1523 * Halt the engines and disable interrupts so we won't get any more
1524 * completions from H/W and we won't have any accesses from the
1525 * H/W to the host machine
1527 hdev->asic_funcs->halt_engines(hdev, true);
1529 /* Go over all the queues, release all CS and their jobs */
1530 hl_cs_rollback_all(hdev);
1532 /* Kill processes here after CS rollback. This is because the process
1533 * can't really exit until all its CSs are done, which is what we
1537 "Waiting for all processes to exit (timeout of %u seconds)",
1538 HL_PENDING_RESET_LONG_SEC);
1540 rc = device_kill_open_processes(hdev, HL_PENDING_RESET_LONG_SEC);
1542 dev_crit(hdev->dev, "Failed to kill all open processes\n");
1544 hl_cb_pool_fini(hdev);
1546 /* Reset the H/W. It will be in idle state after this returns */
1547 hdev->asic_funcs->hw_fini(hdev, true);
1549 /* Release kernel context */
1550 if ((hdev->kernel_ctx) && (hl_ctx_put(hdev->kernel_ctx) != 1))
1551 dev_err(hdev->dev, "kernel ctx is still alive\n");
1553 hl_debugfs_remove_device(hdev);
1559 hl_eq_fini(hdev, &hdev->event_queue);
1561 for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
1562 hl_cq_fini(hdev, &hdev->completion_queue[i]);
1563 kfree(hdev->completion_queue);
1565 hl_hw_queues_destroy(hdev);
1567 /* Call ASIC S/W finalize function */
1568 hdev->asic_funcs->sw_fini(hdev);
1570 device_early_fini(hdev);
1572 /* Hide devices and sysfs nodes from user */
1573 device_cdev_sysfs_del(hdev);
1575 pr_info("removed device successfully\n");
1579 * MMIO register access helper functions.
1583 * hl_rreg - Read an MMIO register
1585 * @hdev: pointer to habanalabs device structure
1586 * @reg: MMIO register offset (in bytes)
1588 * Returns the value of the MMIO register we are asked to read
1591 inline u32 hl_rreg(struct hl_device *hdev, u32 reg)
1593 return readl(hdev->rmmio + reg);
1597 * hl_wreg - Write to an MMIO register
1599 * @hdev: pointer to habanalabs device structure
1600 * @reg: MMIO register offset (in bytes)
1601 * @val: 32-bit value
1603 * Writes the 32-bit value into the MMIO register
1606 inline void hl_wreg(struct hl_device *hdev, u32 reg, u32 val)
1608 writel(val, hdev->rmmio + reg);