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/sched/signal.h>
14 #include <linux/hwmon.h>
15 #include <uapi/misc/habanalabs.h>
17 #define HL_PLDM_PENDING_RESET_PER_SEC (HL_PENDING_RESET_PER_SEC * 10)
19 bool hl_device_disabled_or_in_reset(struct hl_device *hdev)
21 if ((hdev->disabled) || (atomic_read(&hdev->in_reset)))
27 enum hl_device_status hl_device_status(struct hl_device *hdev)
29 enum hl_device_status status;
32 status = HL_DEVICE_STATUS_MALFUNCTION;
33 else if (atomic_read(&hdev->in_reset))
34 status = HL_DEVICE_STATUS_IN_RESET;
36 status = HL_DEVICE_STATUS_OPERATIONAL;
41 static void hpriv_release(struct kref *ref)
43 struct hl_fpriv *hpriv;
44 struct hl_device *hdev;
46 hpriv = container_of(ref, struct hl_fpriv, refcount);
50 put_pid(hpriv->taskpid);
52 hl_debugfs_remove_file(hpriv);
54 mutex_destroy(&hpriv->restore_phase_mutex);
56 mutex_lock(&hdev->fpriv_list_lock);
57 list_del(&hpriv->dev_node);
58 hdev->compute_ctx = NULL;
59 mutex_unlock(&hdev->fpriv_list_lock);
64 void hl_hpriv_get(struct hl_fpriv *hpriv)
66 kref_get(&hpriv->refcount);
69 void hl_hpriv_put(struct hl_fpriv *hpriv)
71 kref_put(&hpriv->refcount, hpriv_release);
75 * hl_device_release - release function for habanalabs device
77 * @inode: pointer to inode structure
78 * @filp: pointer to file structure
80 * Called when process closes an habanalabs device
82 static int hl_device_release(struct inode *inode, struct file *filp)
84 struct hl_fpriv *hpriv = filp->private_data;
86 hl_cb_mgr_fini(hpriv->hdev, &hpriv->cb_mgr);
87 hl_ctx_mgr_fini(hpriv->hdev, &hpriv->ctx_mgr);
89 filp->private_data = NULL;
96 static int hl_device_release_ctrl(struct inode *inode, struct file *filp)
98 struct hl_fpriv *hpriv = filp->private_data;
99 struct hl_device *hdev;
101 filp->private_data = NULL;
105 mutex_lock(&hdev->fpriv_list_lock);
106 list_del(&hpriv->dev_node);
107 mutex_unlock(&hdev->fpriv_list_lock);
115 * hl_mmap - mmap function for habanalabs device
117 * @*filp: pointer to file structure
118 * @*vma: pointer to vm_area_struct of the process
120 * Called when process does an mmap on habanalabs device. Call the device's mmap
121 * function at the end of the common code.
123 static int hl_mmap(struct file *filp, struct vm_area_struct *vma)
125 struct hl_fpriv *hpriv = filp->private_data;
127 if ((vma->vm_pgoff & HL_MMAP_CB_MASK) == HL_MMAP_CB_MASK) {
128 vma->vm_pgoff ^= HL_MMAP_CB_MASK;
129 return hl_cb_mmap(hpriv, vma);
135 static const struct file_operations hl_ops = {
136 .owner = THIS_MODULE,
137 .open = hl_device_open,
138 .release = hl_device_release,
140 .unlocked_ioctl = hl_ioctl,
141 .compat_ioctl = hl_ioctl
144 static const struct file_operations hl_ctrl_ops = {
145 .owner = THIS_MODULE,
146 .open = hl_device_open_ctrl,
147 .release = hl_device_release_ctrl,
148 .unlocked_ioctl = hl_ioctl_control,
149 .compat_ioctl = hl_ioctl_control
152 static void device_release_func(struct device *dev)
158 * device_init_cdev - Initialize cdev and device for habanalabs device
160 * @hdev: pointer to habanalabs device structure
161 * @hclass: pointer to the class object of the device
162 * @minor: minor number of the specific device
163 * @fpos: file operations to install for this device
164 * @name: name of the device as it will appear in the filesystem
165 * @cdev: pointer to the char device object that will be initialized
166 * @dev: pointer to the device object that will be initialized
168 * Initialize a cdev and a Linux device for habanalabs's device.
170 static int device_init_cdev(struct hl_device *hdev, struct class *hclass,
171 int minor, const struct file_operations *fops,
172 char *name, struct cdev *cdev,
175 cdev_init(cdev, fops);
176 cdev->owner = THIS_MODULE;
178 *dev = kzalloc(sizeof(**dev), GFP_KERNEL);
182 device_initialize(*dev);
183 (*dev)->devt = MKDEV(hdev->major, minor);
184 (*dev)->class = hclass;
185 (*dev)->release = device_release_func;
186 dev_set_drvdata(*dev, hdev);
187 dev_set_name(*dev, "%s", name);
192 static int device_cdev_sysfs_add(struct hl_device *hdev)
196 rc = cdev_device_add(&hdev->cdev, hdev->dev);
199 "failed to add a char device to the system\n");
203 rc = cdev_device_add(&hdev->cdev_ctrl, hdev->dev_ctrl);
206 "failed to add a control char device to the system\n");
207 goto delete_cdev_device;
210 /* hl_sysfs_init() must be done after adding the device to the system */
211 rc = hl_sysfs_init(hdev);
213 dev_err(hdev->dev, "failed to initialize sysfs\n");
214 goto delete_ctrl_cdev_device;
217 hdev->cdev_sysfs_created = true;
221 delete_ctrl_cdev_device:
222 cdev_device_del(&hdev->cdev_ctrl, hdev->dev_ctrl);
224 cdev_device_del(&hdev->cdev, hdev->dev);
228 static void device_cdev_sysfs_del(struct hl_device *hdev)
230 /* device_release() won't be called so must free devices explicitly */
231 if (!hdev->cdev_sysfs_created) {
232 kfree(hdev->dev_ctrl);
238 cdev_device_del(&hdev->cdev_ctrl, hdev->dev_ctrl);
239 cdev_device_del(&hdev->cdev, hdev->dev);
243 * device_early_init - do some early initialization for the habanalabs device
245 * @hdev: pointer to habanalabs device structure
247 * Install the relevant function pointers and call the early_init function,
248 * if such a function exists
250 static int device_early_init(struct hl_device *hdev)
254 switch (hdev->asic_type) {
256 goya_set_asic_funcs(hdev);
257 strlcpy(hdev->asic_name, "GOYA", sizeof(hdev->asic_name));
260 gaudi_set_asic_funcs(hdev);
261 sprintf(hdev->asic_name, "GAUDI");
264 dev_err(hdev->dev, "Unrecognized ASIC type %d\n",
269 rc = hdev->asic_funcs->early_init(hdev);
273 rc = hl_asid_init(hdev);
277 hdev->cq_wq = alloc_workqueue("hl-free-jobs", WQ_UNBOUND, 0);
278 if (hdev->cq_wq == NULL) {
279 dev_err(hdev->dev, "Failed to allocate CQ workqueue\n");
284 hdev->eq_wq = alloc_workqueue("hl-events", WQ_UNBOUND, 0);
285 if (hdev->eq_wq == NULL) {
286 dev_err(hdev->dev, "Failed to allocate EQ workqueue\n");
291 hdev->hl_chip_info = kzalloc(sizeof(struct hwmon_chip_info),
293 if (!hdev->hl_chip_info) {
298 hdev->idle_busy_ts_arr = kmalloc_array(HL_IDLE_BUSY_TS_ARR_SIZE,
299 sizeof(struct hl_device_idle_busy_ts),
300 (GFP_KERNEL | __GFP_ZERO));
301 if (!hdev->idle_busy_ts_arr) {
306 hl_cb_mgr_init(&hdev->kernel_cb_mgr);
308 mutex_init(&hdev->send_cpu_message_lock);
309 mutex_init(&hdev->debug_lock);
310 mutex_init(&hdev->mmu_cache_lock);
311 INIT_LIST_HEAD(&hdev->hw_queues_mirror_list);
312 spin_lock_init(&hdev->hw_queues_mirror_lock);
313 INIT_LIST_HEAD(&hdev->fpriv_list);
314 mutex_init(&hdev->fpriv_list_lock);
315 atomic_set(&hdev->in_reset, 0);
320 kfree(hdev->hl_chip_info);
322 destroy_workqueue(hdev->eq_wq);
324 destroy_workqueue(hdev->cq_wq);
328 if (hdev->asic_funcs->early_fini)
329 hdev->asic_funcs->early_fini(hdev);
335 * device_early_fini - finalize all that was done in device_early_init
337 * @hdev: pointer to habanalabs device structure
340 static void device_early_fini(struct hl_device *hdev)
342 mutex_destroy(&hdev->mmu_cache_lock);
343 mutex_destroy(&hdev->debug_lock);
344 mutex_destroy(&hdev->send_cpu_message_lock);
346 mutex_destroy(&hdev->fpriv_list_lock);
348 hl_cb_mgr_fini(hdev, &hdev->kernel_cb_mgr);
350 kfree(hdev->idle_busy_ts_arr);
351 kfree(hdev->hl_chip_info);
353 destroy_workqueue(hdev->eq_wq);
354 destroy_workqueue(hdev->cq_wq);
358 if (hdev->asic_funcs->early_fini)
359 hdev->asic_funcs->early_fini(hdev);
362 static void set_freq_to_low_job(struct work_struct *work)
364 struct hl_device *hdev = container_of(work, struct hl_device,
367 mutex_lock(&hdev->fpriv_list_lock);
369 if (!hdev->compute_ctx)
370 hl_device_set_frequency(hdev, PLL_LOW);
372 mutex_unlock(&hdev->fpriv_list_lock);
374 schedule_delayed_work(&hdev->work_freq,
375 usecs_to_jiffies(HL_PLL_LOW_JOB_FREQ_USEC));
378 static void hl_device_heartbeat(struct work_struct *work)
380 struct hl_device *hdev = container_of(work, struct hl_device,
381 work_heartbeat.work);
383 if (hl_device_disabled_or_in_reset(hdev))
386 if (!hdev->asic_funcs->send_heartbeat(hdev))
389 dev_err(hdev->dev, "Device heartbeat failed!\n");
390 hl_device_reset(hdev, true, false);
395 schedule_delayed_work(&hdev->work_heartbeat,
396 usecs_to_jiffies(HL_HEARTBEAT_PER_USEC));
400 * device_late_init - do late stuff initialization for the habanalabs device
402 * @hdev: pointer to habanalabs device structure
404 * Do stuff that either needs the device H/W queues to be active or needs
405 * to happen after all the rest of the initialization is finished
407 static int device_late_init(struct hl_device *hdev)
411 if (hdev->asic_funcs->late_init) {
412 rc = hdev->asic_funcs->late_init(hdev);
415 "failed late initialization for the H/W\n");
420 hdev->high_pll = hdev->asic_prop.high_pll;
422 /* force setting to low frequency */
423 hdev->curr_pll_profile = PLL_LOW;
425 if (hdev->pm_mng_profile == PM_AUTO)
426 hdev->asic_funcs->set_pll_profile(hdev, PLL_LOW);
428 hdev->asic_funcs->set_pll_profile(hdev, PLL_LAST);
430 INIT_DELAYED_WORK(&hdev->work_freq, set_freq_to_low_job);
431 schedule_delayed_work(&hdev->work_freq,
432 usecs_to_jiffies(HL_PLL_LOW_JOB_FREQ_USEC));
434 if (hdev->heartbeat) {
435 INIT_DELAYED_WORK(&hdev->work_heartbeat, hl_device_heartbeat);
436 schedule_delayed_work(&hdev->work_heartbeat,
437 usecs_to_jiffies(HL_HEARTBEAT_PER_USEC));
440 hdev->late_init_done = true;
446 * device_late_fini - finalize all that was done in device_late_init
448 * @hdev: pointer to habanalabs device structure
451 static void device_late_fini(struct hl_device *hdev)
453 if (!hdev->late_init_done)
456 cancel_delayed_work_sync(&hdev->work_freq);
458 cancel_delayed_work_sync(&hdev->work_heartbeat);
460 if (hdev->asic_funcs->late_fini)
461 hdev->asic_funcs->late_fini(hdev);
463 hdev->late_init_done = false;
466 uint32_t hl_device_utilization(struct hl_device *hdev, uint32_t period_ms)
468 struct hl_device_idle_busy_ts *ts;
469 ktime_t zero_ktime, curr = ktime_get();
470 u32 overlap_cnt = 0, last_index = hdev->idle_busy_ts_idx;
471 s64 period_us, last_start_us, last_end_us, last_busy_time_us,
472 total_busy_time_us = 0, total_busy_time_ms;
474 zero_ktime = ktime_set(0, 0);
475 period_us = period_ms * USEC_PER_MSEC;
476 ts = &hdev->idle_busy_ts_arr[last_index];
478 /* check case that device is currently in idle */
479 if (!ktime_compare(ts->busy_to_idle_ts, zero_ktime) &&
480 !ktime_compare(ts->idle_to_busy_ts, zero_ktime)) {
483 /* Handle case idle_busy_ts_idx was 0 */
484 if (last_index > HL_IDLE_BUSY_TS_ARR_SIZE)
485 last_index = HL_IDLE_BUSY_TS_ARR_SIZE - 1;
487 ts = &hdev->idle_busy_ts_arr[last_index];
490 while (overlap_cnt < HL_IDLE_BUSY_TS_ARR_SIZE) {
491 /* Check if we are in last sample case. i.e. if the sample
492 * begun before the sampling period. This could be a real
493 * sample or 0 so need to handle both cases
495 last_start_us = ktime_to_us(
496 ktime_sub(curr, ts->idle_to_busy_ts));
498 if (last_start_us > period_us) {
500 /* First check two cases:
501 * 1. If the device is currently busy
502 * 2. If the device was idle during the whole sampling
506 if (!ktime_compare(ts->busy_to_idle_ts, zero_ktime)) {
507 /* Check if the device is currently busy */
508 if (ktime_compare(ts->idle_to_busy_ts,
512 /* We either didn't have any activity or we
513 * reached an entry which is 0. Either way,
514 * exit and return what was accumulated so far
519 /* If sample has finished, check it is relevant */
520 last_end_us = ktime_to_us(
521 ktime_sub(curr, ts->busy_to_idle_ts));
523 if (last_end_us > period_us)
526 /* It is relevant so add it but with adjustment */
527 last_busy_time_us = ktime_to_us(
528 ktime_sub(ts->busy_to_idle_ts,
529 ts->idle_to_busy_ts));
530 total_busy_time_us += last_busy_time_us -
531 (last_start_us - period_us);
535 /* Check if the sample is finished or still open */
536 if (ktime_compare(ts->busy_to_idle_ts, zero_ktime))
537 last_busy_time_us = ktime_to_us(
538 ktime_sub(ts->busy_to_idle_ts,
539 ts->idle_to_busy_ts));
541 last_busy_time_us = ktime_to_us(
542 ktime_sub(curr, ts->idle_to_busy_ts));
544 total_busy_time_us += last_busy_time_us;
547 /* Handle case idle_busy_ts_idx was 0 */
548 if (last_index > HL_IDLE_BUSY_TS_ARR_SIZE)
549 last_index = HL_IDLE_BUSY_TS_ARR_SIZE - 1;
551 ts = &hdev->idle_busy_ts_arr[last_index];
556 total_busy_time_ms = DIV_ROUND_UP_ULL(total_busy_time_us,
559 return DIV_ROUND_UP_ULL(total_busy_time_ms * 100, period_ms);
563 * hl_device_set_frequency - set the frequency of the device
565 * @hdev: pointer to habanalabs device structure
566 * @freq: the new frequency value
568 * Change the frequency if needed. This function has no protection against
569 * concurrency, therefore it is assumed that the calling function has protected
570 * itself against the case of calling this function from multiple threads with
573 * Returns 0 if no change was done, otherwise returns 1
575 int hl_device_set_frequency(struct hl_device *hdev, enum hl_pll_frequency freq)
577 if ((hdev->pm_mng_profile == PM_MANUAL) ||
578 (hdev->curr_pll_profile == freq))
581 dev_dbg(hdev->dev, "Changing device frequency to %s\n",
582 freq == PLL_HIGH ? "high" : "low");
584 hdev->asic_funcs->set_pll_profile(hdev, freq);
586 hdev->curr_pll_profile = freq;
591 int hl_device_set_debug_mode(struct hl_device *hdev, bool enable)
595 mutex_lock(&hdev->debug_lock);
598 if (!hdev->in_debug) {
600 "Failed to disable debug mode because device was not in debug mode\n");
605 if (!hdev->hard_reset_pending)
606 hdev->asic_funcs->halt_coresight(hdev);
610 if (!hdev->hard_reset_pending)
611 hdev->asic_funcs->enable_clock_gating(hdev);
616 if (hdev->in_debug) {
618 "Failed to enable debug mode because device is already in debug mode\n");
623 hdev->asic_funcs->disable_clock_gating(hdev);
627 mutex_unlock(&hdev->debug_lock);
633 * hl_device_suspend - initiate device suspend
635 * @hdev: pointer to habanalabs device structure
637 * Puts the hw in the suspend state (all asics).
638 * Returns 0 for success or an error on failure.
639 * Called at driver suspend.
641 int hl_device_suspend(struct hl_device *hdev)
645 pci_save_state(hdev->pdev);
647 /* Block future CS/VM/JOB completion operations */
648 rc = atomic_cmpxchg(&hdev->in_reset, 0, 1);
650 dev_err(hdev->dev, "Can't suspend while in reset\n");
654 /* This blocks all other stuff that is not blocked by in_reset */
655 hdev->disabled = true;
658 * Flush anyone that is inside the critical section of enqueue
661 hdev->asic_funcs->hw_queues_lock(hdev);
662 hdev->asic_funcs->hw_queues_unlock(hdev);
664 /* Flush processes that are sending message to CPU */
665 mutex_lock(&hdev->send_cpu_message_lock);
666 mutex_unlock(&hdev->send_cpu_message_lock);
668 rc = hdev->asic_funcs->suspend(hdev);
671 "Failed to disable PCI access of device CPU\n");
673 /* Shut down the device */
674 pci_disable_device(hdev->pdev);
675 pci_set_power_state(hdev->pdev, PCI_D3hot);
681 * hl_device_resume - initiate device resume
683 * @hdev: pointer to habanalabs device structure
685 * Bring the hw back to operating state (all asics).
686 * Returns 0 for success or an error on failure.
687 * Called at driver resume.
689 int hl_device_resume(struct hl_device *hdev)
693 pci_set_power_state(hdev->pdev, PCI_D0);
694 pci_restore_state(hdev->pdev);
695 rc = pci_enable_device_mem(hdev->pdev);
698 "Failed to enable PCI device in resume\n");
702 pci_set_master(hdev->pdev);
704 rc = hdev->asic_funcs->resume(hdev);
706 dev_err(hdev->dev, "Failed to resume device after suspend\n");
711 hdev->disabled = false;
712 atomic_set(&hdev->in_reset, 0);
714 rc = hl_device_reset(hdev, true, false);
716 dev_err(hdev->dev, "Failed to reset device during resume\n");
723 pci_clear_master(hdev->pdev);
724 pci_disable_device(hdev->pdev);
729 static int device_kill_open_processes(struct hl_device *hdev)
731 u16 pending_total, pending_cnt;
732 struct hl_fpriv *hpriv;
733 struct task_struct *task = NULL;
736 pending_total = HL_PLDM_PENDING_RESET_PER_SEC;
738 pending_total = HL_PENDING_RESET_PER_SEC;
740 /* Giving time for user to close FD, and for processes that are inside
741 * hl_device_open to finish
743 if (!list_empty(&hdev->fpriv_list))
746 mutex_lock(&hdev->fpriv_list_lock);
748 /* This section must be protected because we are dereferencing
749 * pointers that are freed if the process exits
751 list_for_each_entry(hpriv, &hdev->fpriv_list, dev_node) {
752 task = get_pid_task(hpriv->taskpid, PIDTYPE_PID);
754 dev_info(hdev->dev, "Killing user process pid=%d\n",
756 send_sig(SIGKILL, task, 1);
757 usleep_range(1000, 10000);
759 put_task_struct(task);
763 mutex_unlock(&hdev->fpriv_list_lock);
765 /* We killed the open users, but because the driver cleans up after the
766 * user contexts are closed (e.g. mmu mappings), we need to wait again
767 * to make sure the cleaning phase is finished before continuing with
771 pending_cnt = pending_total;
773 while ((!list_empty(&hdev->fpriv_list)) && (pending_cnt)) {
775 "Waiting for all unmap operations to finish before hard reset\n");
782 return list_empty(&hdev->fpriv_list) ? 0 : -EBUSY;
785 static void device_hard_reset_pending(struct work_struct *work)
787 struct hl_device_reset_work *device_reset_work =
788 container_of(work, struct hl_device_reset_work, reset_work);
789 struct hl_device *hdev = device_reset_work->hdev;
791 hl_device_reset(hdev, true, true);
793 kfree(device_reset_work);
797 * hl_device_reset - reset the device
799 * @hdev: pointer to habanalabs device structure
800 * @hard_reset: should we do hard reset to all engines or just reset the
801 * compute/dma engines
802 * @from_hard_reset_thread: is the caller the hard-reset thread
804 * Block future CS and wait for pending CS to be enqueued
806 * Flush all completions
807 * Re-initialize all internal data structures
808 * Call ASIC H/W init, late_init
812 * Returns 0 for success or an error on failure.
814 int hl_device_reset(struct hl_device *hdev, bool hard_reset,
815 bool from_hard_reset_thread)
819 if (!hdev->init_done) {
821 "Can't reset before initialization is done\n");
825 if ((!hard_reset) && (!hdev->supports_soft_reset)) {
826 dev_dbg(hdev->dev, "Doing hard-reset instead of soft-reset\n");
831 * Prevent concurrency in this function - only one reset should be
832 * done at any given time. Only need to perform this if we didn't
833 * get from the dedicated hard reset thread
835 if (!from_hard_reset_thread) {
836 /* Block future CS/VM/JOB completion operations */
837 rc = atomic_cmpxchg(&hdev->in_reset, 0, 1);
841 /* This also blocks future CS/VM/JOB completion operations */
842 hdev->disabled = true;
844 /* Flush anyone that is inside the critical section of enqueue
847 hdev->asic_funcs->hw_queues_lock(hdev);
848 hdev->asic_funcs->hw_queues_unlock(hdev);
850 /* Flush anyone that is inside device open */
851 mutex_lock(&hdev->fpriv_list_lock);
852 mutex_unlock(&hdev->fpriv_list_lock);
854 dev_err(hdev->dev, "Going to RESET device!\n");
858 if ((hard_reset) && (!from_hard_reset_thread)) {
859 struct hl_device_reset_work *device_reset_work;
861 hdev->hard_reset_pending = true;
863 device_reset_work = kzalloc(sizeof(*device_reset_work),
865 if (!device_reset_work) {
871 * Because the reset function can't run from interrupt or
872 * from heartbeat work, we need to call the reset function
873 * from a dedicated work
875 INIT_WORK(&device_reset_work->reset_work,
876 device_hard_reset_pending);
877 device_reset_work->hdev = hdev;
878 schedule_work(&device_reset_work->reset_work);
884 device_late_fini(hdev);
887 * Now that the heartbeat thread is closed, flush processes
888 * which are sending messages to CPU
890 mutex_lock(&hdev->send_cpu_message_lock);
891 mutex_unlock(&hdev->send_cpu_message_lock);
895 * Halt the engines and disable interrupts so we won't get any more
896 * completions from H/W and we won't have any accesses from the
897 * H/W to the host machine
899 hdev->asic_funcs->halt_engines(hdev, hard_reset);
901 /* Go over all the queues, release all CS and their jobs */
902 hl_cs_rollback_all(hdev);
905 /* Kill processes here after CS rollback. This is because the
906 * process can't really exit until all its CSs are done, which
907 * is what we do in cs rollback
909 rc = device_kill_open_processes(hdev);
912 "Failed to kill all open processes, stopping hard reset\n");
916 /* Flush the Event queue workers to make sure no other thread is
917 * reading or writing to registers during the reset
919 flush_workqueue(hdev->eq_wq);
922 /* Release kernel context */
923 if ((hard_reset) && (hl_ctx_put(hdev->kernel_ctx) == 1))
924 hdev->kernel_ctx = NULL;
926 /* Reset the H/W. It will be in idle state after this returns */
927 hdev->asic_funcs->hw_fini(hdev, hard_reset);
932 hl_eq_reset(hdev, &hdev->event_queue);
935 /* Re-initialize PI,CI to 0 in all queues (hw queue, cq) */
936 hl_hw_queue_reset(hdev, hard_reset);
937 for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
938 hl_cq_reset(hdev, &hdev->completion_queue[i]);
940 hdev->idle_busy_ts_idx = 0;
941 hdev->idle_busy_ts_arr[0].busy_to_idle_ts = ktime_set(0, 0);
942 hdev->idle_busy_ts_arr[0].idle_to_busy_ts = ktime_set(0, 0);
944 if (hdev->cs_active_cnt)
945 dev_crit(hdev->dev, "CS active cnt %d is not 0 during reset\n",
946 hdev->cs_active_cnt);
948 mutex_lock(&hdev->fpriv_list_lock);
950 /* Make sure the context switch phase will run again */
951 if (hdev->compute_ctx) {
952 atomic_set(&hdev->compute_ctx->thread_ctx_switch_token, 1);
953 hdev->compute_ctx->thread_ctx_switch_wait_token = 0;
956 mutex_unlock(&hdev->fpriv_list_lock);
958 /* Finished tear-down, starting to re-initialize */
961 hdev->device_cpu_disabled = false;
962 hdev->hard_reset_pending = false;
964 if (hdev->kernel_ctx) {
966 "kernel ctx was alive during hard reset, something is terribly wrong\n");
971 rc = hl_mmu_init(hdev);
974 "Failed to initialize MMU S/W after hard reset\n");
978 /* Allocate the kernel context */
979 hdev->kernel_ctx = kzalloc(sizeof(*hdev->kernel_ctx),
981 if (!hdev->kernel_ctx) {
986 hdev->compute_ctx = NULL;
988 rc = hl_ctx_init(hdev, hdev->kernel_ctx, true);
991 "failed to init kernel ctx in hard reset\n");
992 kfree(hdev->kernel_ctx);
993 hdev->kernel_ctx = NULL;
998 rc = hdev->asic_funcs->hw_init(hdev);
1001 "failed to initialize the H/W after reset\n");
1005 hdev->disabled = false;
1007 /* Check that the communication with the device is working */
1008 rc = hdev->asic_funcs->test_queues(hdev);
1011 "Failed to detect if device is alive after reset\n");
1016 rc = device_late_init(hdev);
1019 "Failed late init after hard reset\n");
1023 rc = hl_vm_init(hdev);
1026 "Failed to init memory module after hard reset\n");
1030 hl_set_max_power(hdev, hdev->max_power);
1032 rc = hdev->asic_funcs->soft_reset_late_init(hdev);
1035 "Failed late init after soft reset\n");
1040 atomic_set(&hdev->in_reset, 0);
1043 hdev->hard_reset_cnt++;
1045 hdev->soft_reset_cnt++;
1047 dev_warn(hdev->dev, "Successfully finished resetting the device\n");
1052 hdev->disabled = true;
1056 "Failed to reset! Device is NOT usable\n");
1057 hdev->hard_reset_cnt++;
1060 "Failed to do soft-reset, trying hard reset\n");
1061 hdev->soft_reset_cnt++;
1066 atomic_set(&hdev->in_reset, 0);
1072 * hl_device_init - main initialization function for habanalabs device
1074 * @hdev: pointer to habanalabs device structure
1076 * Allocate an id for the device, do early initialization and then call the
1077 * ASIC specific initialization functions. Finally, create the cdev and the
1078 * Linux device to expose it to the user
1080 int hl_device_init(struct hl_device *hdev, struct class *hclass)
1082 int i, rc, cq_cnt, cq_ready_cnt;
1084 bool add_cdev_sysfs_on_err = false;
1086 name = kasprintf(GFP_KERNEL, "hl%d", hdev->id / 2);
1092 /* Initialize cdev and device structures */
1093 rc = device_init_cdev(hdev, hclass, hdev->id, &hl_ops, name,
1094 &hdev->cdev, &hdev->dev);
1101 name = kasprintf(GFP_KERNEL, "hl_controlD%d", hdev->id / 2);
1107 /* Initialize cdev and device structures for control device */
1108 rc = device_init_cdev(hdev, hclass, hdev->id_control, &hl_ctrl_ops,
1109 name, &hdev->cdev_ctrl, &hdev->dev_ctrl);
1116 /* Initialize ASIC function pointers and perform early init */
1117 rc = device_early_init(hdev);
1122 * Start calling ASIC initialization. First S/W then H/W and finally
1125 rc = hdev->asic_funcs->sw_init(hdev);
1130 * Initialize the H/W queues. Must be done before hw_init, because
1131 * there the addresses of the kernel queue are being written to the
1132 * registers of the device
1134 rc = hl_hw_queues_create(hdev);
1136 dev_err(hdev->dev, "failed to initialize kernel queues\n");
1140 cq_cnt = hdev->asic_prop.completion_queues_count;
1143 * Initialize the completion queues. Must be done before hw_init,
1144 * because there the addresses of the completion queues are being
1145 * passed as arguments to request_irq
1147 hdev->completion_queue = kcalloc(cq_cnt,
1148 sizeof(*hdev->completion_queue),
1151 if (!hdev->completion_queue) {
1152 dev_err(hdev->dev, "failed to allocate completion queues\n");
1154 goto hw_queues_destroy;
1157 for (i = 0, cq_ready_cnt = 0 ; i < cq_cnt ; i++, cq_ready_cnt++) {
1158 rc = hl_cq_init(hdev, &hdev->completion_queue[i],
1159 hdev->asic_funcs->get_queue_id_for_cq(hdev, i));
1162 "failed to initialize completion queue\n");
1168 * Initialize the event queue. Must be done before hw_init,
1169 * because there the address of the event queue is being
1170 * passed as argument to request_irq
1172 rc = hl_eq_init(hdev, &hdev->event_queue);
1174 dev_err(hdev->dev, "failed to initialize event queue\n");
1178 /* MMU S/W must be initialized before kernel context is created */
1179 rc = hl_mmu_init(hdev);
1181 dev_err(hdev->dev, "Failed to initialize MMU S/W structures\n");
1185 /* Allocate the kernel context */
1186 hdev->kernel_ctx = kzalloc(sizeof(*hdev->kernel_ctx), GFP_KERNEL);
1187 if (!hdev->kernel_ctx) {
1192 hdev->compute_ctx = NULL;
1194 rc = hl_ctx_init(hdev, hdev->kernel_ctx, true);
1196 dev_err(hdev->dev, "failed to initialize kernel context\n");
1197 kfree(hdev->kernel_ctx);
1201 rc = hl_cb_pool_init(hdev);
1203 dev_err(hdev->dev, "failed to initialize CB pool\n");
1207 hl_debugfs_add_device(hdev);
1209 if (hdev->asic_funcs->get_hw_state(hdev) == HL_DEVICE_HW_STATE_DIRTY) {
1211 "H/W state is dirty, must reset before initializing\n");
1212 hdev->asic_funcs->halt_engines(hdev, true);
1213 hdev->asic_funcs->hw_fini(hdev, true);
1217 * From this point, in case of an error, add char devices and create
1218 * sysfs nodes as part of the error flow, to allow debugging.
1220 add_cdev_sysfs_on_err = true;
1222 rc = hdev->asic_funcs->hw_init(hdev);
1224 dev_err(hdev->dev, "failed to initialize the H/W\n");
1229 hdev->disabled = false;
1231 /* Check that the communication with the device is working */
1232 rc = hdev->asic_funcs->test_queues(hdev);
1234 dev_err(hdev->dev, "Failed to detect if device is alive\n");
1239 rc = device_late_init(hdev);
1241 dev_err(hdev->dev, "Failed late initialization\n");
1246 dev_info(hdev->dev, "Found %s device with %lluGB DRAM\n",
1248 hdev->asic_prop.dram_size / 1024 / 1024 / 1024);
1250 rc = hl_vm_init(hdev);
1252 dev_err(hdev->dev, "Failed to initialize memory module\n");
1258 * Expose devices and sysfs nodes to user.
1259 * From here there is no need to add char devices and create sysfs nodes
1260 * in case of an error.
1262 add_cdev_sysfs_on_err = false;
1263 rc = device_cdev_sysfs_add(hdev);
1266 "Failed to add char devices and sysfs nodes\n");
1272 * hl_hwmon_init() must be called after device_late_init(), because only
1273 * there we get the information from the device about which
1274 * hwmon-related sensors the device supports.
1275 * Furthermore, it must be done after adding the device to the system.
1277 rc = hl_hwmon_init(hdev);
1279 dev_err(hdev->dev, "Failed to initialize hwmon\n");
1284 dev_notice(hdev->dev,
1285 "Successfully added device to habanalabs driver\n");
1287 hdev->init_done = true;
1292 if (hl_ctx_put(hdev->kernel_ctx) != 1)
1294 "kernel ctx is still alive on initialization failure\n");
1298 hl_eq_fini(hdev, &hdev->event_queue);
1300 for (i = 0 ; i < cq_ready_cnt ; i++)
1301 hl_cq_fini(hdev, &hdev->completion_queue[i]);
1302 kfree(hdev->completion_queue);
1304 hl_hw_queues_destroy(hdev);
1306 hdev->asic_funcs->sw_fini(hdev);
1308 device_early_fini(hdev);
1310 kfree(hdev->dev_ctrl);
1314 hdev->disabled = true;
1315 if (add_cdev_sysfs_on_err)
1316 device_cdev_sysfs_add(hdev);
1318 dev_err(&hdev->pdev->dev,
1319 "Failed to initialize hl%d. Device is NOT usable !\n",
1322 pr_err("Failed to initialize hl%d. Device is NOT usable !\n",
1329 * hl_device_fini - main tear-down function for habanalabs device
1331 * @hdev: pointer to habanalabs device structure
1333 * Destroy the device, call ASIC fini functions and release the id
1335 void hl_device_fini(struct hl_device *hdev)
1340 dev_info(hdev->dev, "Removing device\n");
1343 * This function is competing with the reset function, so try to
1344 * take the reset atomic and if we are already in middle of reset,
1345 * wait until reset function is finished. Reset function is designed
1346 * to always finish. However, in Gaudi, because of all the network
1347 * ports, the hard reset could take between 10-30 seconds
1350 timeout = ktime_add_us(ktime_get(),
1351 HL_HARD_RESET_MAX_TIMEOUT * 1000 * 1000);
1352 rc = atomic_cmpxchg(&hdev->in_reset, 0, 1);
1354 usleep_range(50, 200);
1355 rc = atomic_cmpxchg(&hdev->in_reset, 0, 1);
1356 if (ktime_compare(ktime_get(), timeout) > 0) {
1357 WARN(1, "Failed to remove device because reset function did not finish\n");
1362 /* Mark device as disabled */
1363 hdev->disabled = true;
1365 /* Flush anyone that is inside the critical section of enqueue
1368 hdev->asic_funcs->hw_queues_lock(hdev);
1369 hdev->asic_funcs->hw_queues_unlock(hdev);
1371 /* Flush anyone that is inside device open */
1372 mutex_lock(&hdev->fpriv_list_lock);
1373 mutex_unlock(&hdev->fpriv_list_lock);
1375 hdev->hard_reset_pending = true;
1377 hl_hwmon_fini(hdev);
1379 device_late_fini(hdev);
1381 hl_debugfs_remove_device(hdev);
1384 * Halt the engines and disable interrupts so we won't get any more
1385 * completions from H/W and we won't have any accesses from the
1386 * H/W to the host machine
1388 hdev->asic_funcs->halt_engines(hdev, true);
1390 /* Go over all the queues, release all CS and their jobs */
1391 hl_cs_rollback_all(hdev);
1393 /* Kill processes here after CS rollback. This is because the process
1394 * can't really exit until all its CSs are done, which is what we
1397 rc = device_kill_open_processes(hdev);
1399 dev_crit(hdev->dev, "Failed to kill all open processes\n");
1401 hl_cb_pool_fini(hdev);
1403 /* Release kernel context */
1404 if ((hdev->kernel_ctx) && (hl_ctx_put(hdev->kernel_ctx) != 1))
1405 dev_err(hdev->dev, "kernel ctx is still alive\n");
1407 /* Reset the H/W. It will be in idle state after this returns */
1408 hdev->asic_funcs->hw_fini(hdev, true);
1414 hl_eq_fini(hdev, &hdev->event_queue);
1416 for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
1417 hl_cq_fini(hdev, &hdev->completion_queue[i]);
1418 kfree(hdev->completion_queue);
1420 hl_hw_queues_destroy(hdev);
1422 /* Call ASIC S/W finalize function */
1423 hdev->asic_funcs->sw_fini(hdev);
1425 device_early_fini(hdev);
1427 /* Hide devices and sysfs nodes from user */
1428 device_cdev_sysfs_del(hdev);
1430 pr_info("removed device successfully\n");
1434 * MMIO register access helper functions.
1438 * hl_rreg - Read an MMIO register
1440 * @hdev: pointer to habanalabs device structure
1441 * @reg: MMIO register offset (in bytes)
1443 * Returns the value of the MMIO register we are asked to read
1446 inline u32 hl_rreg(struct hl_device *hdev, u32 reg)
1448 return readl(hdev->rmmio + reg);
1452 * hl_wreg - Write to an MMIO register
1454 * @hdev: pointer to habanalabs device structure
1455 * @reg: MMIO register offset (in bytes)
1456 * @val: 32-bit value
1458 * Writes the 32-bit value into the MMIO register
1461 inline void hl_wreg(struct hl_device *hdev, u32 reg, u32 val)
1463 writel(val, hdev->rmmio + reg);