65717e4055da6f406ddbac9124c1387b582dc269
[linux-2.6-microblaze.git] / drivers / misc / habanalabs / habanalabs.h
1 /* SPDX-License-Identifier: GPL-2.0
2  *
3  * Copyright 2016-2019 HabanaLabs, Ltd.
4  * All Rights Reserved.
5  *
6  */
7
8 #ifndef HABANALABSP_H_
9 #define HABANALABSP_H_
10
11 #include "include/armcp_if.h"
12 #include "include/qman_if.h"
13
14 #include <linux/cdev.h>
15 #include <linux/iopoll.h>
16 #include <linux/irqreturn.h>
17 #include <linux/dma-fence.h>
18 #include <linux/dma-direction.h>
19 #include <linux/scatterlist.h>
20 #include <linux/hashtable.h>
21
22 #define HL_NAME                         "habanalabs"
23
24 #define HL_MMAP_CB_MASK                 (0x8000000000000000ull >> PAGE_SHIFT)
25
26 #define HL_PENDING_RESET_PER_SEC        5
27
28 #define HL_DEVICE_TIMEOUT_USEC          1000000 /* 1 s */
29
30 #define HL_HEARTBEAT_PER_USEC           5000000 /* 5 s */
31
32 #define HL_PLL_LOW_JOB_FREQ_USEC        5000000 /* 5 s */
33
34 #define HL_ARMCP_INFO_TIMEOUT_USEC      10000000 /* 10s */
35 #define HL_ARMCP_EEPROM_TIMEOUT_USEC    10000000 /* 10s */
36
37 #define HL_MAX_QUEUES                   128
38
39 #define HL_MAX_JOBS_PER_CS              64
40
41 /* MUST BE POWER OF 2 and larger than 1 */
42 #define HL_MAX_PENDING_CS               64
43
44 /* Memory */
45 #define MEM_HASH_TABLE_BITS             7 /* 1 << 7 buckets */
46
47 /* MMU */
48 #define MMU_HASH_TABLE_BITS             7 /* 1 << 7 buckets */
49
50 /**
51  * struct pgt_info - MMU hop page info.
52  * @node: hash linked-list node for the pgts shadow hash of pgts.
53  * @phys_addr: physical address of the pgt.
54  * @shadow_addr: shadow hop in the host.
55  * @ctx: pointer to the owner ctx.
56  * @num_of_ptes: indicates how many ptes are used in the pgt.
57  *
58  * The MMU page tables hierarchy is placed on the DRAM. When a new level (hop)
59  * is needed during mapping, a new page is allocated and this structure holds
60  * its essential information. During unmapping, if no valid PTEs remained in the
61  * page, it is freed with its pgt_info structure.
62  */
63 struct pgt_info {
64         struct hlist_node       node;
65         u64                     phys_addr;
66         u64                     shadow_addr;
67         struct hl_ctx           *ctx;
68         int                     num_of_ptes;
69 };
70
71 struct hl_device;
72 struct hl_fpriv;
73
74 /**
75  * enum hl_queue_type - Supported QUEUE types.
76  * @QUEUE_TYPE_NA: queue is not available.
77  * @QUEUE_TYPE_EXT: external queue which is a DMA channel that may access the
78  *                  host.
79  * @QUEUE_TYPE_INT: internal queue that performs DMA inside the device's
80  *                      memories and/or operates the compute engines.
81  * @QUEUE_TYPE_CPU: S/W queue for communication with the device's CPU.
82  */
83 enum hl_queue_type {
84         QUEUE_TYPE_NA,
85         QUEUE_TYPE_EXT,
86         QUEUE_TYPE_INT,
87         QUEUE_TYPE_CPU
88 };
89
90 /**
91  * struct hw_queue_properties - queue information.
92  * @type: queue type.
93  * @kmd_only: true if only KMD is allowed to send a job to this queue, false
94  *            otherwise.
95  */
96 struct hw_queue_properties {
97         enum hl_queue_type      type;
98         u8                      kmd_only;
99 };
100
101 /**
102  * enum vm_type_t - virtual memory mapping request information.
103  * @VM_TYPE_USERPTR: mapping of user memory to device virtual address.
104  * @VM_TYPE_PHYS_PACK: mapping of DRAM memory to device virtual address.
105  */
106 enum vm_type_t {
107         VM_TYPE_USERPTR,
108         VM_TYPE_PHYS_PACK
109 };
110
111 /**
112  * enum hl_device_hw_state - H/W device state. use this to understand whether
113  *                           to do reset before hw_init or not
114  * @HL_DEVICE_HW_STATE_CLEAN: H/W state is clean. i.e. after hard reset
115  * @HL_DEVICE_HW_STATE_DIRTY: H/W state is dirty. i.e. we started to execute
116  *                            hw_init
117  */
118 enum hl_device_hw_state {
119         HL_DEVICE_HW_STATE_CLEAN = 0,
120         HL_DEVICE_HW_STATE_DIRTY
121 };
122
123 /**
124  * struct asic_fixed_properties - ASIC specific immutable properties.
125  * @hw_queues_props: H/W queues properties.
126  * @armcp_info: received various information from ArmCP regarding the H/W. e.g.
127  *              available sensors.
128  * @uboot_ver: F/W U-boot version.
129  * @preboot_ver: F/W Preboot version.
130  * @sram_base_address: SRAM physical start address.
131  * @sram_end_address: SRAM physical end address.
132  * @sram_user_base_address - SRAM physical start address for user access.
133  * @dram_base_address: DRAM physical start address.
134  * @dram_end_address: DRAM physical end address.
135  * @dram_user_base_address: DRAM physical start address for user access.
136  * @dram_size: DRAM total size.
137  * @dram_pci_bar_size: size of PCI bar towards DRAM.
138  * @host_phys_base_address: base physical address of host memory for
139  *                              transactions that the device generates.
140  * @max_power_default: max power of the device after reset
141  * @va_space_host_start_address: base address of virtual memory range for
142  *                               mapping host memory.
143  * @va_space_host_end_address: end address of virtual memory range for
144  *                             mapping host memory.
145  * @va_space_dram_start_address: base address of virtual memory range for
146  *                               mapping DRAM memory.
147  * @va_space_dram_end_address: end address of virtual memory range for
148  *                             mapping DRAM memory.
149  * @dram_size_for_default_page_mapping: DRAM size needed to map to avoid page
150  *                                      fault.
151  * @pcie_dbi_base_address: Base address of the PCIE_DBI block.
152  * @pcie_aux_dbi_reg_addr: Address of the PCIE_AUX DBI register.
153  * @mmu_pgt_addr: base physical address in DRAM of MMU page tables.
154  * @mmu_dram_default_page_addr: DRAM default page physical address.
155  * @mmu_pgt_size: MMU page tables total size.
156  * @mmu_pte_size: PTE size in MMU page tables.
157  * @mmu_hop_table_size: MMU hop table size.
158  * @mmu_hop0_tables_total_size: total size of MMU hop0 tables.
159  * @dram_page_size: page size for MMU DRAM allocation.
160  * @cfg_size: configuration space size on SRAM.
161  * @sram_size: total size of SRAM.
162  * @max_asid: maximum number of open contexts (ASIDs).
163  * @num_of_events: number of possible internal H/W IRQs.
164  * @psoc_pci_pll_nr: PCI PLL NR value.
165  * @psoc_pci_pll_nf: PCI PLL NF value.
166  * @psoc_pci_pll_od: PCI PLL OD value.
167  * @psoc_pci_pll_div_factor: PCI PLL DIV FACTOR 1 value.
168  * @completion_queues_count: number of completion queues.
169  * @high_pll: high PLL frequency used by the device.
170  * @cb_pool_cb_cnt: number of CBs in the CB pool.
171  * @cb_pool_cb_size: size of each CB in the CB pool.
172  * @tpc_enabled_mask: which TPCs are enabled.
173  */
174 struct asic_fixed_properties {
175         struct hw_queue_properties      hw_queues_props[HL_MAX_QUEUES];
176         struct armcp_info       armcp_info;
177         char                    uboot_ver[VERSION_MAX_LEN];
178         char                    preboot_ver[VERSION_MAX_LEN];
179         u64                     sram_base_address;
180         u64                     sram_end_address;
181         u64                     sram_user_base_address;
182         u64                     dram_base_address;
183         u64                     dram_end_address;
184         u64                     dram_user_base_address;
185         u64                     dram_size;
186         u64                     dram_pci_bar_size;
187         u64                     host_phys_base_address;
188         u64                     max_power_default;
189         u64                     va_space_host_start_address;
190         u64                     va_space_host_end_address;
191         u64                     va_space_dram_start_address;
192         u64                     va_space_dram_end_address;
193         u64                     dram_size_for_default_page_mapping;
194         u64                     pcie_dbi_base_address;
195         u64                     pcie_aux_dbi_reg_addr;
196         u64                     mmu_pgt_addr;
197         u64                     mmu_dram_default_page_addr;
198         u32                     mmu_pgt_size;
199         u32                     mmu_pte_size;
200         u32                     mmu_hop_table_size;
201         u32                     mmu_hop0_tables_total_size;
202         u32                     dram_page_size;
203         u32                     cfg_size;
204         u32                     sram_size;
205         u32                     max_asid;
206         u32                     num_of_events;
207         u32                     psoc_pci_pll_nr;
208         u32                     psoc_pci_pll_nf;
209         u32                     psoc_pci_pll_od;
210         u32                     psoc_pci_pll_div_factor;
211         u32                     high_pll;
212         u32                     cb_pool_cb_cnt;
213         u32                     cb_pool_cb_size;
214         u8                      completion_queues_count;
215         u8                      tpc_enabled_mask;
216 };
217
218 /**
219  * struct hl_dma_fence - wrapper for fence object used by command submissions.
220  * @base_fence: kernel fence object.
221  * @lock: spinlock to protect fence.
222  * @hdev: habanalabs device structure.
223  * @cs_seq: command submission sequence number.
224  */
225 struct hl_dma_fence {
226         struct dma_fence        base_fence;
227         spinlock_t              lock;
228         struct hl_device        *hdev;
229         u64                     cs_seq;
230 };
231
232 /*
233  * Command Buffers
234  */
235
236 #define HL_MAX_CB_SIZE          0x200000        /* 2MB */
237
238 /**
239  * struct hl_cb_mgr - describes a Command Buffer Manager.
240  * @cb_lock: protects cb_handles.
241  * @cb_handles: an idr to hold all command buffer handles.
242  */
243 struct hl_cb_mgr {
244         spinlock_t              cb_lock;
245         struct idr              cb_handles; /* protected by cb_lock */
246 };
247
248 /**
249  * struct hl_cb - describes a Command Buffer.
250  * @refcount: reference counter for usage of the CB.
251  * @hdev: pointer to device this CB belongs to.
252  * @lock: spinlock to protect mmap/cs flows.
253  * @debugfs_list: node in debugfs list of command buffers.
254  * @pool_list: node in pool list of command buffers.
255  * @kernel_address: Holds the CB's kernel virtual address.
256  * @bus_address: Holds the CB's DMA address.
257  * @mmap_size: Holds the CB's size that was mmaped.
258  * @size: holds the CB's size.
259  * @id: the CB's ID.
260  * @cs_cnt: holds number of CS that this CB participates in.
261  * @ctx_id: holds the ID of the owner's context.
262  * @mmap: true if the CB is currently mmaped to user.
263  * @is_pool: true if CB was acquired from the pool, false otherwise.
264  */
265 struct hl_cb {
266         struct kref             refcount;
267         struct hl_device        *hdev;
268         spinlock_t              lock;
269         struct list_head        debugfs_list;
270         struct list_head        pool_list;
271         u64                     kernel_address;
272         dma_addr_t              bus_address;
273         u32                     mmap_size;
274         u32                     size;
275         u32                     id;
276         u32                     cs_cnt;
277         u32                     ctx_id;
278         u8                      mmap;
279         u8                      is_pool;
280 };
281
282
283 /*
284  * QUEUES
285  */
286
287 struct hl_cs_job;
288
289 /*
290  * Currently, there are two limitations on the maximum length of a queue:
291  *
292  * 1. The memory footprint of the queue. The current allocated space for the
293  *    queue is PAGE_SIZE. Because each entry in the queue is HL_BD_SIZE,
294  *    the maximum length of the queue can be PAGE_SIZE / HL_BD_SIZE,
295  *    which currently is 4096/16 = 256 entries.
296  *
297  *    To increase that, we need either to decrease the size of the
298  *    BD (difficult), or allocate more than a single page (easier).
299  *
300  * 2. Because the size of the JOB handle field in the BD CTL / completion queue
301  *    is 10-bit, we can have up to 1024 open jobs per hardware queue.
302  *    Therefore, each queue can hold up to 1024 entries.
303  *
304  * HL_QUEUE_LENGTH is in units of struct hl_bd.
305  * HL_QUEUE_LENGTH * sizeof(struct hl_bd) should be <= HL_PAGE_SIZE
306  */
307
308 #define HL_PAGE_SIZE                    4096 /* minimum page size */
309 /* Must be power of 2 (HL_PAGE_SIZE / HL_BD_SIZE) */
310 #define HL_QUEUE_LENGTH                 256
311 #define HL_QUEUE_SIZE_IN_BYTES          (HL_QUEUE_LENGTH * HL_BD_SIZE)
312
313 /*
314  * HL_CQ_LENGTH is in units of struct hl_cq_entry.
315  * HL_CQ_LENGTH should be <= HL_PAGE_SIZE
316  */
317 #define HL_CQ_LENGTH                    HL_QUEUE_LENGTH
318 #define HL_CQ_SIZE_IN_BYTES             (HL_CQ_LENGTH * HL_CQ_ENTRY_SIZE)
319
320 /* Must be power of 2 (HL_PAGE_SIZE / HL_EQ_ENTRY_SIZE) */
321 #define HL_EQ_LENGTH                    64
322 #define HL_EQ_SIZE_IN_BYTES             (HL_EQ_LENGTH * HL_EQ_ENTRY_SIZE)
323
324
325 /**
326  * struct hl_hw_queue - describes a H/W transport queue.
327  * @shadow_queue: pointer to a shadow queue that holds pointers to jobs.
328  * @queue_type: type of queue.
329  * @kernel_address: holds the queue's kernel virtual address.
330  * @bus_address: holds the queue's DMA address.
331  * @pi: holds the queue's pi value.
332  * @ci: holds the queue's ci value, AS CALCULATED BY THE DRIVER (not real ci).
333  * @hw_queue_id: the id of the H/W queue.
334  * @int_queue_len: length of internal queue (number of entries).
335  * @valid: is the queue valid (we have array of 32 queues, not all of them
336  *              exists).
337  */
338 struct hl_hw_queue {
339         struct hl_cs_job        **shadow_queue;
340         enum hl_queue_type      queue_type;
341         u64                     kernel_address;
342         dma_addr_t              bus_address;
343         u32                     pi;
344         u32                     ci;
345         u32                     hw_queue_id;
346         u16                     int_queue_len;
347         u8                      valid;
348 };
349
350 /**
351  * struct hl_cq - describes a completion queue
352  * @hdev: pointer to the device structure
353  * @kernel_address: holds the queue's kernel virtual address
354  * @bus_address: holds the queue's DMA address
355  * @hw_queue_id: the id of the matching H/W queue
356  * @ci: ci inside the queue
357  * @pi: pi inside the queue
358  * @free_slots_cnt: counter of free slots in queue
359  */
360 struct hl_cq {
361         struct hl_device        *hdev;
362         u64                     kernel_address;
363         dma_addr_t              bus_address;
364         u32                     hw_queue_id;
365         u32                     ci;
366         u32                     pi;
367         atomic_t                free_slots_cnt;
368 };
369
370 /**
371  * struct hl_eq - describes the event queue (single one per device)
372  * @hdev: pointer to the device structure
373  * @kernel_address: holds the queue's kernel virtual address
374  * @bus_address: holds the queue's DMA address
375  * @ci: ci inside the queue
376  */
377 struct hl_eq {
378         struct hl_device        *hdev;
379         u64                     kernel_address;
380         dma_addr_t              bus_address;
381         u32                     ci;
382 };
383
384
385 /*
386  * ASICs
387  */
388
389 /**
390  * enum hl_asic_type - supported ASIC types.
391  * @ASIC_INVALID: Invalid ASIC type.
392  * @ASIC_GOYA: Goya device.
393  */
394 enum hl_asic_type {
395         ASIC_INVALID,
396         ASIC_GOYA
397 };
398
399 struct hl_cs_parser;
400
401 /**
402  * enum hl_pm_mng_profile - power management profile.
403  * @PM_AUTO: internal clock is set by KMD.
404  * @PM_MANUAL: internal clock is set by the user.
405  * @PM_LAST: last power management type.
406  */
407 enum hl_pm_mng_profile {
408         PM_AUTO = 1,
409         PM_MANUAL,
410         PM_LAST
411 };
412
413 /**
414  * enum hl_pll_frequency - PLL frequency.
415  * @PLL_HIGH: high frequency.
416  * @PLL_LOW: low frequency.
417  * @PLL_LAST: last frequency values that were configured by the user.
418  */
419 enum hl_pll_frequency {
420         PLL_HIGH = 1,
421         PLL_LOW,
422         PLL_LAST
423 };
424
425 /**
426  * struct hl_asic_funcs - ASIC specific functions that are can be called from
427  *                        common code.
428  * @early_init: sets up early driver state (pre sw_init), doesn't configure H/W.
429  * @early_fini: tears down what was done in early_init.
430  * @late_init: sets up late driver/hw state (post hw_init) - Optional.
431  * @late_fini: tears down what was done in late_init (pre hw_fini) - Optional.
432  * @sw_init: sets up driver state, does not configure H/W.
433  * @sw_fini: tears down driver state, does not configure H/W.
434  * @hw_init: sets up the H/W state.
435  * @hw_fini: tears down the H/W state.
436  * @halt_engines: halt engines, needed for reset sequence. This also disables
437  *                interrupts from the device. Should be called before
438  *                hw_fini and before CS rollback.
439  * @suspend: handles IP specific H/W or SW changes for suspend.
440  * @resume: handles IP specific H/W or SW changes for resume.
441  * @cb_mmap: maps a CB.
442  * @ring_doorbell: increment PI on a given QMAN.
443  * @flush_pq_write: flush PQ entry write if necessary, WARN if flushing failed.
444  * @dma_alloc_coherent: Allocate coherent DMA memory by calling
445  *                      dma_alloc_coherent(). This is ASIC function because its
446  *                      implementation is not trivial when the driver is loaded
447  *                      in simulation mode (not upstreamed).
448  * @dma_free_coherent: Free coherent DMA memory by calling dma_free_coherent().
449  *                     This is ASIC function because its implementation is not
450  *                     trivial when the driver is loaded in simulation mode
451  *                     (not upstreamed).
452  * @get_int_queue_base: get the internal queue base address.
453  * @test_queues: run simple test on all queues for sanity check.
454  * @dma_pool_zalloc: small DMA allocation of coherent memory from DMA pool.
455  *                   size of allocation is HL_DMA_POOL_BLK_SIZE.
456  * @dma_pool_free: free small DMA allocation from pool.
457  * @cpu_accessible_dma_pool_alloc: allocate CPU PQ packet from DMA pool.
458  * @cpu_accessible_dma_pool_free: free CPU PQ packet from DMA pool.
459  * @hl_dma_unmap_sg: DMA unmap scatter-gather list.
460  * @cs_parser: parse Command Submission.
461  * @asic_dma_map_sg: DMA map scatter-gather list.
462  * @get_dma_desc_list_size: get number of LIN_DMA packets required for CB.
463  * @add_end_of_cb_packets: Add packets to the end of CB, if device requires it.
464  * @update_eq_ci: update event queue CI.
465  * @context_switch: called upon ASID context switch.
466  * @restore_phase_topology: clear all SOBs amd MONs.
467  * @debugfs_read32: debug interface for reading u32 from DRAM/SRAM.
468  * @debugfs_write32: debug interface for writing u32 to DRAM/SRAM.
469  * @add_device_attr: add ASIC specific device attributes.
470  * @handle_eqe: handle event queue entry (IRQ) from ArmCP.
471  * @set_pll_profile: change PLL profile (manual/automatic).
472  * @get_events_stat: retrieve event queue entries histogram.
473  * @read_pte: read MMU page table entry from DRAM.
474  * @write_pte: write MMU page table entry to DRAM.
475  * @mmu_invalidate_cache: flush MMU STLB cache, either with soft (L1 only) or
476  *                        hard (L0 & L1) flush.
477  * @mmu_invalidate_cache_range: flush specific MMU STLB cache lines with
478  *                              ASID-VA-size mask.
479  * @send_heartbeat: send is-alive packet to ArmCP and verify response.
480  * @debug_coresight: perform certain actions on Coresight for debugging.
481  * @is_device_idle: return true if device is idle, false otherwise.
482  * @soft_reset_late_init: perform certain actions needed after soft reset.
483  * @hw_queues_lock: acquire H/W queues lock.
484  * @hw_queues_unlock: release H/W queues lock.
485  * @get_pci_id: retrieve PCI ID.
486  * @get_eeprom_data: retrieve EEPROM data from F/W.
487  * @send_cpu_message: send buffer to ArmCP.
488  * @get_hw_state: retrieve the H/W state
489  * @pci_bars_map: Map PCI BARs.
490  * @set_dram_bar_base: Set DRAM BAR to map specific device address. Returns
491  *                     old address the bar pointed to or U64_MAX for failure
492  * @init_iatu: Initialize the iATU unit inside the PCI controller.
493  * @rreg: Read a register. Needed for simulator support.
494  * @wreg: Write a register. Needed for simulator support.
495  */
496 struct hl_asic_funcs {
497         int (*early_init)(struct hl_device *hdev);
498         int (*early_fini)(struct hl_device *hdev);
499         int (*late_init)(struct hl_device *hdev);
500         void (*late_fini)(struct hl_device *hdev);
501         int (*sw_init)(struct hl_device *hdev);
502         int (*sw_fini)(struct hl_device *hdev);
503         int (*hw_init)(struct hl_device *hdev);
504         void (*hw_fini)(struct hl_device *hdev, bool hard_reset);
505         void (*halt_engines)(struct hl_device *hdev, bool hard_reset);
506         int (*suspend)(struct hl_device *hdev);
507         int (*resume)(struct hl_device *hdev);
508         int (*cb_mmap)(struct hl_device *hdev, struct vm_area_struct *vma,
509                         u64 kaddress, phys_addr_t paddress, u32 size);
510         void (*ring_doorbell)(struct hl_device *hdev, u32 hw_queue_id, u32 pi);
511         void (*flush_pq_write)(struct hl_device *hdev, u64 *pq, u64 exp_val);
512         void* (*dma_alloc_coherent)(struct hl_device *hdev, size_t size,
513                                         dma_addr_t *dma_handle, gfp_t flag);
514         void (*dma_free_coherent)(struct hl_device *hdev, size_t size,
515                                         void *cpu_addr, dma_addr_t dma_handle);
516         void* (*get_int_queue_base)(struct hl_device *hdev, u32 queue_id,
517                                 dma_addr_t *dma_handle, u16 *queue_len);
518         int (*test_queues)(struct hl_device *hdev);
519         void* (*dma_pool_zalloc)(struct hl_device *hdev, size_t size,
520                                 gfp_t mem_flags, dma_addr_t *dma_handle);
521         void (*dma_pool_free)(struct hl_device *hdev, void *vaddr,
522                                 dma_addr_t dma_addr);
523         void* (*cpu_accessible_dma_pool_alloc)(struct hl_device *hdev,
524                                 size_t size, dma_addr_t *dma_handle);
525         void (*cpu_accessible_dma_pool_free)(struct hl_device *hdev,
526                                 size_t size, void *vaddr);
527         void (*hl_dma_unmap_sg)(struct hl_device *hdev,
528                                 struct scatterlist *sg, int nents,
529                                 enum dma_data_direction dir);
530         int (*cs_parser)(struct hl_device *hdev, struct hl_cs_parser *parser);
531         int (*asic_dma_map_sg)(struct hl_device *hdev,
532                                 struct scatterlist *sg, int nents,
533                                 enum dma_data_direction dir);
534         u32 (*get_dma_desc_list_size)(struct hl_device *hdev,
535                                         struct sg_table *sgt);
536         void (*add_end_of_cb_packets)(u64 kernel_address, u32 len, u64 cq_addr,
537                                         u32 cq_val, u32 msix_num);
538         void (*update_eq_ci)(struct hl_device *hdev, u32 val);
539         int (*context_switch)(struct hl_device *hdev, u32 asid);
540         void (*restore_phase_topology)(struct hl_device *hdev);
541         int (*debugfs_read32)(struct hl_device *hdev, u64 addr, u32 *val);
542         int (*debugfs_write32)(struct hl_device *hdev, u64 addr, u32 val);
543         void (*add_device_attr)(struct hl_device *hdev,
544                                 struct attribute_group *dev_attr_grp);
545         void (*handle_eqe)(struct hl_device *hdev,
546                                 struct hl_eq_entry *eq_entry);
547         void (*set_pll_profile)(struct hl_device *hdev,
548                         enum hl_pll_frequency freq);
549         void* (*get_events_stat)(struct hl_device *hdev, u32 *size);
550         u64 (*read_pte)(struct hl_device *hdev, u64 addr);
551         void (*write_pte)(struct hl_device *hdev, u64 addr, u64 val);
552         void (*mmu_invalidate_cache)(struct hl_device *hdev, bool is_hard);
553         void (*mmu_invalidate_cache_range)(struct hl_device *hdev, bool is_hard,
554                         u32 asid, u64 va, u64 size);
555         int (*send_heartbeat)(struct hl_device *hdev);
556         int (*debug_coresight)(struct hl_device *hdev, void *data);
557         bool (*is_device_idle)(struct hl_device *hdev, char *buf, size_t size);
558         int (*soft_reset_late_init)(struct hl_device *hdev);
559         void (*hw_queues_lock)(struct hl_device *hdev);
560         void (*hw_queues_unlock)(struct hl_device *hdev);
561         u32 (*get_pci_id)(struct hl_device *hdev);
562         int (*get_eeprom_data)(struct hl_device *hdev, void *data,
563                                 size_t max_size);
564         int (*send_cpu_message)(struct hl_device *hdev, u32 *msg,
565                                 u16 len, u32 timeout, long *result);
566         enum hl_device_hw_state (*get_hw_state)(struct hl_device *hdev);
567         int (*pci_bars_map)(struct hl_device *hdev);
568         u64 (*set_dram_bar_base)(struct hl_device *hdev, u64 addr);
569         int (*init_iatu)(struct hl_device *hdev);
570         u32 (*rreg)(struct hl_device *hdev, u32 reg);
571         void (*wreg)(struct hl_device *hdev, u32 reg, u32 val);
572 };
573
574
575 /*
576  * CONTEXTS
577  */
578
579 #define HL_KERNEL_ASID_ID       0
580
581 /**
582  * struct hl_va_range - virtual addresses range.
583  * @lock: protects the virtual addresses list.
584  * @list: list of virtual addresses blocks available for mappings.
585  * @start_addr: range start address.
586  * @end_addr: range end address.
587  */
588 struct hl_va_range {
589         struct mutex            lock;
590         struct list_head        list;
591         u64                     start_addr;
592         u64                     end_addr;
593 };
594
595 /**
596  * struct hl_ctx - user/kernel context.
597  * @mem_hash: holds mapping from virtual address to virtual memory area
598  *              descriptor (hl_vm_phys_pg_list or hl_userptr).
599  * @mmu_phys_hash: holds a mapping from physical address to pgt_info structure.
600  * @mmu_shadow_hash: holds a mapping from shadow address to pgt_info structure.
601  * @hpriv: pointer to the private (KMD) data of the process (fd).
602  * @hdev: pointer to the device structure.
603  * @refcount: reference counter for the context. Context is released only when
604  *              this hits 0l. It is incremented on CS and CS_WAIT.
605  * @cs_pending: array of DMA fence objects representing pending CS.
606  * @host_va_range: holds available virtual addresses for host mappings.
607  * @dram_va_range: holds available virtual addresses for DRAM mappings.
608  * @mem_hash_lock: protects the mem_hash.
609  * @mmu_lock: protects the MMU page tables. Any change to the PGT, modifing the
610  *            MMU hash or walking the PGT requires talking this lock
611  * @debugfs_list: node in debugfs list of contexts.
612  * @cs_sequence: sequence number for CS. Value is assigned to a CS and passed
613  *                      to user so user could inquire about CS. It is used as
614  *                      index to cs_pending array.
615  * @dram_default_hops: array that holds all hops addresses needed for default
616  *                     DRAM mapping.
617  * @cs_lock: spinlock to protect cs_sequence.
618  * @dram_phys_mem: amount of used physical DRAM memory by this context.
619  * @thread_ctx_switch_token: token to prevent multiple threads of the same
620  *                              context from running the context switch phase.
621  *                              Only a single thread should run it.
622  * @thread_ctx_switch_wait_token: token to prevent the threads that didn't run
623  *                              the context switch phase from moving to their
624  *                              execution phase before the context switch phase
625  *                              has finished.
626  * @asid: context's unique address space ID in the device's MMU.
627  */
628 struct hl_ctx {
629         DECLARE_HASHTABLE(mem_hash, MEM_HASH_TABLE_BITS);
630         DECLARE_HASHTABLE(mmu_phys_hash, MMU_HASH_TABLE_BITS);
631         DECLARE_HASHTABLE(mmu_shadow_hash, MMU_HASH_TABLE_BITS);
632         struct hl_fpriv         *hpriv;
633         struct hl_device        *hdev;
634         struct kref             refcount;
635         struct dma_fence        *cs_pending[HL_MAX_PENDING_CS];
636         struct hl_va_range      host_va_range;
637         struct hl_va_range      dram_va_range;
638         struct mutex            mem_hash_lock;
639         struct mutex            mmu_lock;
640         struct list_head        debugfs_list;
641         u64                     cs_sequence;
642         u64                     *dram_default_hops;
643         spinlock_t              cs_lock;
644         atomic64_t              dram_phys_mem;
645         atomic_t                thread_ctx_switch_token;
646         u32                     thread_ctx_switch_wait_token;
647         u32                     asid;
648 };
649
650 /**
651  * struct hl_ctx_mgr - for handling multiple contexts.
652  * @ctx_lock: protects ctx_handles.
653  * @ctx_handles: idr to hold all ctx handles.
654  */
655 struct hl_ctx_mgr {
656         struct mutex            ctx_lock;
657         struct idr              ctx_handles;
658 };
659
660
661
662 /*
663  * COMMAND SUBMISSIONS
664  */
665
666 /**
667  * struct hl_userptr - memory mapping chunk information
668  * @vm_type: type of the VM.
669  * @job_node: linked-list node for hanging the object on the Job's list.
670  * @vec: pointer to the frame vector.
671  * @sgt: pointer to the scatter-gather table that holds the pages.
672  * @dir: for DMA unmapping, the direction must be supplied, so save it.
673  * @debugfs_list: node in debugfs list of command submissions.
674  * @addr: user-space virtual pointer to the start of the memory area.
675  * @size: size of the memory area to pin & map.
676  * @dma_mapped: true if the SG was mapped to DMA addresses, false otherwise.
677  */
678 struct hl_userptr {
679         enum vm_type_t          vm_type; /* must be first */
680         struct list_head        job_node;
681         struct frame_vector     *vec;
682         struct sg_table         *sgt;
683         enum dma_data_direction dir;
684         struct list_head        debugfs_list;
685         u64                     addr;
686         u32                     size;
687         u8                      dma_mapped;
688 };
689
690 /**
691  * struct hl_cs - command submission.
692  * @jobs_in_queue_cnt: per each queue, maintain counter of submitted jobs.
693  * @ctx: the context this CS belongs to.
694  * @job_list: list of the CS's jobs in the various queues.
695  * @job_lock: spinlock for the CS's jobs list. Needed for free_job.
696  * @refcount: reference counter for usage of the CS.
697  * @fence: pointer to the fence object of this CS.
698  * @work_tdr: delayed work node for TDR.
699  * @mirror_node : node in device mirror list of command submissions.
700  * @debugfs_list: node in debugfs list of command submissions.
701  * @sequence: the sequence number of this CS.
702  * @submitted: true if CS was submitted to H/W.
703  * @completed: true if CS was completed by device.
704  * @timedout : true if CS was timedout.
705  * @tdr_active: true if TDR was activated for this CS (to prevent
706  *              double TDR activation).
707  * @aborted: true if CS was aborted due to some device error.
708  */
709 struct hl_cs {
710         u8                      jobs_in_queue_cnt[HL_MAX_QUEUES];
711         struct hl_ctx           *ctx;
712         struct list_head        job_list;
713         spinlock_t              job_lock;
714         struct kref             refcount;
715         struct dma_fence        *fence;
716         struct delayed_work     work_tdr;
717         struct list_head        mirror_node;
718         struct list_head        debugfs_list;
719         u64                     sequence;
720         u8                      submitted;
721         u8                      completed;
722         u8                      timedout;
723         u8                      tdr_active;
724         u8                      aborted;
725 };
726
727 /**
728  * struct hl_cs_job - command submission job.
729  * @cs_node: the node to hang on the CS jobs list.
730  * @cs: the CS this job belongs to.
731  * @user_cb: the CB we got from the user.
732  * @patched_cb: in case of patching, this is internal CB which is submitted on
733  *              the queue instead of the CB we got from the IOCTL.
734  * @finish_work: workqueue object to run when job is completed.
735  * @userptr_list: linked-list of userptr mappings that belong to this job and
736  *                      wait for completion.
737  * @debugfs_list: node in debugfs list of command submission jobs.
738  * @id: the id of this job inside a CS.
739  * @hw_queue_id: the id of the H/W queue this job is submitted to.
740  * @user_cb_size: the actual size of the CB we got from the user.
741  * @job_cb_size: the actual size of the CB that we put on the queue.
742  * @ext_queue: whether the job is for external queue or internal queue.
743  */
744 struct hl_cs_job {
745         struct list_head        cs_node;
746         struct hl_cs            *cs;
747         struct hl_cb            *user_cb;
748         struct hl_cb            *patched_cb;
749         struct work_struct      finish_work;
750         struct list_head        userptr_list;
751         struct list_head        debugfs_list;
752         u32                     id;
753         u32                     hw_queue_id;
754         u32                     user_cb_size;
755         u32                     job_cb_size;
756         u8                      ext_queue;
757 };
758
759 /**
760  * struct hl_cs_parser - command submission paerser properties.
761  * @user_cb: the CB we got from the user.
762  * @patched_cb: in case of patching, this is internal CB which is submitted on
763  *              the queue instead of the CB we got from the IOCTL.
764  * @job_userptr_list: linked-list of userptr mappings that belong to the related
765  *                      job and wait for completion.
766  * @cs_sequence: the sequence number of the related CS.
767  * @ctx_id: the ID of the context the related CS belongs to.
768  * @hw_queue_id: the id of the H/W queue this job is submitted to.
769  * @user_cb_size: the actual size of the CB we got from the user.
770  * @patched_cb_size: the size of the CB after parsing.
771  * @ext_queue: whether the job is for external queue or internal queue.
772  * @job_id: the id of the related job inside the related CS.
773  * @use_virt_addr: whether to treat the addresses in the CB as virtual during
774  *                      parsing.
775  */
776 struct hl_cs_parser {
777         struct hl_cb            *user_cb;
778         struct hl_cb            *patched_cb;
779         struct list_head        *job_userptr_list;
780         u64                     cs_sequence;
781         u32                     ctx_id;
782         u32                     hw_queue_id;
783         u32                     user_cb_size;
784         u32                     patched_cb_size;
785         u8                      ext_queue;
786         u8                      job_id;
787         u8                      use_virt_addr;
788 };
789
790
791 /*
792  * MEMORY STRUCTURE
793  */
794
795 /**
796  * struct hl_vm_hash_node - hash element from virtual address to virtual
797  *                              memory area descriptor (hl_vm_phys_pg_list or
798  *                              hl_userptr).
799  * @node: node to hang on the hash table in context object.
800  * @vaddr: key virtual address.
801  * @ptr: value pointer (hl_vm_phys_pg_list or hl_userptr).
802  */
803 struct hl_vm_hash_node {
804         struct hlist_node       node;
805         u64                     vaddr;
806         void                    *ptr;
807 };
808
809 /**
810  * struct hl_vm_phys_pg_pack - physical page pack.
811  * @vm_type: describes the type of the virtual area descriptor.
812  * @pages: the physical page array.
813  * @npages: num physical pages in the pack.
814  * @total_size: total size of all the pages in this list.
815  * @mapping_cnt: number of shared mappings.
816  * @asid: the context related to this list.
817  * @page_size: size of each page in the pack.
818  * @flags: HL_MEM_* flags related to this list.
819  * @handle: the provided handle related to this list.
820  * @offset: offset from the first page.
821  * @contiguous: is contiguous physical memory.
822  * @created_from_userptr: is product of host virtual address.
823  */
824 struct hl_vm_phys_pg_pack {
825         enum vm_type_t          vm_type; /* must be first */
826         u64                     *pages;
827         u64                     npages;
828         u64                     total_size;
829         atomic_t                mapping_cnt;
830         u32                     asid;
831         u32                     page_size;
832         u32                     flags;
833         u32                     handle;
834         u32                     offset;
835         u8                      contiguous;
836         u8                      created_from_userptr;
837 };
838
839 /**
840  * struct hl_vm_va_block - virtual range block information.
841  * @node: node to hang on the virtual range list in context object.
842  * @start: virtual range start address.
843  * @end: virtual range end address.
844  * @size: virtual range size.
845  */
846 struct hl_vm_va_block {
847         struct list_head        node;
848         u64                     start;
849         u64                     end;
850         u64                     size;
851 };
852
853 /**
854  * struct hl_vm - virtual memory manager for MMU.
855  * @dram_pg_pool: pool for DRAM physical pages of 2MB.
856  * @dram_pg_pool_refcount: reference counter for the pool usage.
857  * @idr_lock: protects the phys_pg_list_handles.
858  * @phys_pg_pack_handles: idr to hold all device allocations handles.
859  * @init_done: whether initialization was done. We need this because VM
860  *              initialization might be skipped during device initialization.
861  */
862 struct hl_vm {
863         struct gen_pool         *dram_pg_pool;
864         struct kref             dram_pg_pool_refcount;
865         spinlock_t              idr_lock;
866         struct idr              phys_pg_pack_handles;
867         u8                      init_done;
868 };
869
870
871 /*
872  * DEBUG, PROFILING STRUCTURE
873  */
874
875 /**
876  * struct hl_debug_params - Coresight debug parameters.
877  * @input: pointer to component specific input parameters.
878  * @output: pointer to component specific output parameters.
879  * @output_size: size of output buffer.
880  * @reg_idx: relevant register ID.
881  * @op: component operation to execute.
882  * @enable: true if to enable component debugging, false otherwise.
883  */
884 struct hl_debug_params {
885         void *input;
886         void *output;
887         u32 output_size;
888         u32 reg_idx;
889         u32 op;
890         bool enable;
891 };
892
893 /*
894  * FILE PRIVATE STRUCTURE
895  */
896
897 /**
898  * struct hl_fpriv - process information stored in FD private data.
899  * @hdev: habanalabs device structure.
900  * @filp: pointer to the given file structure.
901  * @taskpid: current process ID.
902  * @ctx: current executing context.
903  * @ctx_mgr: context manager to handle multiple context for this FD.
904  * @cb_mgr: command buffer manager to handle multiple buffers for this FD.
905  * @debugfs_list: list of relevant ASIC debugfs.
906  * @refcount: number of related contexts.
907  * @restore_phase_mutex: lock for context switch and restore phase.
908  */
909 struct hl_fpriv {
910         struct hl_device        *hdev;
911         struct file             *filp;
912         struct pid              *taskpid;
913         struct hl_ctx           *ctx; /* TODO: remove for multiple ctx */
914         struct hl_ctx_mgr       ctx_mgr;
915         struct hl_cb_mgr        cb_mgr;
916         struct list_head        debugfs_list;
917         struct kref             refcount;
918         struct mutex            restore_phase_mutex;
919 };
920
921
922 /*
923  * DebugFS
924  */
925
926 /**
927  * struct hl_info_list - debugfs file ops.
928  * @name: file name.
929  * @show: function to output information.
930  * @write: function to write to the file.
931  */
932 struct hl_info_list {
933         const char      *name;
934         int             (*show)(struct seq_file *s, void *data);
935         ssize_t         (*write)(struct file *file, const char __user *buf,
936                                 size_t count, loff_t *f_pos);
937 };
938
939 /**
940  * struct hl_debugfs_entry - debugfs dentry wrapper.
941  * @dent: base debugfs entry structure.
942  * @info_ent: dentry realted ops.
943  * @dev_entry: ASIC specific debugfs manager.
944  */
945 struct hl_debugfs_entry {
946         struct dentry                   *dent;
947         const struct hl_info_list       *info_ent;
948         struct hl_dbg_device_entry      *dev_entry;
949 };
950
951 /**
952  * struct hl_dbg_device_entry - ASIC specific debugfs manager.
953  * @root: root dentry.
954  * @hdev: habanalabs device structure.
955  * @entry_arr: array of available hl_debugfs_entry.
956  * @file_list: list of available debugfs files.
957  * @file_mutex: protects file_list.
958  * @cb_list: list of available CBs.
959  * @cb_spinlock: protects cb_list.
960  * @cs_list: list of available CSs.
961  * @cs_spinlock: protects cs_list.
962  * @cs_job_list: list of available CB jobs.
963  * @cs_job_spinlock: protects cs_job_list.
964  * @userptr_list: list of available userptrs (virtual memory chunk descriptor).
965  * @userptr_spinlock: protects userptr_list.
966  * @ctx_mem_hash_list: list of available contexts with MMU mappings.
967  * @ctx_mem_hash_spinlock: protects cb_list.
968  * @addr: next address to read/write from/to in read/write32.
969  * @mmu_addr: next virtual address to translate to physical address in mmu_show.
970  * @mmu_asid: ASID to use while translating in mmu_show.
971  * @i2c_bus: generic u8 debugfs file for bus value to use in i2c_data_read.
972  * @i2c_bus: generic u8 debugfs file for address value to use in i2c_data_read.
973  * @i2c_bus: generic u8 debugfs file for register value to use in i2c_data_read.
974  */
975 struct hl_dbg_device_entry {
976         struct dentry                   *root;
977         struct hl_device                *hdev;
978         struct hl_debugfs_entry         *entry_arr;
979         struct list_head                file_list;
980         struct mutex                    file_mutex;
981         struct list_head                cb_list;
982         spinlock_t                      cb_spinlock;
983         struct list_head                cs_list;
984         spinlock_t                      cs_spinlock;
985         struct list_head                cs_job_list;
986         spinlock_t                      cs_job_spinlock;
987         struct list_head                userptr_list;
988         spinlock_t                      userptr_spinlock;
989         struct list_head                ctx_mem_hash_list;
990         spinlock_t                      ctx_mem_hash_spinlock;
991         u64                             addr;
992         u64                             mmu_addr;
993         u32                             mmu_asid;
994         u8                              i2c_bus;
995         u8                              i2c_addr;
996         u8                              i2c_reg;
997 };
998
999
1000 /*
1001  * DEVICES
1002  */
1003
1004 /* Theoretical limit only. A single host can only contain up to 4 or 8 PCIe
1005  * x16 cards. In extereme cases, there are hosts that can accommodate 16 cards
1006  */
1007 #define HL_MAX_MINORS   256
1008
1009 /*
1010  * Registers read & write functions.
1011  */
1012
1013 u32 hl_rreg(struct hl_device *hdev, u32 reg);
1014 void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
1015
1016 #define RREG32(reg) hdev->asic_funcs->rreg(hdev, (reg))
1017 #define WREG32(reg, v) hdev->asic_funcs->wreg(hdev, (reg), (v))
1018 #define DREG32(reg) pr_info("REGISTER: " #reg " : 0x%08X\n",    \
1019                         hdev->asic_funcs->rreg(hdev, (reg)))
1020
1021 #define WREG32_P(reg, val, mask)                                \
1022         do {                                                    \
1023                 u32 tmp_ = RREG32(reg);                         \
1024                 tmp_ &= (mask);                                 \
1025                 tmp_ |= ((val) & ~(mask));                      \
1026                 WREG32(reg, tmp_);                              \
1027         } while (0)
1028 #define WREG32_AND(reg, and) WREG32_P(reg, 0, and)
1029 #define WREG32_OR(reg, or) WREG32_P(reg, or, ~(or))
1030
1031 #define REG_FIELD_SHIFT(reg, field) reg##_##field##_SHIFT
1032 #define REG_FIELD_MASK(reg, field) reg##_##field##_MASK
1033 #define WREG32_FIELD(reg, field, val)   \
1034         WREG32(mm##reg, (RREG32(mm##reg) & ~REG_FIELD_MASK(reg, field)) | \
1035                         (val) << REG_FIELD_SHIFT(reg, field))
1036
1037 #define hl_poll_timeout(hdev, addr, val, cond, sleep_us, timeout_us) \
1038 ({ \
1039         ktime_t __timeout = ktime_add_us(ktime_get(), timeout_us); \
1040         might_sleep_if(sleep_us); \
1041         for (;;) { \
1042                 (val) = RREG32(addr); \
1043                 if (cond) \
1044                         break; \
1045                 if (timeout_us && ktime_compare(ktime_get(), __timeout) > 0) { \
1046                         (val) = RREG32(addr); \
1047                         break; \
1048                 } \
1049                 if (sleep_us) \
1050                         usleep_range((sleep_us >> 2) + 1, sleep_us); \
1051         } \
1052         (cond) ? 0 : -ETIMEDOUT; \
1053 })
1054
1055
1056 #define HL_ENG_BUSY(buf, size, fmt, ...) ({ \
1057                 if (buf) \
1058                         snprintf(buf, size, fmt, ##__VA_ARGS__); \
1059                 false; \
1060         })
1061
1062 struct hwmon_chip_info;
1063
1064 /**
1065  * struct hl_device_reset_work - reset workqueue task wrapper.
1066  * @reset_work: reset work to be done.
1067  * @hdev: habanalabs device structure.
1068  */
1069 struct hl_device_reset_work {
1070         struct work_struct              reset_work;
1071         struct hl_device                *hdev;
1072 };
1073
1074 /**
1075  * struct hl_device - habanalabs device structure.
1076  * @pdev: pointer to PCI device, can be NULL in case of simulator device.
1077  * @pcie_bar: array of available PCIe bars.
1078  * @rmmio: configuration area address on SRAM.
1079  * @cdev: related char device.
1080  * @dev: realted kernel basic device structure.
1081  * @work_freq: delayed work to lower device frequency if possible.
1082  * @work_heartbeat: delayed work for ArmCP is-alive check.
1083  * @asic_name: ASIC specific nmae.
1084  * @asic_type: ASIC specific type.
1085  * @completion_queue: array of hl_cq.
1086  * @cq_wq: work queue of completion queues for executing work in process context
1087  * @eq_wq: work queue of event queue for executing work in process context.
1088  * @kernel_ctx: KMD context structure.
1089  * @kernel_queues: array of hl_hw_queue.
1090  * @hw_queues_mirror_list: CS mirror list for TDR.
1091  * @hw_queues_mirror_lock: protects hw_queues_mirror_list.
1092  * @kernel_cb_mgr: command buffer manager for creating/destroying/handling CGs.
1093  * @event_queue: event queue for IRQ from ArmCP.
1094  * @dma_pool: DMA pool for small allocations.
1095  * @cpu_accessible_dma_mem: KMD <-> ArmCP shared memory CPU address.
1096  * @cpu_accessible_dma_address: KMD <-> ArmCP shared memory DMA address.
1097  * @cpu_accessible_dma_pool: KMD <-> ArmCP shared memory pool.
1098  * @asid_bitmap: holds used/available ASIDs.
1099  * @asid_mutex: protects asid_bitmap.
1100  * @fd_open_cnt_lock: lock for updating fd_open_cnt in hl_device_open. Although
1101  *                    fd_open_cnt is atomic, we need this lock to serialize
1102  *                    the open function because the driver currently supports
1103  *                    only a single process at a time. In addition, we need a
1104  *                    lock here so we can flush user processes which are opening
1105  *                    the device while we are trying to hard reset it
1106  * @send_cpu_message_lock: enforces only one message in KMD <-> ArmCP queue.
1107  * @asic_prop: ASIC specific immutable properties.
1108  * @asic_funcs: ASIC specific functions.
1109  * @asic_specific: ASIC specific information to use only from ASIC files.
1110  * @mmu_pgt_pool: pool of available MMU hops.
1111  * @vm: virtual memory manager for MMU.
1112  * @mmu_cache_lock: protects MMU cache invalidation as it can serve one context.
1113  * @mmu_shadow_hop0: shadow mapping of the MMU hop 0 zone.
1114  * @hwmon_dev: H/W monitor device.
1115  * @pm_mng_profile: current power management profile.
1116  * @hl_chip_info: ASIC's sensors information.
1117  * @hl_debugfs: device's debugfs manager.
1118  * @cb_pool: list of preallocated CBs.
1119  * @cb_pool_lock: protects the CB pool.
1120  * @user_ctx: current user context executing.
1121  * @dram_used_mem: current DRAM memory consumption.
1122  * @timeout_jiffies: device CS timeout value.
1123  * @max_power: the max power of the device, as configured by the sysadmin. This
1124  *             value is saved so in case of hard-reset, KMD will restore this
1125  *             value and update the F/W after the re-initialization
1126  * @in_reset: is device in reset flow.
1127  * @curr_pll_profile: current PLL profile.
1128  * @fd_open_cnt: number of open user processes.
1129  * @cs_active_cnt: number of active command submissions on this device (active
1130  *                 means already in H/W queues)
1131  * @major: habanalabs KMD major.
1132  * @high_pll: high PLL profile frequency.
1133  * @soft_reset_cnt: number of soft reset since KMD loading.
1134  * @hard_reset_cnt: number of hard reset since KMD loading.
1135  * @id: device minor.
1136  * @disabled: is device disabled.
1137  * @late_init_done: is late init stage was done during initialization.
1138  * @hwmon_initialized: is H/W monitor sensors was initialized.
1139  * @hard_reset_pending: is there a hard reset work pending.
1140  * @heartbeat: is heartbeat sanity check towards ArmCP enabled.
1141  * @reset_on_lockup: true if a reset should be done in case of stuck CS, false
1142  *                   otherwise.
1143  * @dram_supports_virtual_memory: is MMU enabled towards DRAM.
1144  * @dram_default_page_mapping: is DRAM default page mapping enabled.
1145  * @init_done: is the initialization of the device done.
1146  * @mmu_enable: is MMU enabled.
1147  * @device_cpu_disabled: is the device CPU disabled (due to timeouts)
1148  * @dma_mask: the dma mask that was set for this device
1149  */
1150 struct hl_device {
1151         struct pci_dev                  *pdev;
1152         void __iomem                    *pcie_bar[6];
1153         void __iomem                    *rmmio;
1154         struct cdev                     cdev;
1155         struct device                   *dev;
1156         struct delayed_work             work_freq;
1157         struct delayed_work             work_heartbeat;
1158         char                            asic_name[16];
1159         enum hl_asic_type               asic_type;
1160         struct hl_cq                    *completion_queue;
1161         struct workqueue_struct         *cq_wq;
1162         struct workqueue_struct         *eq_wq;
1163         struct hl_ctx                   *kernel_ctx;
1164         struct hl_hw_queue              *kernel_queues;
1165         struct list_head                hw_queues_mirror_list;
1166         spinlock_t                      hw_queues_mirror_lock;
1167         struct hl_cb_mgr                kernel_cb_mgr;
1168         struct hl_eq                    event_queue;
1169         struct dma_pool                 *dma_pool;
1170         void                            *cpu_accessible_dma_mem;
1171         dma_addr_t                      cpu_accessible_dma_address;
1172         struct gen_pool                 *cpu_accessible_dma_pool;
1173         unsigned long                   *asid_bitmap;
1174         struct mutex                    asid_mutex;
1175         /* TODO: remove fd_open_cnt_lock for multiple process support */
1176         struct mutex                    fd_open_cnt_lock;
1177         struct mutex                    send_cpu_message_lock;
1178         struct asic_fixed_properties    asic_prop;
1179         const struct hl_asic_funcs      *asic_funcs;
1180         void                            *asic_specific;
1181         struct gen_pool                 *mmu_pgt_pool;
1182         struct hl_vm                    vm;
1183         struct mutex                    mmu_cache_lock;
1184         void                            *mmu_shadow_hop0;
1185         struct device                   *hwmon_dev;
1186         enum hl_pm_mng_profile          pm_mng_profile;
1187         struct hwmon_chip_info          *hl_chip_info;
1188
1189         struct hl_dbg_device_entry      hl_debugfs;
1190
1191         struct list_head                cb_pool;
1192         spinlock_t                      cb_pool_lock;
1193
1194         /* TODO: remove user_ctx for multiple process support */
1195         struct hl_ctx                   *user_ctx;
1196
1197         atomic64_t                      dram_used_mem;
1198         u64                             timeout_jiffies;
1199         u64                             max_power;
1200         atomic_t                        in_reset;
1201         atomic_t                        curr_pll_profile;
1202         atomic_t                        fd_open_cnt;
1203         atomic_t                        cs_active_cnt;
1204         u32                             major;
1205         u32                             high_pll;
1206         u32                             soft_reset_cnt;
1207         u32                             hard_reset_cnt;
1208         u16                             id;
1209         u8                              disabled;
1210         u8                              late_init_done;
1211         u8                              hwmon_initialized;
1212         u8                              hard_reset_pending;
1213         u8                              heartbeat;
1214         u8                              reset_on_lockup;
1215         u8                              dram_supports_virtual_memory;
1216         u8                              dram_default_page_mapping;
1217         u8                              init_done;
1218         u8                              device_cpu_disabled;
1219         u8                              dma_mask;
1220
1221         /* Parameters for bring-up */
1222         u8                              mmu_enable;
1223         u8                              cpu_enable;
1224         u8                              reset_pcilink;
1225         u8                              cpu_queues_enable;
1226         u8                              fw_loading;
1227         u8                              pldm;
1228 };
1229
1230
1231 /*
1232  * IOCTLs
1233  */
1234
1235 /**
1236  * typedef hl_ioctl_t - typedef for ioctl function in the driver
1237  * @hpriv: pointer to the FD's private data, which contains state of
1238  *              user process
1239  * @data: pointer to the input/output arguments structure of the IOCTL
1240  *
1241  * Return: 0 for success, negative value for error
1242  */
1243 typedef int hl_ioctl_t(struct hl_fpriv *hpriv, void *data);
1244
1245 /**
1246  * struct hl_ioctl_desc - describes an IOCTL entry of the driver.
1247  * @cmd: the IOCTL code as created by the kernel macros.
1248  * @func: pointer to the driver's function that should be called for this IOCTL.
1249  */
1250 struct hl_ioctl_desc {
1251         unsigned int cmd;
1252         hl_ioctl_t *func;
1253 };
1254
1255
1256 /*
1257  * Kernel module functions that can be accessed by entire module
1258  */
1259
1260 /**
1261  * hl_mem_area_inside_range() - Checks whether address+size are inside a range.
1262  * @address: The start address of the area we want to validate.
1263  * @size: The size in bytes of the area we want to validate.
1264  * @range_start_address: The start address of the valid range.
1265  * @range_end_address: The end address of the valid range.
1266  *
1267  * Return: true if the area is inside the valid range, false otherwise.
1268  */
1269 static inline bool hl_mem_area_inside_range(u64 address, u32 size,
1270                                 u64 range_start_address, u64 range_end_address)
1271 {
1272         u64 end_address = address + size;
1273
1274         if ((address >= range_start_address) &&
1275                         (end_address <= range_end_address) &&
1276                         (end_address > address))
1277                 return true;
1278
1279         return false;
1280 }
1281
1282 /**
1283  * hl_mem_area_crosses_range() - Checks whether address+size crossing a range.
1284  * @address: The start address of the area we want to validate.
1285  * @size: The size in bytes of the area we want to validate.
1286  * @range_start_address: The start address of the valid range.
1287  * @range_end_address: The end address of the valid range.
1288  *
1289  * Return: true if the area overlaps part or all of the valid range,
1290  *              false otherwise.
1291  */
1292 static inline bool hl_mem_area_crosses_range(u64 address, u32 size,
1293                                 u64 range_start_address, u64 range_end_address)
1294 {
1295         u64 end_address = address + size;
1296
1297         if ((address >= range_start_address) &&
1298                         (address < range_end_address))
1299                 return true;
1300
1301         if ((end_address >= range_start_address) &&
1302                         (end_address < range_end_address))
1303                 return true;
1304
1305         if ((address < range_start_address) &&
1306                         (end_address >= range_end_address))
1307                 return true;
1308
1309         return false;
1310 }
1311
1312 int hl_device_open(struct inode *inode, struct file *filp);
1313 bool hl_device_disabled_or_in_reset(struct hl_device *hdev);
1314 enum hl_device_status hl_device_status(struct hl_device *hdev);
1315 int create_hdev(struct hl_device **dev, struct pci_dev *pdev,
1316                 enum hl_asic_type asic_type, int minor);
1317 void destroy_hdev(struct hl_device *hdev);
1318 int hl_poll_timeout_memory(struct hl_device *hdev, u64 addr, u32 timeout_us,
1319                                 u32 *val);
1320 int hl_poll_timeout_device_memory(struct hl_device *hdev, void __iomem *addr,
1321                                 u32 timeout_us, u32 *val);
1322 int hl_hw_queues_create(struct hl_device *hdev);
1323 void hl_hw_queues_destroy(struct hl_device *hdev);
1324 int hl_hw_queue_send_cb_no_cmpl(struct hl_device *hdev, u32 hw_queue_id,
1325                                 u32 cb_size, u64 cb_ptr);
1326 int hl_hw_queue_schedule_cs(struct hl_cs *cs);
1327 u32 hl_hw_queue_add_ptr(u32 ptr, u16 val);
1328 void hl_hw_queue_inc_ci_kernel(struct hl_device *hdev, u32 hw_queue_id);
1329 void hl_int_hw_queue_update_ci(struct hl_cs *cs);
1330 void hl_hw_queue_reset(struct hl_device *hdev, bool hard_reset);
1331
1332 #define hl_queue_inc_ptr(p)             hl_hw_queue_add_ptr(p, 1)
1333 #define hl_pi_2_offset(pi)              ((pi) & (HL_QUEUE_LENGTH - 1))
1334
1335 int hl_cq_init(struct hl_device *hdev, struct hl_cq *q, u32 hw_queue_id);
1336 void hl_cq_fini(struct hl_device *hdev, struct hl_cq *q);
1337 int hl_eq_init(struct hl_device *hdev, struct hl_eq *q);
1338 void hl_eq_fini(struct hl_device *hdev, struct hl_eq *q);
1339 void hl_cq_reset(struct hl_device *hdev, struct hl_cq *q);
1340 void hl_eq_reset(struct hl_device *hdev, struct hl_eq *q);
1341 irqreturn_t hl_irq_handler_cq(int irq, void *arg);
1342 irqreturn_t hl_irq_handler_eq(int irq, void *arg);
1343 u32 hl_cq_inc_ptr(u32 ptr);
1344
1345 int hl_asid_init(struct hl_device *hdev);
1346 void hl_asid_fini(struct hl_device *hdev);
1347 unsigned long hl_asid_alloc(struct hl_device *hdev);
1348 void hl_asid_free(struct hl_device *hdev, unsigned long asid);
1349
1350 int hl_ctx_create(struct hl_device *hdev, struct hl_fpriv *hpriv);
1351 void hl_ctx_free(struct hl_device *hdev, struct hl_ctx *ctx);
1352 int hl_ctx_init(struct hl_device *hdev, struct hl_ctx *ctx, bool is_kernel_ctx);
1353 void hl_ctx_do_release(struct kref *ref);
1354 void hl_ctx_get(struct hl_device *hdev, struct hl_ctx *ctx);
1355 int hl_ctx_put(struct hl_ctx *ctx);
1356 struct dma_fence *hl_ctx_get_fence(struct hl_ctx *ctx, u64 seq);
1357 void hl_ctx_mgr_init(struct hl_ctx_mgr *mgr);
1358 void hl_ctx_mgr_fini(struct hl_device *hdev, struct hl_ctx_mgr *mgr);
1359
1360 int hl_device_init(struct hl_device *hdev, struct class *hclass);
1361 void hl_device_fini(struct hl_device *hdev);
1362 int hl_device_suspend(struct hl_device *hdev);
1363 int hl_device_resume(struct hl_device *hdev);
1364 int hl_device_reset(struct hl_device *hdev, bool hard_reset,
1365                         bool from_hard_reset_thread);
1366 void hl_hpriv_get(struct hl_fpriv *hpriv);
1367 void hl_hpriv_put(struct hl_fpriv *hpriv);
1368 int hl_device_set_frequency(struct hl_device *hdev, enum hl_pll_frequency freq);
1369
1370 int hl_build_hwmon_channel_info(struct hl_device *hdev,
1371                 struct armcp_sensor *sensors_arr);
1372
1373 int hl_sysfs_init(struct hl_device *hdev);
1374 void hl_sysfs_fini(struct hl_device *hdev);
1375
1376 int hl_hwmon_init(struct hl_device *hdev);
1377 void hl_hwmon_fini(struct hl_device *hdev);
1378
1379 int hl_cb_create(struct hl_device *hdev, struct hl_cb_mgr *mgr, u32 cb_size,
1380                 u64 *handle, int ctx_id);
1381 int hl_cb_destroy(struct hl_device *hdev, struct hl_cb_mgr *mgr, u64 cb_handle);
1382 int hl_cb_mmap(struct hl_fpriv *hpriv, struct vm_area_struct *vma);
1383 struct hl_cb *hl_cb_get(struct hl_device *hdev, struct hl_cb_mgr *mgr,
1384                         u32 handle);
1385 void hl_cb_put(struct hl_cb *cb);
1386 void hl_cb_mgr_init(struct hl_cb_mgr *mgr);
1387 void hl_cb_mgr_fini(struct hl_device *hdev, struct hl_cb_mgr *mgr);
1388 struct hl_cb *hl_cb_kernel_create(struct hl_device *hdev, u32 cb_size);
1389 int hl_cb_pool_init(struct hl_device *hdev);
1390 int hl_cb_pool_fini(struct hl_device *hdev);
1391
1392 void hl_cs_rollback_all(struct hl_device *hdev);
1393 struct hl_cs_job *hl_cs_allocate_job(struct hl_device *hdev, bool ext_queue);
1394
1395 void goya_set_asic_funcs(struct hl_device *hdev);
1396
1397 int hl_vm_ctx_init(struct hl_ctx *ctx);
1398 void hl_vm_ctx_fini(struct hl_ctx *ctx);
1399
1400 int hl_vm_init(struct hl_device *hdev);
1401 void hl_vm_fini(struct hl_device *hdev);
1402
1403 int hl_pin_host_memory(struct hl_device *hdev, u64 addr, u64 size,
1404                         struct hl_userptr *userptr);
1405 int hl_unpin_host_memory(struct hl_device *hdev, struct hl_userptr *userptr);
1406 void hl_userptr_delete_list(struct hl_device *hdev,
1407                                 struct list_head *userptr_list);
1408 bool hl_userptr_is_pinned(struct hl_device *hdev, u64 addr, u32 size,
1409                                 struct list_head *userptr_list,
1410                                 struct hl_userptr **userptr);
1411
1412 int hl_mmu_init(struct hl_device *hdev);
1413 void hl_mmu_fini(struct hl_device *hdev);
1414 int hl_mmu_ctx_init(struct hl_ctx *ctx);
1415 void hl_mmu_ctx_fini(struct hl_ctx *ctx);
1416 int hl_mmu_map(struct hl_ctx *ctx, u64 virt_addr, u64 phys_addr, u32 page_size);
1417 int hl_mmu_unmap(struct hl_ctx *ctx, u64 virt_addr, u32 page_size);
1418 void hl_mmu_swap_out(struct hl_ctx *ctx);
1419 void hl_mmu_swap_in(struct hl_ctx *ctx);
1420
1421 int hl_fw_push_fw_to_device(struct hl_device *hdev, const char *fw_name,
1422                                 void __iomem *dst);
1423 int hl_fw_send_pci_access_msg(struct hl_device *hdev, u32 opcode);
1424 int hl_fw_send_cpu_message(struct hl_device *hdev, u32 hw_queue_id, u32 *msg,
1425                                 u16 len, u32 timeout, long *result);
1426 int hl_fw_test_cpu_queue(struct hl_device *hdev);
1427 void *hl_fw_cpu_accessible_dma_pool_alloc(struct hl_device *hdev, size_t size,
1428                                                 dma_addr_t *dma_handle);
1429 void hl_fw_cpu_accessible_dma_pool_free(struct hl_device *hdev, size_t size,
1430                                         void *vaddr);
1431 int hl_fw_send_heartbeat(struct hl_device *hdev);
1432 int hl_fw_armcp_info_get(struct hl_device *hdev);
1433 int hl_fw_get_eeprom_data(struct hl_device *hdev, void *data, size_t max_size);
1434
1435 int hl_pci_bars_map(struct hl_device *hdev, const char * const name[3],
1436                         bool is_wc[3]);
1437 int hl_pci_iatu_write(struct hl_device *hdev, u32 addr, u32 data);
1438 int hl_pci_set_dram_bar_base(struct hl_device *hdev, u8 inbound_region, u8 bar,
1439                                 u64 addr);
1440 int hl_pci_init_iatu(struct hl_device *hdev, u64 sram_base_address,
1441                         u64 dram_base_address, u64 host_phys_size);
1442 int hl_pci_init(struct hl_device *hdev, u8 dma_mask);
1443 void hl_pci_fini(struct hl_device *hdev);
1444 int hl_pci_set_dma_mask(struct hl_device *hdev, u8 dma_mask);
1445
1446 long hl_get_frequency(struct hl_device *hdev, u32 pll_index, bool curr);
1447 void hl_set_frequency(struct hl_device *hdev, u32 pll_index, u64 freq);
1448 long hl_get_temperature(struct hl_device *hdev, int sensor_index, u32 attr);
1449 long hl_get_voltage(struct hl_device *hdev, int sensor_index, u32 attr);
1450 long hl_get_current(struct hl_device *hdev, int sensor_index, u32 attr);
1451 long hl_get_fan_speed(struct hl_device *hdev, int sensor_index, u32 attr);
1452 long hl_get_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr);
1453 void hl_set_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr,
1454                         long value);
1455 u64 hl_get_max_power(struct hl_device *hdev);
1456 void hl_set_max_power(struct hl_device *hdev, u64 value);
1457
1458 #ifdef CONFIG_DEBUG_FS
1459
1460 void hl_debugfs_init(void);
1461 void hl_debugfs_fini(void);
1462 void hl_debugfs_add_device(struct hl_device *hdev);
1463 void hl_debugfs_remove_device(struct hl_device *hdev);
1464 void hl_debugfs_add_file(struct hl_fpriv *hpriv);
1465 void hl_debugfs_remove_file(struct hl_fpriv *hpriv);
1466 void hl_debugfs_add_cb(struct hl_cb *cb);
1467 void hl_debugfs_remove_cb(struct hl_cb *cb);
1468 void hl_debugfs_add_cs(struct hl_cs *cs);
1469 void hl_debugfs_remove_cs(struct hl_cs *cs);
1470 void hl_debugfs_add_job(struct hl_device *hdev, struct hl_cs_job *job);
1471 void hl_debugfs_remove_job(struct hl_device *hdev, struct hl_cs_job *job);
1472 void hl_debugfs_add_userptr(struct hl_device *hdev, struct hl_userptr *userptr);
1473 void hl_debugfs_remove_userptr(struct hl_device *hdev,
1474                                 struct hl_userptr *userptr);
1475 void hl_debugfs_add_ctx_mem_hash(struct hl_device *hdev, struct hl_ctx *ctx);
1476 void hl_debugfs_remove_ctx_mem_hash(struct hl_device *hdev, struct hl_ctx *ctx);
1477
1478 #else
1479
1480 static inline void __init hl_debugfs_init(void)
1481 {
1482 }
1483
1484 static inline void hl_debugfs_fini(void)
1485 {
1486 }
1487
1488 static inline void hl_debugfs_add_device(struct hl_device *hdev)
1489 {
1490 }
1491
1492 static inline void hl_debugfs_remove_device(struct hl_device *hdev)
1493 {
1494 }
1495
1496 static inline void hl_debugfs_add_file(struct hl_fpriv *hpriv)
1497 {
1498 }
1499
1500 static inline void hl_debugfs_remove_file(struct hl_fpriv *hpriv)
1501 {
1502 }
1503
1504 static inline void hl_debugfs_add_cb(struct hl_cb *cb)
1505 {
1506 }
1507
1508 static inline void hl_debugfs_remove_cb(struct hl_cb *cb)
1509 {
1510 }
1511
1512 static inline void hl_debugfs_add_cs(struct hl_cs *cs)
1513 {
1514 }
1515
1516 static inline void hl_debugfs_remove_cs(struct hl_cs *cs)
1517 {
1518 }
1519
1520 static inline void hl_debugfs_add_job(struct hl_device *hdev,
1521                                         struct hl_cs_job *job)
1522 {
1523 }
1524
1525 static inline void hl_debugfs_remove_job(struct hl_device *hdev,
1526                                         struct hl_cs_job *job)
1527 {
1528 }
1529
1530 static inline void hl_debugfs_add_userptr(struct hl_device *hdev,
1531                                         struct hl_userptr *userptr)
1532 {
1533 }
1534
1535 static inline void hl_debugfs_remove_userptr(struct hl_device *hdev,
1536                                         struct hl_userptr *userptr)
1537 {
1538 }
1539
1540 static inline void hl_debugfs_add_ctx_mem_hash(struct hl_device *hdev,
1541                                         struct hl_ctx *ctx)
1542 {
1543 }
1544
1545 static inline void hl_debugfs_remove_ctx_mem_hash(struct hl_device *hdev,
1546                                         struct hl_ctx *ctx)
1547 {
1548 }
1549
1550 #endif
1551
1552 /* IOCTLs */
1553 long hl_ioctl(struct file *filep, unsigned int cmd, unsigned long arg);
1554 int hl_cb_ioctl(struct hl_fpriv *hpriv, void *data);
1555 int hl_cs_ioctl(struct hl_fpriv *hpriv, void *data);
1556 int hl_cs_wait_ioctl(struct hl_fpriv *hpriv, void *data);
1557 int hl_mem_ioctl(struct hl_fpriv *hpriv, void *data);
1558
1559 #endif /* HABANALABSP_H_ */