1 // SPDX-License-Identifier: GPL-2.0
2 
3 /*
4  * Copyright 2016-2022 HabanaLabs, Ltd.
5  * All Rights Reserved.
6  */
7 
8 #include <uapi/drm/habanalabs_accel.h>
9 #include "habanalabs.h"
10 #include "../include/hw_ip/mmu/mmu_general.h"
11 
12 #include <linux/uaccess.h>
13 #include <linux/slab.h>
14 #include <linux/vmalloc.h>
15 #include <linux/pci-p2pdma.h>
16 
17 MODULE_IMPORT_NS(DMA_BUF);
18 
19 #define HL_MMU_DEBUG	0
20 
21 /* use small pages for supporting non-pow2 (32M/40M/48M) DRAM phys page sizes */
22 #define DRAM_POOL_PAGE_SIZE	SZ_8M
23 
24 #define MEM_HANDLE_INVALID	ULONG_MAX
25 
26 static int allocate_timestamps_buffers(struct hl_fpriv *hpriv,
27 			struct hl_mem_in *args, u64 *handle);
28 
29 static int set_alloc_page_size(struct hl_device *hdev, struct hl_mem_in *args, u32 *page_size)
30 {
31 	struct asic_fixed_properties *prop = &hdev->asic_prop;
32 	u64 psize;
33 
34 	/*
35 	 * for ASIC that supports setting the allocation page size by user we will address
36 	 * user's choice only if it is not 0 (as 0 means taking the default page size)
37 	 */
38 	if (prop->supports_user_set_page_size && args->alloc.page_size) {
39 		psize = args->alloc.page_size;
40 
41 		if (!is_power_of_2(psize)) {
42 			dev_err(hdev->dev, "user page size (%#llx) is not power of 2\n", psize);
43 			return -EINVAL;
44 		}
45 	} else {
46 		psize = prop->device_mem_alloc_default_page_size;
47 	}
48 
49 	*page_size = psize;
50 
51 	return 0;
52 }
53 
54 /*
55  * The va ranges in context object contain a list with the available chunks of
56  * device virtual memory.
57  * There is one range for host allocations and one for DRAM allocations.
58  *
59  * On initialization each range contains one chunk of all of its available
60  * virtual range which is a half of the total device virtual range.
61  *
62  * On each mapping of physical pages, a suitable virtual range chunk (with a
63  * minimum size) is selected from the list. If the chunk size equals the
64  * requested size, the chunk is returned. Otherwise, the chunk is split into
65  * two chunks - one to return as result and a remainder to stay in the list.
66  *
67  * On each Unmapping of a virtual address, the relevant virtual chunk is
68  * returned to the list. The chunk is added to the list and if its edges match
69  * the edges of the adjacent chunks (means a contiguous chunk can be created),
70  * the chunks are merged.
71  *
72  * On finish, the list is checked to have only one chunk of all the relevant
73  * virtual range (which is a half of the device total virtual range).
74  * If not (means not all mappings were unmapped), a warning is printed.
75  */
76 
77 /*
78  * alloc_device_memory() - allocate device memory.
79  * @ctx: pointer to the context structure.
80  * @args: host parameters containing the requested size.
81  * @ret_handle: result handle.
82  *
83  * This function does the following:
84  * - Allocate the requested size rounded up to 'dram_page_size' pages.
85  * - Return unique handle for later map/unmap/free.
86  */
87 static int alloc_device_memory(struct hl_ctx *ctx, struct hl_mem_in *args,
88 				u32 *ret_handle)
89 {
90 	struct hl_device *hdev = ctx->hdev;
91 	struct hl_vm *vm = &hdev->vm;
92 	struct hl_vm_phys_pg_pack *phys_pg_pack;
93 	u64 paddr = 0, total_size, num_pgs, i;
94 	u32 num_curr_pgs, page_size;
95 	bool contiguous;
96 	int handle, rc;
97 
98 	num_curr_pgs = 0;
99 
100 	rc = set_alloc_page_size(hdev, args, &page_size);
101 	if (rc)
102 		return rc;
103 
104 	num_pgs = DIV_ROUND_UP_ULL(args->alloc.mem_size, page_size);
105 	total_size = num_pgs * page_size;
106 
107 	if (!total_size) {
108 		dev_err(hdev->dev, "Cannot allocate 0 bytes\n");
109 		return -EINVAL;
110 	}
111 
112 	contiguous = args->flags & HL_MEM_CONTIGUOUS;
113 
114 	if (contiguous) {
115 		if (is_power_of_2(page_size))
116 			paddr = (uintptr_t) gen_pool_dma_alloc_align(vm->dram_pg_pool,
117 								     total_size, NULL, page_size);
118 		else
119 			paddr = gen_pool_alloc(vm->dram_pg_pool, total_size);
120 		if (!paddr) {
121 			dev_err(hdev->dev,
122 				"Cannot allocate %llu contiguous pages with total size of %llu\n",
123 				num_pgs, total_size);
124 			return -ENOMEM;
125 		}
126 	}
127 
128 	phys_pg_pack = kzalloc(sizeof(*phys_pg_pack), GFP_KERNEL);
129 	if (!phys_pg_pack) {
130 		rc = -ENOMEM;
131 		goto pages_pack_err;
132 	}
133 
134 	phys_pg_pack->vm_type = VM_TYPE_PHYS_PACK;
135 	phys_pg_pack->asid = ctx->asid;
136 	phys_pg_pack->npages = num_pgs;
137 	phys_pg_pack->page_size = page_size;
138 	phys_pg_pack->total_size = total_size;
139 	phys_pg_pack->flags = args->flags;
140 	phys_pg_pack->contiguous = contiguous;
141 
142 	phys_pg_pack->pages = kvmalloc_array(num_pgs, sizeof(u64), GFP_KERNEL);
143 	if (ZERO_OR_NULL_PTR(phys_pg_pack->pages)) {
144 		rc = -ENOMEM;
145 		goto pages_arr_err;
146 	}
147 
148 	if (phys_pg_pack->contiguous) {
149 		for (i = 0 ; i < num_pgs ; i++)
150 			phys_pg_pack->pages[i] = paddr + i * page_size;
151 	} else {
152 		for (i = 0 ; i < num_pgs ; i++) {
153 			if (is_power_of_2(page_size))
154 				phys_pg_pack->pages[i] =
155 					(uintptr_t)gen_pool_dma_alloc_align(vm->dram_pg_pool,
156 									    page_size, NULL,
157 									    page_size);
158 			else
159 				phys_pg_pack->pages[i] = gen_pool_alloc(vm->dram_pg_pool,
160 									page_size);
161 
162 			if (!phys_pg_pack->pages[i]) {
163 				dev_err(hdev->dev,
164 					"Cannot allocate device memory (out of memory)\n");
165 				rc = -ENOMEM;
166 				goto page_err;
167 			}
168 
169 			num_curr_pgs++;
170 		}
171 	}
172 
173 	spin_lock(&vm->idr_lock);
174 	handle = idr_alloc(&vm->phys_pg_pack_handles, phys_pg_pack, 1, 0,
175 				GFP_ATOMIC);
176 	spin_unlock(&vm->idr_lock);
177 
178 	if (handle < 0) {
179 		dev_err(hdev->dev, "Failed to get handle for page\n");
180 		rc = -EFAULT;
181 		goto idr_err;
182 	}
183 
184 	for (i = 0 ; i < num_pgs ; i++)
185 		kref_get(&vm->dram_pg_pool_refcount);
186 
187 	phys_pg_pack->handle = handle;
188 
189 	atomic64_add(phys_pg_pack->total_size, &ctx->dram_phys_mem);
190 	atomic64_add(phys_pg_pack->total_size, &hdev->dram_used_mem);
191 
192 	*ret_handle = handle;
193 
194 	return 0;
195 
196 idr_err:
197 page_err:
198 	if (!phys_pg_pack->contiguous)
199 		for (i = 0 ; i < num_curr_pgs ; i++)
200 			gen_pool_free(vm->dram_pg_pool, phys_pg_pack->pages[i],
201 					page_size);
202 
203 	kvfree(phys_pg_pack->pages);
204 pages_arr_err:
205 	kfree(phys_pg_pack);
206 pages_pack_err:
207 	if (contiguous)
208 		gen_pool_free(vm->dram_pg_pool, paddr, total_size);
209 
210 	return rc;
211 }
212 
213 /**
214  * dma_map_host_va() - DMA mapping of the given host virtual address.
215  * @hdev: habanalabs device structure.
216  * @addr: the host virtual address of the memory area.
217  * @size: the size of the memory area.
218  * @p_userptr: pointer to result userptr structure.
219  *
220  * This function does the following:
221  * - Allocate userptr structure.
222  * - Pin the given host memory using the userptr structure.
223  * - Perform DMA mapping to have the DMA addresses of the pages.
224  */
225 static int dma_map_host_va(struct hl_device *hdev, u64 addr, u64 size,
226 				struct hl_userptr **p_userptr)
227 {
228 	struct hl_userptr *userptr;
229 	int rc;
230 
231 	userptr = kzalloc(sizeof(*userptr), GFP_KERNEL);
232 	if (!userptr) {
233 		rc = -ENOMEM;
234 		goto userptr_err;
235 	}
236 
237 	rc = hl_pin_host_memory(hdev, addr, size, userptr);
238 	if (rc)
239 		goto pin_err;
240 
241 	userptr->dma_mapped = true;
242 	userptr->dir = DMA_BIDIRECTIONAL;
243 	userptr->vm_type = VM_TYPE_USERPTR;
244 
245 	*p_userptr = userptr;
246 
247 	rc = hdev->asic_funcs->asic_dma_map_sgtable(hdev, userptr->sgt, DMA_BIDIRECTIONAL);
248 	if (rc) {
249 		dev_err(hdev->dev, "failed to map sgt with DMA region\n");
250 		goto dma_map_err;
251 	}
252 
253 	return 0;
254 
255 dma_map_err:
256 	hl_unpin_host_memory(hdev, userptr);
257 pin_err:
258 	kfree(userptr);
259 userptr_err:
260 
261 	return rc;
262 }
263 
264 /**
265  * dma_unmap_host_va() - DMA unmapping of the given host virtual address.
266  * @hdev: habanalabs device structure.
267  * @userptr: userptr to free.
268  *
269  * This function does the following:
270  * - Unpins the physical pages.
271  * - Frees the userptr structure.
272  */
273 static void dma_unmap_host_va(struct hl_device *hdev,
274 				struct hl_userptr *userptr)
275 {
276 	hl_unpin_host_memory(hdev, userptr);
277 	kfree(userptr);
278 }
279 
280 /**
281  * dram_pg_pool_do_release() - free DRAM pages pool
282  * @ref: pointer to reference object.
283  *
284  * This function does the following:
285  * - Frees the idr structure of physical pages handles.
286  * - Frees the generic pool of DRAM physical pages.
287  */
288 static void dram_pg_pool_do_release(struct kref *ref)
289 {
290 	struct hl_vm *vm = container_of(ref, struct hl_vm,
291 			dram_pg_pool_refcount);
292 
293 	/*
294 	 * free the idr here as only here we know for sure that there are no
295 	 * allocated physical pages and hence there are no handles in use
296 	 */
297 	idr_destroy(&vm->phys_pg_pack_handles);
298 	gen_pool_destroy(vm->dram_pg_pool);
299 }
300 
301 /**
302  * free_phys_pg_pack() - free physical page pack.
303  * @hdev: habanalabs device structure.
304  * @phys_pg_pack: physical page pack to free.
305  *
306  * This function does the following:
307  * - For DRAM memory only
308  *   - iterate over the pack, free each physical block structure by
309  *     returning it to the general pool.
310  * - Free the hl_vm_phys_pg_pack structure.
311  */
312 static void free_phys_pg_pack(struct hl_device *hdev,
313 				struct hl_vm_phys_pg_pack *phys_pg_pack)
314 {
315 	struct hl_vm *vm = &hdev->vm;
316 	u64 i;
317 
318 	if (phys_pg_pack->created_from_userptr)
319 		goto end;
320 
321 	if (phys_pg_pack->contiguous) {
322 		gen_pool_free(vm->dram_pg_pool, phys_pg_pack->pages[0],
323 			phys_pg_pack->total_size);
324 
325 		for (i = 0; i < phys_pg_pack->npages ; i++)
326 			kref_put(&vm->dram_pg_pool_refcount,
327 				dram_pg_pool_do_release);
328 	} else {
329 		for (i = 0 ; i < phys_pg_pack->npages ; i++) {
330 			gen_pool_free(vm->dram_pg_pool,
331 				phys_pg_pack->pages[i],
332 				phys_pg_pack->page_size);
333 			kref_put(&vm->dram_pg_pool_refcount,
334 				dram_pg_pool_do_release);
335 		}
336 	}
337 
338 end:
339 	kvfree(phys_pg_pack->pages);
340 	kfree(phys_pg_pack);
341 
342 	return;
343 }
344 
345 /**
346  * free_device_memory() - free device memory.
347  * @ctx: pointer to the context structure.
348  * @args: host parameters containing the requested size.
349  *
350  * This function does the following:
351  * - Free the device memory related to the given handle.
352  */
353 static int free_device_memory(struct hl_ctx *ctx, struct hl_mem_in *args)
354 {
355 	struct hl_device *hdev = ctx->hdev;
356 	struct hl_vm *vm = &hdev->vm;
357 	struct hl_vm_phys_pg_pack *phys_pg_pack;
358 	u32 handle = args->free.handle;
359 
360 	spin_lock(&vm->idr_lock);
361 	phys_pg_pack = idr_find(&vm->phys_pg_pack_handles, handle);
362 	if (!phys_pg_pack) {
363 		spin_unlock(&vm->idr_lock);
364 		dev_err(hdev->dev, "free device memory failed, no match for handle %u\n", handle);
365 		return -EINVAL;
366 	}
367 
368 	if (atomic_read(&phys_pg_pack->mapping_cnt) > 0) {
369 		spin_unlock(&vm->idr_lock);
370 		dev_err(hdev->dev, "handle %u is mapped, cannot free\n", handle);
371 		return -EINVAL;
372 	}
373 
374 	/* must remove from idr before the freeing of the physical pages as the refcount of the pool
375 	 * is also the trigger of the idr destroy
376 	 */
377 	idr_remove(&vm->phys_pg_pack_handles, handle);
378 	spin_unlock(&vm->idr_lock);
379 
380 	atomic64_sub(phys_pg_pack->total_size, &ctx->dram_phys_mem);
381 	atomic64_sub(phys_pg_pack->total_size, &hdev->dram_used_mem);
382 
383 	free_phys_pg_pack(hdev, phys_pg_pack);
384 
385 	return 0;
386 }
387 
388 /**
389  * clear_va_list_locked() - free virtual addresses list.
390  * @hdev: habanalabs device structure.
391  * @va_list: list of virtual addresses to free.
392  *
393  * This function does the following:
394  * - Iterate over the list and free each virtual addresses block.
395  *
396  * This function should be called only when va_list lock is taken.
397  */
398 static void clear_va_list_locked(struct hl_device *hdev,
399 		struct list_head *va_list)
400 {
401 	struct hl_vm_va_block *va_block, *tmp;
402 
403 	list_for_each_entry_safe(va_block, tmp, va_list, node) {
404 		list_del(&va_block->node);
405 		kfree(va_block);
406 	}
407 }
408 
409 /**
410  * print_va_list_locked() - print virtual addresses list.
411  * @hdev: habanalabs device structure.
412  * @va_list: list of virtual addresses to print.
413  *
414  * This function does the following:
415  * - Iterate over the list and print each virtual addresses block.
416  *
417  * This function should be called only when va_list lock is taken.
418  */
419 static void print_va_list_locked(struct hl_device *hdev,
420 		struct list_head *va_list)
421 {
422 #if HL_MMU_DEBUG
423 	struct hl_vm_va_block *va_block;
424 
425 	dev_dbg(hdev->dev, "print va list:\n");
426 
427 	list_for_each_entry(va_block, va_list, node)
428 		dev_dbg(hdev->dev,
429 			"va block, start: 0x%llx, end: 0x%llx, size: %llu\n",
430 			va_block->start, va_block->end, va_block->size);
431 #endif
432 }
433 
434 /**
435  * merge_va_blocks_locked() - merge a virtual block if possible.
436  * @hdev: pointer to the habanalabs device structure.
437  * @va_list: pointer to the virtual addresses block list.
438  * @va_block: virtual block to merge with adjacent blocks.
439  *
440  * This function does the following:
441  * - Merge the given blocks with the adjacent blocks if their virtual ranges
442  *   create a contiguous virtual range.
443  *
444  * This Function should be called only when va_list lock is taken.
445  */
446 static void merge_va_blocks_locked(struct hl_device *hdev,
447 		struct list_head *va_list, struct hl_vm_va_block *va_block)
448 {
449 	struct hl_vm_va_block *prev, *next;
450 
451 	prev = list_prev_entry(va_block, node);
452 	if (&prev->node != va_list && prev->end + 1 == va_block->start) {
453 		prev->end = va_block->end;
454 		prev->size = prev->end - prev->start + 1;
455 		list_del(&va_block->node);
456 		kfree(va_block);
457 		va_block = prev;
458 	}
459 
460 	next = list_next_entry(va_block, node);
461 	if (&next->node != va_list && va_block->end + 1 == next->start) {
462 		next->start = va_block->start;
463 		next->size = next->end - next->start + 1;
464 		list_del(&va_block->node);
465 		kfree(va_block);
466 	}
467 }
468 
469 /**
470  * add_va_block_locked() - add a virtual block to the virtual addresses list.
471  * @hdev: pointer to the habanalabs device structure.
472  * @va_list: pointer to the virtual addresses block list.
473  * @start: start virtual address.
474  * @end: end virtual address.
475  *
476  * This function does the following:
477  * - Add the given block to the virtual blocks list and merge with other blocks
478  *   if a contiguous virtual block can be created.
479  *
480  * This Function should be called only when va_list lock is taken.
481  */
482 static int add_va_block_locked(struct hl_device *hdev,
483 		struct list_head *va_list, u64 start, u64 end)
484 {
485 	struct hl_vm_va_block *va_block, *res = NULL;
486 	u64 size = end - start + 1;
487 
488 	print_va_list_locked(hdev, va_list);
489 
490 	list_for_each_entry(va_block, va_list, node) {
491 		/* TODO: remove upon matureness */
492 		if (hl_mem_area_crosses_range(start, size, va_block->start,
493 				va_block->end)) {
494 			dev_err(hdev->dev,
495 				"block crossing ranges at start 0x%llx, end 0x%llx\n",
496 				va_block->start, va_block->end);
497 			return -EINVAL;
498 		}
499 
500 		if (va_block->end < start)
501 			res = va_block;
502 	}
503 
504 	va_block = kmalloc(sizeof(*va_block), GFP_KERNEL);
505 	if (!va_block)
506 		return -ENOMEM;
507 
508 	va_block->start = start;
509 	va_block->end = end;
510 	va_block->size = size;
511 
512 	if (!res)
513 		list_add(&va_block->node, va_list);
514 	else
515 		list_add(&va_block->node, &res->node);
516 
517 	merge_va_blocks_locked(hdev, va_list, va_block);
518 
519 	print_va_list_locked(hdev, va_list);
520 
521 	return 0;
522 }
523 
524 /**
525  * add_va_block() - wrapper for add_va_block_locked.
526  * @hdev: pointer to the habanalabs device structure.
527  * @va_range: pointer to the virtual addresses range object.
528  * @start: start virtual address.
529  * @end: end virtual address.
530  *
531  * This function does the following:
532  * - Takes the list lock and calls add_va_block_locked.
533  */
534 static inline int add_va_block(struct hl_device *hdev,
535 		struct hl_va_range *va_range, u64 start, u64 end)
536 {
537 	int rc;
538 
539 	mutex_lock(&va_range->lock);
540 	rc = add_va_block_locked(hdev, &va_range->list, start, end);
541 	mutex_unlock(&va_range->lock);
542 
543 	return rc;
544 }
545 
546 /**
547  * is_hint_crossing_range() - check if hint address crossing specified reserved.
548  * @range_type: virtual space range type.
549  * @start_addr: start virtual address.
550  * @size: block size.
551  * @prop: asic properties structure to retrieve reserved ranges from.
552  */
553 static inline bool is_hint_crossing_range(enum hl_va_range_type range_type,
554 		u64 start_addr, u32 size, struct asic_fixed_properties *prop) {
555 	bool range_cross;
556 
557 	if (range_type == HL_VA_RANGE_TYPE_DRAM)
558 		range_cross =
559 			hl_mem_area_crosses_range(start_addr, size,
560 			prop->hints_dram_reserved_va_range.start_addr,
561 			prop->hints_dram_reserved_va_range.end_addr);
562 	else if (range_type == HL_VA_RANGE_TYPE_HOST)
563 		range_cross =
564 			hl_mem_area_crosses_range(start_addr,	size,
565 			prop->hints_host_reserved_va_range.start_addr,
566 			prop->hints_host_reserved_va_range.end_addr);
567 	else
568 		range_cross =
569 			hl_mem_area_crosses_range(start_addr, size,
570 			prop->hints_host_hpage_reserved_va_range.start_addr,
571 			prop->hints_host_hpage_reserved_va_range.end_addr);
572 
573 	return range_cross;
574 }
575 
576 /**
577  * get_va_block() - get a virtual block for the given size and alignment.
578  *
579  * @hdev: pointer to the habanalabs device structure.
580  * @va_range: pointer to the virtual addresses range.
581  * @size: requested block size.
582  * @hint_addr: hint for requested address by the user.
583  * @va_block_align: required alignment of the virtual block start address.
584  * @range_type: va range type (host, dram)
585  * @flags: additional memory flags, currently only uses HL_MEM_FORCE_HINT
586  *
587  * This function does the following:
588  * - Iterate on the virtual block list to find a suitable virtual block for the
589  *   given size, hint address and alignment.
590  * - Reserve the requested block and update the list.
591  * - Return the start address of the virtual block.
592  */
593 static u64 get_va_block(struct hl_device *hdev,
594 				struct hl_va_range *va_range,
595 				u64 size, u64 hint_addr, u32 va_block_align,
596 				enum hl_va_range_type range_type,
597 				u32 flags)
598 {
599 	struct hl_vm_va_block *va_block, *new_va_block = NULL;
600 	struct asic_fixed_properties *prop = &hdev->asic_prop;
601 	u64 tmp_hint_addr, valid_start, valid_size, prev_start, prev_end,
602 		align_mask, reserved_valid_start = 0, reserved_valid_size = 0,
603 		dram_hint_mask = prop->dram_hints_align_mask;
604 	bool add_prev = false;
605 	bool is_align_pow_2  = is_power_of_2(va_range->page_size);
606 	bool is_hint_dram_addr = hl_is_dram_va(hdev, hint_addr);
607 	bool force_hint = flags & HL_MEM_FORCE_HINT;
608 	int rc;
609 
610 	if (is_align_pow_2)
611 		align_mask = ~((u64)va_block_align - 1);
612 	else
613 		/*
614 		 * with non-power-of-2 range we work only with page granularity
615 		 * and the start address is page aligned,
616 		 * so no need for alignment checking.
617 		 */
618 		size = DIV_ROUND_UP_ULL(size, va_range->page_size) *
619 							va_range->page_size;
620 
621 	tmp_hint_addr = hint_addr & ~dram_hint_mask;
622 
623 	/* Check if we need to ignore hint address */
624 	if ((is_align_pow_2 && (hint_addr & (va_block_align - 1))) ||
625 			(!is_align_pow_2 && is_hint_dram_addr &&
626 			do_div(tmp_hint_addr, va_range->page_size))) {
627 
628 		if (force_hint) {
629 			/* Hint must be respected, so here we just fail */
630 			dev_err(hdev->dev,
631 				"Hint address 0x%llx is not page aligned - cannot be respected\n",
632 				hint_addr);
633 			return 0;
634 		}
635 
636 		dev_dbg(hdev->dev,
637 			"Hint address 0x%llx will be ignored because it is not aligned\n",
638 			hint_addr);
639 		hint_addr = 0;
640 	}
641 
642 	mutex_lock(&va_range->lock);
643 
644 	print_va_list_locked(hdev, &va_range->list);
645 
646 	list_for_each_entry(va_block, &va_range->list, node) {
647 		/* Calc the first possible aligned addr */
648 		valid_start = va_block->start;
649 
650 		if (is_align_pow_2 && (valid_start & (va_block_align - 1))) {
651 			valid_start &= align_mask;
652 			valid_start += va_block_align;
653 			if (valid_start > va_block->end)
654 				continue;
655 		}
656 
657 		valid_size = va_block->end - valid_start + 1;
658 		if (valid_size < size)
659 			continue;
660 
661 		/*
662 		 * In case hint address is 0, and hints_range_reservation
663 		 * property enabled, then avoid allocating va blocks from the
664 		 * range reserved for hint addresses
665 		 */
666 		if (prop->hints_range_reservation && !hint_addr)
667 			if (is_hint_crossing_range(range_type, valid_start,
668 					size, prop))
669 				continue;
670 
671 		/* Pick the minimal length block which has the required size */
672 		if (!new_va_block || (valid_size < reserved_valid_size)) {
673 			new_va_block = va_block;
674 			reserved_valid_start = valid_start;
675 			reserved_valid_size = valid_size;
676 		}
677 
678 		if (hint_addr && hint_addr >= valid_start &&
679 					(hint_addr + size) <= va_block->end) {
680 			new_va_block = va_block;
681 			reserved_valid_start = hint_addr;
682 			reserved_valid_size = valid_size;
683 			break;
684 		}
685 	}
686 
687 	if (!new_va_block) {
688 		dev_err(hdev->dev, "no available va block for size %llu\n",
689 								size);
690 		goto out;
691 	}
692 
693 	if (force_hint && reserved_valid_start != hint_addr) {
694 		/* Hint address must be respected. If we are here - this means
695 		 * we could not respect it.
696 		 */
697 		dev_err(hdev->dev,
698 			"Hint address 0x%llx could not be respected\n",
699 			hint_addr);
700 		reserved_valid_start = 0;
701 		goto out;
702 	}
703 
704 	/*
705 	 * Check if there is some leftover range due to reserving the new
706 	 * va block, then return it to the main virtual addresses list.
707 	 */
708 	if (reserved_valid_start > new_va_block->start) {
709 		prev_start = new_va_block->start;
710 		prev_end = reserved_valid_start - 1;
711 
712 		new_va_block->start = reserved_valid_start;
713 		new_va_block->size = reserved_valid_size;
714 
715 		add_prev = true;
716 	}
717 
718 	if (new_va_block->size > size) {
719 		new_va_block->start += size;
720 		new_va_block->size = new_va_block->end - new_va_block->start + 1;
721 	} else {
722 		list_del(&new_va_block->node);
723 		kfree(new_va_block);
724 	}
725 
726 	if (add_prev) {
727 		rc = add_va_block_locked(hdev, &va_range->list, prev_start, prev_end);
728 		if (rc) {
729 			reserved_valid_start = 0;
730 			goto out;
731 		}
732 	}
733 
734 	print_va_list_locked(hdev, &va_range->list);
735 out:
736 	mutex_unlock(&va_range->lock);
737 
738 	return reserved_valid_start;
739 }
740 
741 /*
742  * hl_reserve_va_block() - reserve a virtual block of a given size.
743  * @hdev: pointer to the habanalabs device structure.
744  * @ctx: current context
745  * @type: virtual addresses range type.
746  * @size: requested block size.
747  * @alignment: required alignment in bytes of the virtual block start address,
748  *             0 means no alignment.
749  *
750  * This function does the following:
751  * - Iterate on the virtual block list to find a suitable virtual block for the
752  *   given size and alignment.
753  * - Reserve the requested block and update the list.
754  * - Return the start address of the virtual block.
755  */
756 u64 hl_reserve_va_block(struct hl_device *hdev, struct hl_ctx *ctx,
757 		enum hl_va_range_type type, u64 size, u32 alignment)
758 {
759 	return get_va_block(hdev, ctx->va_range[type], size, 0,
760 			max(alignment, ctx->va_range[type]->page_size),
761 			type, 0);
762 }
763 
764 /**
765  * hl_get_va_range_type() - get va_range type for the given address and size.
766  * @ctx: context to fetch va_range from.
767  * @address: the start address of the area we want to validate.
768  * @size: the size in bytes of the area we want to validate.
769  * @type: returned va_range type.
770  *
771  * Return: true if the area is inside a valid range, false otherwise.
772  */
773 static int hl_get_va_range_type(struct hl_ctx *ctx, u64 address, u64 size,
774 			enum hl_va_range_type *type)
775 {
776 	int i;
777 
778 	for (i = 0 ; i < HL_VA_RANGE_TYPE_MAX; i++) {
779 		if (hl_mem_area_inside_range(address, size,
780 				ctx->va_range[i]->start_addr,
781 				ctx->va_range[i]->end_addr)) {
782 			*type = i;
783 			return 0;
784 		}
785 	}
786 
787 	return -EINVAL;
788 }
789 
790 /**
791  * hl_unreserve_va_block() - wrapper for add_va_block to unreserve a va block.
792  * @hdev: pointer to the habanalabs device structure
793  * @ctx: pointer to the context structure.
794  * @start_addr: start virtual address.
795  * @size: number of bytes to unreserve.
796  *
797  * This function does the following:
798  * - Takes the list lock and calls add_va_block_locked.
799  */
800 int hl_unreserve_va_block(struct hl_device *hdev, struct hl_ctx *ctx,
801 		u64 start_addr, u64 size)
802 {
803 	enum hl_va_range_type type;
804 	int rc;
805 
806 	rc = hl_get_va_range_type(ctx, start_addr, size, &type);
807 	if (rc) {
808 		dev_err(hdev->dev,
809 			"cannot find va_range for va %#llx size %llu",
810 			start_addr, size);
811 		return rc;
812 	}
813 
814 	rc = add_va_block(hdev, ctx->va_range[type], start_addr,
815 						start_addr + size - 1);
816 	if (rc)
817 		dev_warn(hdev->dev,
818 			"add va block failed for vaddr: 0x%llx\n", start_addr);
819 
820 	return rc;
821 }
822 
823 /**
824  * init_phys_pg_pack_from_userptr() - initialize physical page pack from host
825  *                                    memory
826  * @ctx: pointer to the context structure.
827  * @userptr: userptr to initialize from.
828  * @pphys_pg_pack: result pointer.
829  * @force_regular_page: tell the function to ignore huge page optimization,
830  *                      even if possible. Needed for cases where the device VA
831  *                      is allocated before we know the composition of the
832  *                      physical pages
833  *
834  * This function does the following:
835  * - Pin the physical pages related to the given virtual block.
836  * - Create a physical page pack from the physical pages related to the given
837  *   virtual block.
838  */
839 static int init_phys_pg_pack_from_userptr(struct hl_ctx *ctx,
840 				struct hl_userptr *userptr,
841 				struct hl_vm_phys_pg_pack **pphys_pg_pack,
842 				bool force_regular_page)
843 {
844 	u32 npages, page_size = PAGE_SIZE,
845 		huge_page_size = ctx->hdev->asic_prop.pmmu_huge.page_size;
846 	u32 pgs_in_huge_page = huge_page_size >> __ffs(page_size);
847 	struct hl_vm_phys_pg_pack *phys_pg_pack;
848 	bool first = true, is_huge_page_opt;
849 	u64 page_mask, total_npages;
850 	struct scatterlist *sg;
851 	dma_addr_t dma_addr;
852 	int rc, i, j;
853 
854 	phys_pg_pack = kzalloc(sizeof(*phys_pg_pack), GFP_KERNEL);
855 	if (!phys_pg_pack)
856 		return -ENOMEM;
857 
858 	phys_pg_pack->vm_type = userptr->vm_type;
859 	phys_pg_pack->created_from_userptr = true;
860 	phys_pg_pack->asid = ctx->asid;
861 	atomic_set(&phys_pg_pack->mapping_cnt, 1);
862 
863 	is_huge_page_opt = (force_regular_page ? false : true);
864 
865 	/* Only if all dma_addrs are aligned to 2MB and their
866 	 * sizes is at least 2MB, we can use huge page mapping.
867 	 * We limit the 2MB optimization to this condition,
868 	 * since later on we acquire the related VA range as one
869 	 * consecutive block.
870 	 */
871 	total_npages = 0;
872 	for_each_sgtable_dma_sg(userptr->sgt, sg, i) {
873 		npages = hl_get_sg_info(sg, &dma_addr);
874 
875 		total_npages += npages;
876 
877 		if ((npages % pgs_in_huge_page) ||
878 					(dma_addr & (huge_page_size - 1)))
879 			is_huge_page_opt = false;
880 	}
881 
882 	if (is_huge_page_opt) {
883 		page_size = huge_page_size;
884 		do_div(total_npages, pgs_in_huge_page);
885 	}
886 
887 	page_mask = ~(((u64) page_size) - 1);
888 
889 	phys_pg_pack->pages = kvmalloc_array(total_npages, sizeof(u64),
890 						GFP_KERNEL);
891 	if (ZERO_OR_NULL_PTR(phys_pg_pack->pages)) {
892 		rc = -ENOMEM;
893 		goto page_pack_arr_mem_err;
894 	}
895 
896 	phys_pg_pack->npages = total_npages;
897 	phys_pg_pack->page_size = page_size;
898 	phys_pg_pack->total_size = total_npages * page_size;
899 
900 	j = 0;
901 	for_each_sgtable_dma_sg(userptr->sgt, sg, i) {
902 		npages = hl_get_sg_info(sg, &dma_addr);
903 
904 		/* align down to physical page size and save the offset */
905 		if (first) {
906 			first = false;
907 			phys_pg_pack->offset = dma_addr & (page_size - 1);
908 			dma_addr &= page_mask;
909 		}
910 
911 		while (npages) {
912 			phys_pg_pack->pages[j++] = dma_addr;
913 			dma_addr += page_size;
914 
915 			if (is_huge_page_opt)
916 				npages -= pgs_in_huge_page;
917 			else
918 				npages--;
919 		}
920 	}
921 
922 	*pphys_pg_pack = phys_pg_pack;
923 
924 	return 0;
925 
926 page_pack_arr_mem_err:
927 	kfree(phys_pg_pack);
928 
929 	return rc;
930 }
931 
932 /**
933  * map_phys_pg_pack() - maps the physical page pack..
934  * @ctx: pointer to the context structure.
935  * @vaddr: start address of the virtual area to map from.
936  * @phys_pg_pack: the pack of physical pages to map to.
937  *
938  * This function does the following:
939  * - Maps each chunk of virtual memory to matching physical chunk.
940  * - Stores number of successful mappings in the given argument.
941  * - Returns 0 on success, error code otherwise.
942  */
943 static int map_phys_pg_pack(struct hl_ctx *ctx, u64 vaddr,
944 				struct hl_vm_phys_pg_pack *phys_pg_pack)
945 {
946 	struct hl_device *hdev = ctx->hdev;
947 	u64 next_vaddr = vaddr, paddr, mapped_pg_cnt = 0, i;
948 	u32 page_size = phys_pg_pack->page_size;
949 	int rc = 0;
950 	bool is_host_addr;
951 
952 	for (i = 0 ; i < phys_pg_pack->npages ; i++) {
953 		paddr = phys_pg_pack->pages[i];
954 
955 		rc = hl_mmu_map_page(ctx, next_vaddr, paddr, page_size,
956 				(i + 1) == phys_pg_pack->npages);
957 		if (rc) {
958 			dev_err(hdev->dev,
959 				"map failed for handle %u, npages: %llu, mapped: %llu",
960 				phys_pg_pack->handle, phys_pg_pack->npages,
961 				mapped_pg_cnt);
962 			goto err;
963 		}
964 
965 		mapped_pg_cnt++;
966 		next_vaddr += page_size;
967 	}
968 
969 	return 0;
970 
971 err:
972 	is_host_addr = !hl_is_dram_va(hdev, vaddr);
973 
974 	next_vaddr = vaddr;
975 	for (i = 0 ; i < mapped_pg_cnt ; i++) {
976 		if (hl_mmu_unmap_page(ctx, next_vaddr, page_size,
977 					(i + 1) == mapped_pg_cnt))
978 			dev_warn_ratelimited(hdev->dev,
979 				"failed to unmap handle %u, va: 0x%llx, pa: 0x%llx, page size: %u\n",
980 					phys_pg_pack->handle, next_vaddr,
981 					phys_pg_pack->pages[i], page_size);
982 
983 		next_vaddr += page_size;
984 
985 		/*
986 		 * unmapping on Palladium can be really long, so avoid a CPU
987 		 * soft lockup bug by sleeping a little between unmapping pages
988 		 *
989 		 * In addition, on host num of pages could be huge,
990 		 * because page size could be 4KB, so when unmapping host
991 		 * pages sleep every 32K pages to avoid soft lockup
992 		 */
993 		if (hdev->pldm || (is_host_addr && (i & 0x7FFF) == 0))
994 			usleep_range(50, 200);
995 	}
996 
997 	return rc;
998 }
999 
1000 /**
1001  * unmap_phys_pg_pack() - unmaps the physical page pack.
1002  * @ctx: pointer to the context structure.
1003  * @vaddr: start address of the virtual area to unmap.
1004  * @phys_pg_pack: the pack of physical pages to unmap.
1005  */
1006 static void unmap_phys_pg_pack(struct hl_ctx *ctx, u64 vaddr,
1007 				struct hl_vm_phys_pg_pack *phys_pg_pack)
1008 {
1009 	struct hl_device *hdev = ctx->hdev;
1010 	u64 next_vaddr, i;
1011 	bool is_host_addr;
1012 	u32 page_size;
1013 
1014 	is_host_addr = !hl_is_dram_va(hdev, vaddr);
1015 	page_size = phys_pg_pack->page_size;
1016 	next_vaddr = vaddr;
1017 
1018 	for (i = 0 ; i < phys_pg_pack->npages ; i++, next_vaddr += page_size) {
1019 		if (hl_mmu_unmap_page(ctx, next_vaddr, page_size,
1020 				       (i + 1) == phys_pg_pack->npages))
1021 			dev_warn_ratelimited(hdev->dev,
1022 			"unmap failed for vaddr: 0x%llx\n", next_vaddr);
1023 
1024 		/*
1025 		 * unmapping on Palladium can be really long, so avoid a CPU
1026 		 * soft lockup bug by sleeping a little between unmapping pages
1027 		 *
1028 		 * In addition, on host num of pages could be huge,
1029 		 * because page size could be 4KB, so when unmapping host
1030 		 * pages sleep every 32K pages to avoid soft lockup
1031 		 */
1032 		if (hdev->pldm || (is_host_addr && (i & 0x7FFF) == 0))
1033 			usleep_range(50, 200);
1034 	}
1035 }
1036 
1037 /**
1038  * map_device_va() - map the given memory.
1039  * @ctx: pointer to the context structure.
1040  * @args: host parameters with handle/host virtual address.
1041  * @device_addr: pointer to result device virtual address.
1042  *
1043  * This function does the following:
1044  * - If given a physical device memory handle, map to a device virtual block
1045  *   and return the start address of this block.
1046  * - If given a host virtual address and size, find the related physical pages,
1047  *   map a device virtual block to this pages and return the start address of
1048  *   this block.
1049  */
1050 static int map_device_va(struct hl_ctx *ctx, struct hl_mem_in *args, u64 *device_addr)
1051 {
1052 	struct hl_vm_phys_pg_pack *phys_pg_pack;
1053 	enum hl_va_range_type va_range_type = 0;
1054 	struct hl_device *hdev = ctx->hdev;
1055 	struct hl_userptr *userptr = NULL;
1056 	u32 handle = 0, va_block_align;
1057 	struct hl_vm_hash_node *hnode;
1058 	struct hl_vm *vm = &hdev->vm;
1059 	struct hl_va_range *va_range;
1060 	bool is_userptr, do_prefetch;
1061 	u64 ret_vaddr, hint_addr;
1062 	enum vm_type *vm_type;
1063 	int rc;
1064 
1065 	/* set map flags */
1066 	is_userptr = args->flags & HL_MEM_USERPTR;
1067 	do_prefetch = hdev->supports_mmu_prefetch && (args->flags & HL_MEM_PREFETCH);
1068 
1069 	/* Assume failure */
1070 	*device_addr = 0;
1071 
1072 	if (is_userptr) {
1073 		u64 addr = args->map_host.host_virt_addr,
1074 			size = args->map_host.mem_size;
1075 		u32 page_size = hdev->asic_prop.pmmu.page_size,
1076 			huge_page_size = hdev->asic_prop.pmmu_huge.page_size;
1077 
1078 		rc = dma_map_host_va(hdev, addr, size, &userptr);
1079 		if (rc)
1080 			return rc;
1081 
1082 		rc = init_phys_pg_pack_from_userptr(ctx, userptr,
1083 				&phys_pg_pack, false);
1084 		if (rc) {
1085 			dev_err(hdev->dev,
1086 				"unable to init page pack for vaddr 0x%llx\n",
1087 				addr);
1088 			goto init_page_pack_err;
1089 		}
1090 
1091 		vm_type = (enum vm_type *) userptr;
1092 		hint_addr = args->map_host.hint_addr;
1093 		handle = phys_pg_pack->handle;
1094 
1095 		/* get required alignment */
1096 		if (phys_pg_pack->page_size == page_size) {
1097 			va_range = ctx->va_range[HL_VA_RANGE_TYPE_HOST];
1098 			va_range_type = HL_VA_RANGE_TYPE_HOST;
1099 			/*
1100 			 * huge page alignment may be needed in case of regular
1101 			 * page mapping, depending on the host VA alignment
1102 			 */
1103 			if (addr & (huge_page_size - 1))
1104 				va_block_align = page_size;
1105 			else
1106 				va_block_align = huge_page_size;
1107 		} else {
1108 			/*
1109 			 * huge page alignment is needed in case of huge page
1110 			 * mapping
1111 			 */
1112 			va_range = ctx->va_range[HL_VA_RANGE_TYPE_HOST_HUGE];
1113 			va_range_type = HL_VA_RANGE_TYPE_HOST_HUGE;
1114 			va_block_align = huge_page_size;
1115 		}
1116 	} else {
1117 		handle = lower_32_bits(args->map_device.handle);
1118 
1119 		spin_lock(&vm->idr_lock);
1120 		phys_pg_pack = idr_find(&vm->phys_pg_pack_handles, handle);
1121 		if (!phys_pg_pack) {
1122 			spin_unlock(&vm->idr_lock);
1123 			dev_err(hdev->dev,
1124 				"no match for handle %u\n", handle);
1125 			return -EINVAL;
1126 		}
1127 
1128 		/* increment now to avoid freeing device memory while mapping */
1129 		atomic_inc(&phys_pg_pack->mapping_cnt);
1130 
1131 		spin_unlock(&vm->idr_lock);
1132 
1133 		vm_type = (enum vm_type *) phys_pg_pack;
1134 
1135 		hint_addr = args->map_device.hint_addr;
1136 
1137 		/* DRAM VA alignment is the same as the MMU page size */
1138 		va_range = ctx->va_range[HL_VA_RANGE_TYPE_DRAM];
1139 		va_range_type = HL_VA_RANGE_TYPE_DRAM;
1140 		va_block_align = hdev->asic_prop.dmmu.page_size;
1141 	}
1142 
1143 	/*
1144 	 * relevant for mapping device physical memory only, as host memory is
1145 	 * implicitly shared
1146 	 */
1147 	if (!is_userptr && !(phys_pg_pack->flags & HL_MEM_SHARED) &&
1148 			phys_pg_pack->asid != ctx->asid) {
1149 		dev_err(hdev->dev,
1150 			"Failed to map memory, handle %u is not shared\n",
1151 			handle);
1152 		rc = -EPERM;
1153 		goto shared_err;
1154 	}
1155 
1156 	hnode = kzalloc(sizeof(*hnode), GFP_KERNEL);
1157 	if (!hnode) {
1158 		rc = -ENOMEM;
1159 		goto hnode_err;
1160 	}
1161 
1162 	if (hint_addr && phys_pg_pack->offset) {
1163 		if (args->flags & HL_MEM_FORCE_HINT) {
1164 			/* Fail if hint must be respected but it can't be */
1165 			dev_err(hdev->dev,
1166 				"Hint address 0x%llx cannot be respected because source memory is not aligned 0x%x\n",
1167 				hint_addr, phys_pg_pack->offset);
1168 			rc = -EINVAL;
1169 			goto va_block_err;
1170 		}
1171 		dev_dbg(hdev->dev,
1172 			"Hint address 0x%llx will be ignored because source memory is not aligned 0x%x\n",
1173 			hint_addr, phys_pg_pack->offset);
1174 	}
1175 
1176 	ret_vaddr = get_va_block(hdev, va_range, phys_pg_pack->total_size,
1177 					hint_addr, va_block_align,
1178 					va_range_type, args->flags);
1179 	if (!ret_vaddr) {
1180 		dev_err(hdev->dev, "no available va block for handle %u\n",
1181 				handle);
1182 		rc = -ENOMEM;
1183 		goto va_block_err;
1184 	}
1185 
1186 	mutex_lock(&hdev->mmu_lock);
1187 
1188 	rc = map_phys_pg_pack(ctx, ret_vaddr, phys_pg_pack);
1189 	if (rc) {
1190 		dev_err(hdev->dev, "mapping page pack failed for handle %u\n", handle);
1191 		mutex_unlock(&hdev->mmu_lock);
1192 		goto map_err;
1193 	}
1194 
1195 	rc = hl_mmu_invalidate_cache_range(hdev, false, *vm_type | MMU_OP_SKIP_LOW_CACHE_INV,
1196 				ctx->asid, ret_vaddr, phys_pg_pack->total_size);
1197 	mutex_unlock(&hdev->mmu_lock);
1198 	if (rc)
1199 		goto map_err;
1200 
1201 	/*
1202 	 * prefetch is done upon user's request. it is performed in WQ as and so can
1203 	 * be outside the MMU lock. the operation itself is already protected by the mmu lock
1204 	 */
1205 	if (do_prefetch) {
1206 		rc = hl_mmu_prefetch_cache_range(ctx, *vm_type, ctx->asid, ret_vaddr,
1207 							phys_pg_pack->total_size);
1208 		if (rc)
1209 			goto map_err;
1210 	}
1211 
1212 	ret_vaddr += phys_pg_pack->offset;
1213 
1214 	hnode->ptr = vm_type;
1215 	hnode->vaddr = ret_vaddr;
1216 	hnode->handle = is_userptr ? MEM_HANDLE_INVALID : handle;
1217 
1218 	mutex_lock(&ctx->mem_hash_lock);
1219 	hash_add(ctx->mem_hash, &hnode->node, ret_vaddr);
1220 	mutex_unlock(&ctx->mem_hash_lock);
1221 
1222 	*device_addr = ret_vaddr;
1223 
1224 	if (is_userptr)
1225 		free_phys_pg_pack(hdev, phys_pg_pack);
1226 
1227 	return rc;
1228 
1229 map_err:
1230 	if (add_va_block(hdev, va_range, ret_vaddr,
1231 				ret_vaddr + phys_pg_pack->total_size - 1))
1232 		dev_warn(hdev->dev,
1233 			"release va block failed for handle 0x%x, vaddr: 0x%llx\n",
1234 				handle, ret_vaddr);
1235 
1236 va_block_err:
1237 	kfree(hnode);
1238 hnode_err:
1239 shared_err:
1240 	atomic_dec(&phys_pg_pack->mapping_cnt);
1241 	if (is_userptr)
1242 		free_phys_pg_pack(hdev, phys_pg_pack);
1243 init_page_pack_err:
1244 	if (is_userptr)
1245 		dma_unmap_host_va(hdev, userptr);
1246 
1247 	return rc;
1248 }
1249 
1250 /* Should be called while the context's mem_hash_lock is taken */
1251 static struct hl_vm_hash_node *get_vm_hash_node_locked(struct hl_ctx *ctx, u64 vaddr)
1252 {
1253 	struct hl_vm_hash_node *hnode;
1254 
1255 	hash_for_each_possible(ctx->mem_hash, hnode, node, vaddr)
1256 		if (vaddr == hnode->vaddr)
1257 			return hnode;
1258 
1259 	return NULL;
1260 }
1261 
1262 /**
1263  * unmap_device_va() - unmap the given device virtual address.
1264  * @ctx: pointer to the context structure.
1265  * @args: host parameters with device virtual address to unmap.
1266  * @ctx_free: true if in context free flow, false otherwise.
1267  *
1268  * This function does the following:
1269  * - unmap the physical pages related to the given virtual address.
1270  * - return the device virtual block to the virtual block list.
1271  */
1272 static int unmap_device_va(struct hl_ctx *ctx, struct hl_mem_in *args,
1273 				bool ctx_free)
1274 {
1275 	struct hl_vm_phys_pg_pack *phys_pg_pack = NULL;
1276 	u64 vaddr = args->unmap.device_virt_addr;
1277 	struct asic_fixed_properties *prop;
1278 	struct hl_device *hdev = ctx->hdev;
1279 	struct hl_userptr *userptr = NULL;
1280 	struct hl_vm_hash_node *hnode;
1281 	struct hl_va_range *va_range;
1282 	enum vm_type *vm_type;
1283 	bool is_userptr;
1284 	int rc = 0;
1285 
1286 	prop = &hdev->asic_prop;
1287 
1288 	/* protect from double entrance */
1289 	mutex_lock(&ctx->mem_hash_lock);
1290 	hnode = get_vm_hash_node_locked(ctx, vaddr);
1291 	if (!hnode) {
1292 		mutex_unlock(&ctx->mem_hash_lock);
1293 		dev_err(hdev->dev, "unmap failed, no mem hnode for vaddr 0x%llx\n", vaddr);
1294 		return -EINVAL;
1295 	}
1296 
1297 	if (hnode->export_cnt) {
1298 		mutex_unlock(&ctx->mem_hash_lock);
1299 		dev_err(hdev->dev, "failed to unmap %#llx, memory is exported\n", vaddr);
1300 		return -EINVAL;
1301 	}
1302 
1303 	hash_del(&hnode->node);
1304 	mutex_unlock(&ctx->mem_hash_lock);
1305 
1306 	vm_type = hnode->ptr;
1307 
1308 	if (*vm_type == VM_TYPE_USERPTR) {
1309 		is_userptr = true;
1310 		userptr = hnode->ptr;
1311 
1312 		rc = init_phys_pg_pack_from_userptr(ctx, userptr, &phys_pg_pack,
1313 							false);
1314 		if (rc) {
1315 			dev_err(hdev->dev,
1316 				"unable to init page pack for vaddr 0x%llx\n",
1317 				vaddr);
1318 			goto vm_type_err;
1319 		}
1320 
1321 		if (phys_pg_pack->page_size ==
1322 					hdev->asic_prop.pmmu.page_size)
1323 			va_range = ctx->va_range[HL_VA_RANGE_TYPE_HOST];
1324 		else
1325 			va_range = ctx->va_range[HL_VA_RANGE_TYPE_HOST_HUGE];
1326 	} else if (*vm_type == VM_TYPE_PHYS_PACK) {
1327 		is_userptr = false;
1328 		va_range = ctx->va_range[HL_VA_RANGE_TYPE_DRAM];
1329 		phys_pg_pack = hnode->ptr;
1330 	} else {
1331 		dev_warn(hdev->dev,
1332 			"unmap failed, unknown vm desc for vaddr 0x%llx\n",
1333 				vaddr);
1334 		rc = -EFAULT;
1335 		goto vm_type_err;
1336 	}
1337 
1338 	if (atomic_read(&phys_pg_pack->mapping_cnt) == 0) {
1339 		dev_err(hdev->dev, "vaddr 0x%llx is not mapped\n", vaddr);
1340 		rc = -EINVAL;
1341 		goto mapping_cnt_err;
1342 	}
1343 
1344 	if (!is_userptr && !is_power_of_2(phys_pg_pack->page_size))
1345 		vaddr = prop->dram_base_address +
1346 			DIV_ROUND_DOWN_ULL(vaddr - prop->dram_base_address,
1347 						phys_pg_pack->page_size) *
1348 							phys_pg_pack->page_size;
1349 	else
1350 		vaddr &= ~(((u64) phys_pg_pack->page_size) - 1);
1351 
1352 	mutex_lock(&hdev->mmu_lock);
1353 
1354 	unmap_phys_pg_pack(ctx, vaddr, phys_pg_pack);
1355 
1356 	/*
1357 	 * During context free this function is called in a loop to clean all
1358 	 * the context mappings. Hence the cache invalidation can be called once
1359 	 * at the loop end rather than for each iteration
1360 	 */
1361 	if (!ctx_free)
1362 		rc = hl_mmu_invalidate_cache_range(hdev, true, *vm_type, ctx->asid, vaddr,
1363 							phys_pg_pack->total_size);
1364 
1365 	mutex_unlock(&hdev->mmu_lock);
1366 
1367 	/*
1368 	 * If the context is closing we don't need to check for the MMU cache
1369 	 * invalidation return code and update the VA free list as in this flow
1370 	 * we invalidate the MMU cache outside of this unmap function and the VA
1371 	 * free list will be freed anyway.
1372 	 */
1373 	if (!ctx_free) {
1374 		int tmp_rc;
1375 
1376 		tmp_rc = add_va_block(hdev, va_range, vaddr,
1377 					vaddr + phys_pg_pack->total_size - 1);
1378 		if (tmp_rc) {
1379 			dev_warn(hdev->dev,
1380 					"add va block failed for vaddr: 0x%llx\n",
1381 					vaddr);
1382 			if (!rc)
1383 				rc = tmp_rc;
1384 		}
1385 	}
1386 
1387 	atomic_dec(&phys_pg_pack->mapping_cnt);
1388 	kfree(hnode);
1389 
1390 	if (is_userptr) {
1391 		free_phys_pg_pack(hdev, phys_pg_pack);
1392 		dma_unmap_host_va(hdev, userptr);
1393 	}
1394 
1395 	return rc;
1396 
1397 mapping_cnt_err:
1398 	if (is_userptr)
1399 		free_phys_pg_pack(hdev, phys_pg_pack);
1400 vm_type_err:
1401 	mutex_lock(&ctx->mem_hash_lock);
1402 	hash_add(ctx->mem_hash, &hnode->node, vaddr);
1403 	mutex_unlock(&ctx->mem_hash_lock);
1404 
1405 	return rc;
1406 }
1407 
1408 static int map_block(struct hl_device *hdev, u64 address, u64 *handle, u32 *size)
1409 {
1410 	u32 block_id;
1411 	int rc;
1412 
1413 	*handle = 0;
1414 	if (size)
1415 		*size = 0;
1416 
1417 	rc = hdev->asic_funcs->get_hw_block_id(hdev, address, size, &block_id);
1418 	if (rc)
1419 		return rc;
1420 
1421 	*handle = block_id | HL_MMAP_TYPE_BLOCK;
1422 	*handle <<= PAGE_SHIFT;
1423 
1424 	return 0;
1425 }
1426 
1427 static void hw_block_vm_close(struct vm_area_struct *vma)
1428 {
1429 	struct hl_vm_hw_block_list_node *lnode =
1430 		(struct hl_vm_hw_block_list_node *) vma->vm_private_data;
1431 	struct hl_ctx *ctx = lnode->ctx;
1432 	long new_mmap_size;
1433 
1434 	new_mmap_size = lnode->mapped_size - (vma->vm_end - vma->vm_start);
1435 	if (new_mmap_size > 0) {
1436 		lnode->mapped_size = new_mmap_size;
1437 		return;
1438 	}
1439 
1440 	mutex_lock(&ctx->hw_block_list_lock);
1441 	list_del(&lnode->node);
1442 	mutex_unlock(&ctx->hw_block_list_lock);
1443 	hl_ctx_put(ctx);
1444 	kfree(lnode);
1445 	vma->vm_private_data = NULL;
1446 }
1447 
1448 static const struct vm_operations_struct hw_block_vm_ops = {
1449 	.close = hw_block_vm_close
1450 };
1451 
1452 /**
1453  * hl_hw_block_mmap() - mmap a hw block to user.
1454  * @hpriv: pointer to the private data of the fd
1455  * @vma: pointer to vm_area_struct of the process
1456  *
1457  * Driver increments context reference for every HW block mapped in order
1458  * to prevent user from closing FD without unmapping first
1459  */
1460 int hl_hw_block_mmap(struct hl_fpriv *hpriv, struct vm_area_struct *vma)
1461 {
1462 	struct hl_vm_hw_block_list_node *lnode;
1463 	struct hl_device *hdev = hpriv->hdev;
1464 	struct hl_ctx *ctx = hpriv->ctx;
1465 	u32 block_id, block_size;
1466 	int rc;
1467 
1468 	/* We use the page offset to hold the block id and thus we need to clear
1469 	 * it before doing the mmap itself
1470 	 */
1471 	block_id = vma->vm_pgoff;
1472 	vma->vm_pgoff = 0;
1473 
1474 	/* Driver only allows mapping of a complete HW block */
1475 	block_size = vma->vm_end - vma->vm_start;
1476 
1477 	if (!access_ok((void __user *) (uintptr_t) vma->vm_start, block_size)) {
1478 		dev_err(hdev->dev,
1479 			"user pointer is invalid - 0x%lx\n",
1480 			vma->vm_start);
1481 
1482 		return -EINVAL;
1483 	}
1484 
1485 	lnode = kzalloc(sizeof(*lnode), GFP_KERNEL);
1486 	if (!lnode)
1487 		return -ENOMEM;
1488 
1489 	rc = hdev->asic_funcs->hw_block_mmap(hdev, vma, block_id, block_size);
1490 	if (rc) {
1491 		kfree(lnode);
1492 		return rc;
1493 	}
1494 
1495 	hl_ctx_get(ctx);
1496 
1497 	lnode->ctx = ctx;
1498 	lnode->vaddr = vma->vm_start;
1499 	lnode->block_size = block_size;
1500 	lnode->mapped_size = lnode->block_size;
1501 	lnode->id = block_id;
1502 
1503 	vma->vm_private_data = lnode;
1504 	vma->vm_ops = &hw_block_vm_ops;
1505 
1506 	mutex_lock(&ctx->hw_block_list_lock);
1507 	list_add_tail(&lnode->node, &ctx->hw_block_mem_list);
1508 	mutex_unlock(&ctx->hw_block_list_lock);
1509 
1510 	vma->vm_pgoff = block_id;
1511 
1512 	return 0;
1513 }
1514 
1515 static int set_dma_sg(struct scatterlist *sg, u64 bar_address, u64 chunk_size,
1516 			struct device *dev, enum dma_data_direction dir)
1517 {
1518 	dma_addr_t addr;
1519 	int rc;
1520 
1521 	addr = dma_map_resource(dev, bar_address, chunk_size, dir,
1522 				DMA_ATTR_SKIP_CPU_SYNC);
1523 	rc = dma_mapping_error(dev, addr);
1524 	if (rc)
1525 		return rc;
1526 
1527 	sg_set_page(sg, NULL, chunk_size, 0);
1528 	sg_dma_address(sg) = addr;
1529 	sg_dma_len(sg) = chunk_size;
1530 
1531 	return 0;
1532 }
1533 
1534 static struct sg_table *alloc_sgt_from_device_pages(struct hl_device *hdev, u64 *pages, u64 npages,
1535 						u64 page_size, u64 exported_size,
1536 						struct device *dev, enum dma_data_direction dir)
1537 {
1538 	u64 chunk_size, bar_address, dma_max_seg_size, cur_size_to_export, cur_npages;
1539 	struct asic_fixed_properties *prop;
1540 	int rc, i, j, nents, cur_page;
1541 	struct scatterlist *sg;
1542 	struct sg_table *sgt;
1543 
1544 	prop = &hdev->asic_prop;
1545 
1546 	dma_max_seg_size = dma_get_max_seg_size(dev);
1547 
1548 	/* We would like to align the max segment size to PAGE_SIZE, so the
1549 	 * SGL will contain aligned addresses that can be easily mapped to
1550 	 * an MMU
1551 	 */
1552 	dma_max_seg_size = ALIGN_DOWN(dma_max_seg_size, PAGE_SIZE);
1553 	if (dma_max_seg_size < PAGE_SIZE) {
1554 		dev_err_ratelimited(hdev->dev,
1555 				"dma_max_seg_size %llu can't be smaller than PAGE_SIZE\n",
1556 				dma_max_seg_size);
1557 		return ERR_PTR(-EINVAL);
1558 	}
1559 
1560 	sgt = kzalloc(sizeof(*sgt), GFP_KERNEL);
1561 	if (!sgt)
1562 		return ERR_PTR(-ENOMEM);
1563 
1564 	/* remove export size restrictions in case not explicitly defined */
1565 	cur_size_to_export = exported_size ? exported_size : (npages * page_size);
1566 
1567 	/* If the size of each page is larger than the dma max segment size,
1568 	 * then we can't combine pages and the number of entries in the SGL
1569 	 * will just be the
1570 	 * <number of pages> * <chunks of max segment size in each page>
1571 	 */
1572 	if (page_size > dma_max_seg_size) {
1573 		/* we should limit number of pages according to the exported size */
1574 		cur_npages = DIV_ROUND_UP_SECTOR_T(cur_size_to_export, page_size);
1575 		nents = cur_npages * DIV_ROUND_UP_SECTOR_T(page_size, dma_max_seg_size);
1576 	} else {
1577 		cur_npages = npages;
1578 
1579 		/* Get number of non-contiguous chunks */
1580 		for (i = 1, nents = 1, chunk_size = page_size ; i < cur_npages ; i++) {
1581 			if (pages[i - 1] + page_size != pages[i] ||
1582 					chunk_size + page_size > dma_max_seg_size) {
1583 				nents++;
1584 				chunk_size = page_size;
1585 				continue;
1586 			}
1587 
1588 			chunk_size += page_size;
1589 		}
1590 	}
1591 
1592 	rc = sg_alloc_table(sgt, nents, GFP_KERNEL | __GFP_ZERO);
1593 	if (rc)
1594 		goto error_free;
1595 
1596 	cur_page = 0;
1597 
1598 	if (page_size > dma_max_seg_size) {
1599 		u64 size_left, cur_device_address = 0;
1600 
1601 		size_left = page_size;
1602 
1603 		/* Need to split each page into the number of chunks of
1604 		 * dma_max_seg_size
1605 		 */
1606 		for_each_sgtable_dma_sg(sgt, sg, i) {
1607 			if (size_left == page_size)
1608 				cur_device_address =
1609 					pages[cur_page] - prop->dram_base_address;
1610 			else
1611 				cur_device_address += dma_max_seg_size;
1612 
1613 			/* make sure not to export over exported size */
1614 			chunk_size = min3(size_left, dma_max_seg_size, cur_size_to_export);
1615 
1616 			bar_address = hdev->dram_pci_bar_start + cur_device_address;
1617 
1618 			rc = set_dma_sg(sg, bar_address, chunk_size, dev, dir);
1619 			if (rc)
1620 				goto error_unmap;
1621 
1622 			cur_size_to_export -= chunk_size;
1623 
1624 			if (size_left > dma_max_seg_size) {
1625 				size_left -= dma_max_seg_size;
1626 			} else {
1627 				cur_page++;
1628 				size_left = page_size;
1629 			}
1630 		}
1631 	} else {
1632 		/* Merge pages and put them into the scatterlist */
1633 		for_each_sgtable_dma_sg(sgt, sg, i) {
1634 			chunk_size = page_size;
1635 			for (j = cur_page + 1 ; j < cur_npages ; j++) {
1636 				if (pages[j - 1] + page_size != pages[j] ||
1637 						chunk_size + page_size > dma_max_seg_size)
1638 					break;
1639 
1640 				chunk_size += page_size;
1641 			}
1642 
1643 			bar_address = hdev->dram_pci_bar_start +
1644 					(pages[cur_page] - prop->dram_base_address);
1645 
1646 			/* make sure not to export over exported size */
1647 			chunk_size = min(chunk_size, cur_size_to_export);
1648 			rc = set_dma_sg(sg, bar_address, chunk_size, dev, dir);
1649 			if (rc)
1650 				goto error_unmap;
1651 
1652 			cur_size_to_export -= chunk_size;
1653 			cur_page = j;
1654 		}
1655 	}
1656 
1657 	/* Because we are not going to include a CPU list we want to have some
1658 	 * chance that other users will detect this by setting the orig_nents
1659 	 * to 0 and using only nents (length of DMA list) when going over the
1660 	 * sgl
1661 	 */
1662 	sgt->orig_nents = 0;
1663 
1664 	return sgt;
1665 
1666 error_unmap:
1667 	for_each_sgtable_dma_sg(sgt, sg, i) {
1668 		if (!sg_dma_len(sg))
1669 			continue;
1670 
1671 		dma_unmap_resource(dev, sg_dma_address(sg),
1672 					sg_dma_len(sg), dir,
1673 					DMA_ATTR_SKIP_CPU_SYNC);
1674 	}
1675 
1676 	sg_free_table(sgt);
1677 
1678 error_free:
1679 	kfree(sgt);
1680 	return ERR_PTR(rc);
1681 }
1682 
1683 static int hl_dmabuf_attach(struct dma_buf *dmabuf,
1684 				struct dma_buf_attachment *attachment)
1685 {
1686 	struct hl_dmabuf_priv *hl_dmabuf;
1687 	struct hl_device *hdev;
1688 	int rc;
1689 
1690 	hl_dmabuf = dmabuf->priv;
1691 	hdev = hl_dmabuf->ctx->hdev;
1692 
1693 	rc = pci_p2pdma_distance(hdev->pdev, attachment->dev, true);
1694 
1695 	if (rc < 0)
1696 		attachment->peer2peer = false;
1697 	return 0;
1698 }
1699 
1700 static struct sg_table *hl_map_dmabuf(struct dma_buf_attachment *attachment,
1701 					enum dma_data_direction dir)
1702 {
1703 	struct dma_buf *dma_buf = attachment->dmabuf;
1704 	struct hl_vm_phys_pg_pack *phys_pg_pack;
1705 	struct hl_dmabuf_priv *hl_dmabuf;
1706 	struct hl_device *hdev;
1707 	struct sg_table *sgt;
1708 
1709 	hl_dmabuf = dma_buf->priv;
1710 	hdev = hl_dmabuf->ctx->hdev;
1711 	phys_pg_pack = hl_dmabuf->phys_pg_pack;
1712 
1713 	if (!attachment->peer2peer) {
1714 		dev_dbg(hdev->dev, "Failed to map dmabuf because p2p is disabled\n");
1715 		return ERR_PTR(-EPERM);
1716 	}
1717 
1718 	if (phys_pg_pack)
1719 		sgt = alloc_sgt_from_device_pages(hdev,
1720 						phys_pg_pack->pages,
1721 						phys_pg_pack->npages,
1722 						phys_pg_pack->page_size,
1723 						phys_pg_pack->exported_size,
1724 						attachment->dev,
1725 						dir);
1726 	else
1727 		sgt = alloc_sgt_from_device_pages(hdev,
1728 						&hl_dmabuf->device_address,
1729 						1,
1730 						hl_dmabuf->dmabuf->size,
1731 						0,
1732 						attachment->dev,
1733 						dir);
1734 
1735 	if (IS_ERR(sgt))
1736 		dev_err(hdev->dev, "failed (%ld) to initialize sgt for dmabuf\n", PTR_ERR(sgt));
1737 
1738 	return sgt;
1739 }
1740 
1741 static void hl_unmap_dmabuf(struct dma_buf_attachment *attachment,
1742 				  struct sg_table *sgt,
1743 				  enum dma_data_direction dir)
1744 {
1745 	struct scatterlist *sg;
1746 	int i;
1747 
1748 	/* The memory behind the dma-buf has *always* resided on the device itself, i.e. it lives
1749 	 * only in the 'device' domain (after all, it maps a PCI bar address which points to the
1750 	 * device memory).
1751 	 *
1752 	 * Therefore, it was never in the 'CPU' domain and hence, there is no need to perform
1753 	 * a sync of the memory to the CPU's cache, as it never resided inside that cache.
1754 	 */
1755 	for_each_sgtable_dma_sg(sgt, sg, i)
1756 		dma_unmap_resource(attachment->dev, sg_dma_address(sg),
1757 					sg_dma_len(sg), dir,
1758 					DMA_ATTR_SKIP_CPU_SYNC);
1759 
1760 	/* Need to restore orig_nents because sg_free_table use that field */
1761 	sgt->orig_nents = sgt->nents;
1762 	sg_free_table(sgt);
1763 	kfree(sgt);
1764 }
1765 
1766 static struct hl_vm_hash_node *memhash_node_export_get(struct hl_ctx *ctx, u64 addr)
1767 {
1768 	struct hl_device *hdev = ctx->hdev;
1769 	struct hl_vm_hash_node *hnode;
1770 
1771 	/* get the memory handle */
1772 	mutex_lock(&ctx->mem_hash_lock);
1773 	hnode = get_vm_hash_node_locked(ctx, addr);
1774 	if (!hnode) {
1775 		mutex_unlock(&ctx->mem_hash_lock);
1776 		dev_dbg(hdev->dev, "map address %#llx not found\n", addr);
1777 		return ERR_PTR(-EINVAL);
1778 	}
1779 
1780 	if (upper_32_bits(hnode->handle)) {
1781 		mutex_unlock(&ctx->mem_hash_lock);
1782 		dev_dbg(hdev->dev, "invalid handle %#llx for map address %#llx\n",
1783 				hnode->handle, addr);
1784 		return ERR_PTR(-EINVAL);
1785 	}
1786 
1787 	/*
1788 	 * node found, increase export count so this memory cannot be unmapped
1789 	 * and the hash node cannot be deleted.
1790 	 */
1791 	hnode->export_cnt++;
1792 	mutex_unlock(&ctx->mem_hash_lock);
1793 
1794 	return hnode;
1795 }
1796 
1797 static void memhash_node_export_put(struct hl_ctx *ctx, struct hl_vm_hash_node *hnode)
1798 {
1799 	mutex_lock(&ctx->mem_hash_lock);
1800 	hnode->export_cnt--;
1801 	mutex_unlock(&ctx->mem_hash_lock);
1802 }
1803 
1804 static void hl_release_dmabuf(struct dma_buf *dmabuf)
1805 {
1806 	struct hl_dmabuf_priv *hl_dmabuf = dmabuf->priv;
1807 	struct hl_ctx *ctx;
1808 
1809 	if (!hl_dmabuf)
1810 		return;
1811 
1812 	ctx = hl_dmabuf->ctx;
1813 
1814 	if (hl_dmabuf->memhash_hnode)
1815 		memhash_node_export_put(ctx, hl_dmabuf->memhash_hnode);
1816 
1817 	atomic_dec(&ctx->hdev->dmabuf_export_cnt);
1818 	hl_ctx_put(ctx);
1819 
1820 	/* Paired with get_file() in export_dmabuf() */
1821 	fput(ctx->hpriv->filp);
1822 
1823 	kfree(hl_dmabuf);
1824 }
1825 
1826 static const struct dma_buf_ops habanalabs_dmabuf_ops = {
1827 	.attach = hl_dmabuf_attach,
1828 	.map_dma_buf = hl_map_dmabuf,
1829 	.unmap_dma_buf = hl_unmap_dmabuf,
1830 	.release = hl_release_dmabuf,
1831 };
1832 
1833 static int export_dmabuf(struct hl_ctx *ctx,
1834 				struct hl_dmabuf_priv *hl_dmabuf,
1835 				u64 total_size, int flags, int *dmabuf_fd)
1836 {
1837 	DEFINE_DMA_BUF_EXPORT_INFO(exp_info);
1838 	struct hl_device *hdev = ctx->hdev;
1839 	int rc, fd;
1840 
1841 	exp_info.ops = &habanalabs_dmabuf_ops;
1842 	exp_info.size = total_size;
1843 	exp_info.flags = flags;
1844 	exp_info.priv = hl_dmabuf;
1845 
1846 	hl_dmabuf->dmabuf = dma_buf_export(&exp_info);
1847 	if (IS_ERR(hl_dmabuf->dmabuf)) {
1848 		dev_err(hdev->dev, "failed to export dma-buf\n");
1849 		return PTR_ERR(hl_dmabuf->dmabuf);
1850 	}
1851 
1852 	fd = dma_buf_fd(hl_dmabuf->dmabuf, flags);
1853 	if (fd < 0) {
1854 		dev_err(hdev->dev, "failed to get a file descriptor for a dma-buf, %d\n", fd);
1855 		rc = fd;
1856 		goto err_dma_buf_put;
1857 	}
1858 
1859 	hl_dmabuf->ctx = ctx;
1860 	hl_ctx_get(hl_dmabuf->ctx);
1861 	atomic_inc(&ctx->hdev->dmabuf_export_cnt);
1862 
1863 	/* Get compute device file to enforce release order, such that all exported dma-buf will be
1864 	 * released first and only then the compute device.
1865 	 * Paired with fput() in hl_release_dmabuf().
1866 	 */
1867 	get_file(ctx->hpriv->filp);
1868 
1869 	*dmabuf_fd = fd;
1870 
1871 	return 0;
1872 
1873 err_dma_buf_put:
1874 	hl_dmabuf->dmabuf->priv = NULL;
1875 	dma_buf_put(hl_dmabuf->dmabuf);
1876 	return rc;
1877 }
1878 
1879 static int validate_export_params_common(struct hl_device *hdev, u64 device_addr, u64 size)
1880 {
1881 	if (!IS_ALIGNED(device_addr, PAGE_SIZE)) {
1882 		dev_dbg(hdev->dev,
1883 			"exported device memory address 0x%llx should be aligned to 0x%lx\n",
1884 			device_addr, PAGE_SIZE);
1885 		return -EINVAL;
1886 	}
1887 
1888 	if (size < PAGE_SIZE) {
1889 		dev_dbg(hdev->dev,
1890 			"exported device memory size %llu should be equal to or greater than %lu\n",
1891 			size, PAGE_SIZE);
1892 		return -EINVAL;
1893 	}
1894 
1895 	return 0;
1896 }
1897 
1898 static int validate_export_params_no_mmu(struct hl_device *hdev, u64 device_addr, u64 size)
1899 {
1900 	struct asic_fixed_properties *prop = &hdev->asic_prop;
1901 	u64 bar_address;
1902 	int rc;
1903 
1904 	rc = validate_export_params_common(hdev, device_addr, size);
1905 	if (rc)
1906 		return rc;
1907 
1908 	if (device_addr < prop->dram_user_base_address ||
1909 				(device_addr + size) > prop->dram_end_address ||
1910 				(device_addr + size) < device_addr) {
1911 		dev_dbg(hdev->dev,
1912 			"DRAM memory range 0x%llx (+0x%llx) is outside of DRAM boundaries\n",
1913 			device_addr, size);
1914 		return -EINVAL;
1915 	}
1916 
1917 	bar_address = hdev->dram_pci_bar_start + (device_addr - prop->dram_base_address);
1918 
1919 	if ((bar_address + size) > (hdev->dram_pci_bar_start + prop->dram_pci_bar_size) ||
1920 			(bar_address + size) < bar_address) {
1921 		dev_dbg(hdev->dev,
1922 			"DRAM memory range 0x%llx (+0x%llx) is outside of PCI BAR boundaries\n",
1923 			device_addr, size);
1924 		return -EINVAL;
1925 	}
1926 
1927 	return 0;
1928 }
1929 
1930 static int validate_export_params(struct hl_device *hdev, u64 device_addr, u64 size, u64 offset,
1931 					struct hl_vm_phys_pg_pack *phys_pg_pack)
1932 {
1933 	struct asic_fixed_properties *prop = &hdev->asic_prop;
1934 	u64 bar_address;
1935 	int i, rc;
1936 
1937 	rc = validate_export_params_common(hdev, device_addr, size);
1938 	if (rc)
1939 		return rc;
1940 
1941 	if ((offset + size) > phys_pg_pack->total_size) {
1942 		dev_dbg(hdev->dev, "offset %#llx and size %#llx exceed total map size %#llx\n",
1943 				offset, size, phys_pg_pack->total_size);
1944 		return -EINVAL;
1945 	}
1946 
1947 	for (i = 0 ; i < phys_pg_pack->npages ; i++) {
1948 
1949 		bar_address = hdev->dram_pci_bar_start +
1950 					(phys_pg_pack->pages[i] - prop->dram_base_address);
1951 
1952 		if ((bar_address + phys_pg_pack->page_size) >
1953 				(hdev->dram_pci_bar_start + prop->dram_pci_bar_size) ||
1954 				(bar_address + phys_pg_pack->page_size) < bar_address) {
1955 			dev_dbg(hdev->dev,
1956 				"DRAM memory range 0x%llx (+0x%x) is outside of PCI BAR boundaries\n",
1957 					phys_pg_pack->pages[i],
1958 					phys_pg_pack->page_size);
1959 
1960 			return -EINVAL;
1961 		}
1962 	}
1963 
1964 	return 0;
1965 }
1966 
1967 static struct hl_vm_phys_pg_pack *get_phys_pg_pack_from_hash_node(struct hl_device *hdev,
1968 							struct hl_vm_hash_node *hnode)
1969 {
1970 	struct hl_vm_phys_pg_pack *phys_pg_pack;
1971 	struct hl_vm *vm = &hdev->vm;
1972 
1973 	spin_lock(&vm->idr_lock);
1974 	phys_pg_pack = idr_find(&vm->phys_pg_pack_handles, (u32) hnode->handle);
1975 	if (!phys_pg_pack) {
1976 		spin_unlock(&vm->idr_lock);
1977 		dev_dbg(hdev->dev, "no match for handle 0x%x\n", (u32) hnode->handle);
1978 		return ERR_PTR(-EINVAL);
1979 	}
1980 
1981 	spin_unlock(&vm->idr_lock);
1982 
1983 	if (phys_pg_pack->vm_type != VM_TYPE_PHYS_PACK) {
1984 		dev_dbg(hdev->dev, "handle 0x%llx does not represent DRAM memory\n", hnode->handle);
1985 		return ERR_PTR(-EINVAL);
1986 	}
1987 
1988 	return phys_pg_pack;
1989 }
1990 
1991 /**
1992  * export_dmabuf_from_addr() - export a dma-buf object for the given memory
1993  *                             address and size.
1994  * @ctx: pointer to the context structure.
1995  * @addr: device address.
1996  * @size: size of device memory to export.
1997  * @offset: the offset into the buffer from which to start exporting
1998  * @flags: DMA-BUF file/FD flags.
1999  * @dmabuf_fd: pointer to result FD that represents the dma-buf object.
2000  *
2001  * Create and export a dma-buf object for an existing memory allocation inside
2002  * the device memory, and return a FD which is associated with the dma-buf
2003  * object.
2004  *
2005  * Return: 0 on success, non-zero for failure.
2006  */
2007 static int export_dmabuf_from_addr(struct hl_ctx *ctx, u64 addr, u64 size, u64 offset,
2008 					int flags, int *dmabuf_fd)
2009 {
2010 	struct hl_vm_phys_pg_pack *phys_pg_pack = NULL;
2011 	struct hl_vm_hash_node *hnode = NULL;
2012 	struct asic_fixed_properties *prop;
2013 	struct hl_dmabuf_priv *hl_dmabuf;
2014 	struct hl_device *hdev;
2015 	u64 export_addr;
2016 	int rc;
2017 
2018 	hdev = ctx->hdev;
2019 	prop = &hdev->asic_prop;
2020 
2021 	/* offset must be 0 in devices without virtual memory support */
2022 	if (!prop->dram_supports_virtual_memory && offset) {
2023 		dev_dbg(hdev->dev, "offset is not allowed in device without virtual memory\n");
2024 		return -EINVAL;
2025 	}
2026 
2027 	export_addr = addr + offset;
2028 
2029 	hl_dmabuf = kzalloc(sizeof(*hl_dmabuf), GFP_KERNEL);
2030 	if (!hl_dmabuf)
2031 		return -ENOMEM;
2032 
2033 	if (prop->dram_supports_virtual_memory) {
2034 		hnode = memhash_node_export_get(ctx, addr);
2035 		if (IS_ERR(hnode)) {
2036 			rc = PTR_ERR(hnode);
2037 			goto err_free_dmabuf_wrapper;
2038 		}
2039 		phys_pg_pack = get_phys_pg_pack_from_hash_node(hdev, hnode);
2040 		if (IS_ERR(phys_pg_pack)) {
2041 			rc = PTR_ERR(phys_pg_pack);
2042 			goto dec_memhash_export_cnt;
2043 		}
2044 		rc = validate_export_params(hdev, export_addr, size, offset, phys_pg_pack);
2045 		if (rc)
2046 			goto dec_memhash_export_cnt;
2047 
2048 		phys_pg_pack->exported_size = size;
2049 		hl_dmabuf->phys_pg_pack = phys_pg_pack;
2050 		hl_dmabuf->memhash_hnode = hnode;
2051 	} else {
2052 		rc = validate_export_params_no_mmu(hdev, export_addr, size);
2053 		if (rc)
2054 			goto err_free_dmabuf_wrapper;
2055 	}
2056 
2057 	hl_dmabuf->device_address = export_addr;
2058 
2059 	rc = export_dmabuf(ctx, hl_dmabuf, size, flags, dmabuf_fd);
2060 	if (rc)
2061 		goto dec_memhash_export_cnt;
2062 
2063 	return 0;
2064 
2065 dec_memhash_export_cnt:
2066 	if (prop->dram_supports_virtual_memory)
2067 		memhash_node_export_put(ctx, hnode);
2068 err_free_dmabuf_wrapper:
2069 	kfree(hl_dmabuf);
2070 	return rc;
2071 }
2072 
2073 static void ts_buff_release(struct hl_mmap_mem_buf *buf)
2074 {
2075 	struct hl_ts_buff *ts_buff = buf->private;
2076 
2077 	vfree(ts_buff->kernel_buff_address);
2078 	vfree(ts_buff->user_buff_address);
2079 	kfree(ts_buff);
2080 }
2081 
2082 static int hl_ts_mmap(struct hl_mmap_mem_buf *buf, struct vm_area_struct *vma, void *args)
2083 {
2084 	struct hl_ts_buff *ts_buff = buf->private;
2085 
2086 	vm_flags_set(vma, VM_DONTEXPAND | VM_DONTDUMP | VM_DONTCOPY | VM_NORESERVE);
2087 	return remap_vmalloc_range(vma, ts_buff->user_buff_address, 0);
2088 }
2089 
2090 static int hl_ts_alloc_buf(struct hl_mmap_mem_buf *buf, gfp_t gfp, void *args)
2091 {
2092 	struct hl_ts_buff *ts_buff = NULL;
2093 	u32 num_elements;
2094 	size_t size;
2095 	void *p;
2096 
2097 	num_elements = *(u32 *)args;
2098 
2099 	ts_buff = kzalloc(sizeof(*ts_buff), gfp);
2100 	if (!ts_buff)
2101 		return -ENOMEM;
2102 
2103 	/* Allocate the user buffer */
2104 	size = num_elements * sizeof(u64);
2105 	p = vmalloc_user(size);
2106 	if (!p)
2107 		goto free_mem;
2108 
2109 	ts_buff->user_buff_address = p;
2110 	buf->mappable_size = size;
2111 
2112 	/* Allocate the internal kernel buffer */
2113 	size = num_elements * sizeof(struct hl_user_pending_interrupt);
2114 	p = vzalloc(size);
2115 	if (!p)
2116 		goto free_user_buff;
2117 
2118 	ts_buff->kernel_buff_address = p;
2119 	ts_buff->kernel_buff_size = size;
2120 
2121 	buf->private = ts_buff;
2122 
2123 	return 0;
2124 
2125 free_user_buff:
2126 	vfree(ts_buff->user_buff_address);
2127 free_mem:
2128 	kfree(ts_buff);
2129 	return -ENOMEM;
2130 }
2131 
2132 static struct hl_mmap_mem_buf_behavior hl_ts_behavior = {
2133 	.topic = "TS",
2134 	.mem_id = HL_MMAP_TYPE_TS_BUFF,
2135 	.mmap = hl_ts_mmap,
2136 	.alloc = hl_ts_alloc_buf,
2137 	.release = ts_buff_release,
2138 };
2139 
2140 /**
2141  * allocate_timestamps_buffers() - allocate timestamps buffers
2142  * This function will allocate ts buffer that will later on be mapped to the user
2143  * in order to be able to read the timestamp.
2144  * in addition it'll allocate an extra buffer for registration management.
2145  * since we cannot fail during registration for out-of-memory situation, so
2146  * we'll prepare a pool which will be used as user interrupt nodes and instead
2147  * of dynamically allocating nodes while registration we'll pick the node from
2148  * this pool. in addition it'll add node to the mapping hash which will be used
2149  * to map user ts buffer to the internal kernel ts buffer.
2150  * @hpriv: pointer to the private data of the fd
2151  * @args: ioctl input
2152  * @handle: user timestamp buffer handle as an output
2153  */
2154 static int allocate_timestamps_buffers(struct hl_fpriv *hpriv, struct hl_mem_in *args, u64 *handle)
2155 {
2156 	struct hl_mem_mgr *mmg = &hpriv->mem_mgr;
2157 	struct hl_mmap_mem_buf *buf;
2158 
2159 	if (args->num_of_elements > TS_MAX_ELEMENTS_NUM) {
2160 		dev_err(mmg->dev, "Num of elements exceeds Max allowed number (0x%x > 0x%x)\n",
2161 				args->num_of_elements, TS_MAX_ELEMENTS_NUM);
2162 		return -EINVAL;
2163 	}
2164 
2165 	buf = hl_mmap_mem_buf_alloc(mmg, &hl_ts_behavior, GFP_KERNEL, &args->num_of_elements);
2166 	if (!buf)
2167 		return -ENOMEM;
2168 
2169 	*handle = buf->handle;
2170 
2171 	return 0;
2172 }
2173 
2174 int hl_mem_ioctl(struct hl_fpriv *hpriv, void *data)
2175 {
2176 	enum hl_device_status status;
2177 	union hl_mem_args *args = data;
2178 	struct hl_device *hdev = hpriv->hdev;
2179 	struct hl_ctx *ctx = hpriv->ctx;
2180 	u64 block_handle, device_addr = 0;
2181 	u32 handle = 0, block_size;
2182 	int rc, dmabuf_fd = -EBADF;
2183 
2184 	if (!hl_device_operational(hdev, &status)) {
2185 		dev_dbg_ratelimited(hdev->dev,
2186 			"Device is %s. Can't execute MEMORY IOCTL\n",
2187 			hdev->status[status]);
2188 		return -EBUSY;
2189 	}
2190 
2191 	switch (args->in.op) {
2192 	case HL_MEM_OP_ALLOC:
2193 		if (args->in.alloc.mem_size == 0) {
2194 			dev_err(hdev->dev,
2195 				"alloc size must be larger than 0\n");
2196 			rc = -EINVAL;
2197 			goto out;
2198 		}
2199 
2200 		/* If DRAM does not support virtual memory the driver won't
2201 		 * handle the allocation/freeing of that memory. However, for
2202 		 * system administration/monitoring purposes, the driver will
2203 		 * keep track of the amount of DRAM memory that is allocated
2204 		 * and freed by the user. Because this code totally relies on
2205 		 * the user's input, the driver can't ensure the validity
2206 		 * of this accounting.
2207 		 */
2208 		if (!hdev->asic_prop.dram_supports_virtual_memory) {
2209 			atomic64_add(args->in.alloc.mem_size,
2210 					&ctx->dram_phys_mem);
2211 			atomic64_add(args->in.alloc.mem_size,
2212 					&hdev->dram_used_mem);
2213 
2214 			dev_dbg(hdev->dev, "DRAM alloc is not supported\n");
2215 			rc = 0;
2216 
2217 			memset(args, 0, sizeof(*args));
2218 			args->out.handle = 0;
2219 			goto out;
2220 		}
2221 
2222 		rc = alloc_device_memory(ctx, &args->in, &handle);
2223 
2224 		memset(args, 0, sizeof(*args));
2225 		args->out.handle = (__u64) handle;
2226 		break;
2227 
2228 	case HL_MEM_OP_FREE:
2229 		/* If DRAM does not support virtual memory the driver won't
2230 		 * handle the allocation/freeing of that memory. However, for
2231 		 * system administration/monitoring purposes, the driver will
2232 		 * keep track of the amount of DRAM memory that is allocated
2233 		 * and freed by the user. Because this code totally relies on
2234 		 * the user's input, the driver can't ensure the validity
2235 		 * of this accounting.
2236 		 */
2237 		if (!hdev->asic_prop.dram_supports_virtual_memory) {
2238 			atomic64_sub(args->in.alloc.mem_size,
2239 					&ctx->dram_phys_mem);
2240 			atomic64_sub(args->in.alloc.mem_size,
2241 					&hdev->dram_used_mem);
2242 
2243 			dev_dbg(hdev->dev, "DRAM alloc is not supported\n");
2244 			rc = 0;
2245 
2246 			goto out;
2247 		}
2248 
2249 		rc = free_device_memory(ctx, &args->in);
2250 		break;
2251 
2252 	case HL_MEM_OP_MAP:
2253 		rc = map_device_va(ctx, &args->in, &device_addr);
2254 
2255 		memset(args, 0, sizeof(*args));
2256 		args->out.device_virt_addr = device_addr;
2257 		break;
2258 
2259 	case HL_MEM_OP_UNMAP:
2260 		rc = unmap_device_va(ctx, &args->in, false);
2261 		break;
2262 
2263 	case HL_MEM_OP_MAP_BLOCK:
2264 		rc = map_block(hdev, args->in.map_block.block_addr,
2265 				&block_handle, &block_size);
2266 		args->out.block_handle = block_handle;
2267 		args->out.block_size = block_size;
2268 		break;
2269 
2270 	case HL_MEM_OP_EXPORT_DMABUF_FD:
2271 		rc = export_dmabuf_from_addr(ctx,
2272 				args->in.export_dmabuf_fd.addr,
2273 				args->in.export_dmabuf_fd.mem_size,
2274 				args->in.export_dmabuf_fd.offset,
2275 				args->in.flags,
2276 				&dmabuf_fd);
2277 		memset(args, 0, sizeof(*args));
2278 		args->out.fd = dmabuf_fd;
2279 		break;
2280 
2281 	case HL_MEM_OP_TS_ALLOC:
2282 		rc = allocate_timestamps_buffers(hpriv, &args->in, &args->out.handle);
2283 		break;
2284 	default:
2285 		dev_err(hdev->dev, "Unknown opcode for memory IOCTL\n");
2286 		rc = -EINVAL;
2287 		break;
2288 	}
2289 
2290 out:
2291 	return rc;
2292 }
2293 
2294 static int get_user_memory(struct hl_device *hdev, u64 addr, u64 size,
2295 				u32 npages, u64 start, u32 offset,
2296 				struct hl_userptr *userptr)
2297 {
2298 	int rc;
2299 
2300 	if (!access_ok((void __user *) (uintptr_t) addr, size)) {
2301 		dev_err(hdev->dev, "user pointer is invalid - 0x%llx\n", addr);
2302 		return -EFAULT;
2303 	}
2304 
2305 	userptr->pages = kvmalloc_array(npages, sizeof(struct page *), GFP_KERNEL);
2306 	if (!userptr->pages)
2307 		return -ENOMEM;
2308 
2309 	rc = pin_user_pages_fast(start, npages, FOLL_WRITE | FOLL_LONGTERM,
2310 				 userptr->pages);
2311 
2312 	if (rc != npages) {
2313 		dev_err(hdev->dev,
2314 			"Failed (%d) to pin host memory with user ptr 0x%llx, size 0x%llx, npages %d\n",
2315 			rc, addr, size, npages);
2316 		if (rc < 0)
2317 			goto destroy_pages;
2318 		npages = rc;
2319 		rc = -EFAULT;
2320 		goto put_pages;
2321 	}
2322 	userptr->npages = npages;
2323 
2324 	rc = sg_alloc_table_from_pages(userptr->sgt,
2325 				       userptr->pages,
2326 				       npages, offset, size, GFP_KERNEL);
2327 	if (rc < 0) {
2328 		dev_err(hdev->dev, "failed to create SG table from pages\n");
2329 		goto put_pages;
2330 	}
2331 
2332 	return 0;
2333 
2334 put_pages:
2335 	unpin_user_pages(userptr->pages, npages);
2336 destroy_pages:
2337 	kvfree(userptr->pages);
2338 	return rc;
2339 }
2340 
2341 /**
2342  * hl_pin_host_memory() - pins a chunk of host memory.
2343  * @hdev: pointer to the habanalabs device structure.
2344  * @addr: the host virtual address of the memory area.
2345  * @size: the size of the memory area.
2346  * @userptr: pointer to hl_userptr structure.
2347  *
2348  * This function does the following:
2349  * - Pins the physical pages.
2350  * - Create an SG list from those pages.
2351  */
2352 int hl_pin_host_memory(struct hl_device *hdev, u64 addr, u64 size,
2353 					struct hl_userptr *userptr)
2354 {
2355 	u64 start, end;
2356 	u32 npages, offset;
2357 	int rc;
2358 
2359 	if (!size) {
2360 		dev_err(hdev->dev, "size to pin is invalid - %llu\n", size);
2361 		return -EINVAL;
2362 	}
2363 
2364 	/*
2365 	 * If the combination of the address and size requested for this memory
2366 	 * region causes an integer overflow, return error.
2367 	 */
2368 	if (((addr + size) < addr) ||
2369 			PAGE_ALIGN(addr + size) < (addr + size)) {
2370 		dev_err(hdev->dev,
2371 			"user pointer 0x%llx + %llu causes integer overflow\n",
2372 			addr, size);
2373 		return -EINVAL;
2374 	}
2375 
2376 	userptr->pid = current->pid;
2377 	userptr->sgt = kzalloc(sizeof(*userptr->sgt), GFP_KERNEL);
2378 	if (!userptr->sgt)
2379 		return -ENOMEM;
2380 
2381 	start = addr & PAGE_MASK;
2382 	offset = addr & ~PAGE_MASK;
2383 	end = PAGE_ALIGN(addr + size);
2384 	npages = (end - start) >> PAGE_SHIFT;
2385 
2386 	userptr->size = size;
2387 	userptr->addr = addr;
2388 	userptr->dma_mapped = false;
2389 	INIT_LIST_HEAD(&userptr->job_node);
2390 
2391 	rc = get_user_memory(hdev, addr, size, npages, start, offset,
2392 				userptr);
2393 	if (rc) {
2394 		dev_err(hdev->dev,
2395 			"failed to get user memory for address 0x%llx\n",
2396 			addr);
2397 		goto free_sgt;
2398 	}
2399 
2400 	hl_debugfs_add_userptr(hdev, userptr);
2401 
2402 	return 0;
2403 
2404 free_sgt:
2405 	kfree(userptr->sgt);
2406 	return rc;
2407 }
2408 
2409 /*
2410  * hl_unpin_host_memory - unpins a chunk of host memory.
2411  * @hdev: pointer to the habanalabs device structure
2412  * @userptr: pointer to hl_userptr structure
2413  *
2414  * This function does the following:
2415  * - Unpins the physical pages related to the host memory
2416  * - Free the SG list
2417  */
2418 void hl_unpin_host_memory(struct hl_device *hdev, struct hl_userptr *userptr)
2419 {
2420 	hl_debugfs_remove_userptr(hdev, userptr);
2421 
2422 	if (userptr->dma_mapped)
2423 		hdev->asic_funcs->hl_dma_unmap_sgtable(hdev, userptr->sgt, userptr->dir);
2424 
2425 	unpin_user_pages_dirty_lock(userptr->pages, userptr->npages, true);
2426 	kvfree(userptr->pages);
2427 
2428 	list_del(&userptr->job_node);
2429 
2430 	sg_free_table(userptr->sgt);
2431 	kfree(userptr->sgt);
2432 }
2433 
2434 /**
2435  * hl_userptr_delete_list() - clear userptr list.
2436  * @hdev: pointer to the habanalabs device structure.
2437  * @userptr_list: pointer to the list to clear.
2438  *
2439  * This function does the following:
2440  * - Iterates over the list and unpins the host memory and frees the userptr
2441  *   structure.
2442  */
2443 void hl_userptr_delete_list(struct hl_device *hdev,
2444 				struct list_head *userptr_list)
2445 {
2446 	struct hl_userptr *userptr, *tmp;
2447 
2448 	list_for_each_entry_safe(userptr, tmp, userptr_list, job_node) {
2449 		hl_unpin_host_memory(hdev, userptr);
2450 		kfree(userptr);
2451 	}
2452 
2453 	INIT_LIST_HEAD(userptr_list);
2454 }
2455 
2456 /**
2457  * hl_userptr_is_pinned() - returns whether the given userptr is pinned.
2458  * @hdev: pointer to the habanalabs device structure.
2459  * @addr: user address to check.
2460  * @size: user block size to check.
2461  * @userptr_list: pointer to the list to clear.
2462  * @userptr: pointer to userptr to check.
2463  *
2464  * This function does the following:
2465  * - Iterates over the list and checks if the given userptr is in it, means is
2466  *   pinned. If so, returns true, otherwise returns false.
2467  */
2468 bool hl_userptr_is_pinned(struct hl_device *hdev, u64 addr,
2469 				u32 size, struct list_head *userptr_list,
2470 				struct hl_userptr **userptr)
2471 {
2472 	list_for_each_entry((*userptr), userptr_list, job_node) {
2473 		if ((addr == (*userptr)->addr) && (size == (*userptr)->size))
2474 			return true;
2475 	}
2476 
2477 	return false;
2478 }
2479 
2480 /**
2481  * va_range_init() - initialize virtual addresses range.
2482  * @hdev: pointer to the habanalabs device structure.
2483  * @va_ranges: pointer to va_ranges array.
2484  * @range_type: virtual address range type.
2485  * @start: range start address, inclusive.
2486  * @end: range end address, inclusive.
2487  * @page_size: page size for this va_range.
2488  *
2489  * This function does the following:
2490  * - Initializes the virtual addresses list of the given range with the given
2491  *   addresses.
2492  */
2493 static int va_range_init(struct hl_device *hdev, struct hl_va_range **va_ranges,
2494 				enum hl_va_range_type range_type, u64 start,
2495 				u64 end, u32 page_size)
2496 {
2497 	struct hl_va_range *va_range = va_ranges[range_type];
2498 	int rc;
2499 
2500 	INIT_LIST_HEAD(&va_range->list);
2501 
2502 	/*
2503 	 * PAGE_SIZE alignment
2504 	 * it is the caller's responsibility to align the addresses if the
2505 	 * page size is not a power of 2
2506 	 */
2507 
2508 	if (is_power_of_2(page_size)) {
2509 		start = round_up(start, page_size);
2510 
2511 		/*
2512 		 * The end of the range is inclusive, hence we need to align it
2513 		 * to the end of the last full page in the range. For example if
2514 		 * end = 0x3ff5 with page size 0x1000, we need to align it to
2515 		 * 0x2fff. The remaining 0xff5 bytes do not form a full page.
2516 		 */
2517 		end = round_down(end + 1, page_size) - 1;
2518 	}
2519 
2520 	if (start >= end) {
2521 		dev_err(hdev->dev, "too small vm range for va list\n");
2522 		return -EFAULT;
2523 	}
2524 
2525 	rc = add_va_block(hdev, va_range, start, end);
2526 
2527 	if (rc) {
2528 		dev_err(hdev->dev, "Failed to init host va list\n");
2529 		return rc;
2530 	}
2531 
2532 	va_range->start_addr = start;
2533 	va_range->end_addr = end;
2534 	va_range->page_size = page_size;
2535 
2536 	return 0;
2537 }
2538 
2539 /**
2540  * va_range_fini() - clear a virtual addresses range.
2541  * @hdev: pointer to the habanalabs structure.
2542  * @va_range: pointer to virtual addresses range.
2543  *
2544  * This function does the following:
2545  * - Frees the virtual addresses block list and its lock.
2546  */
2547 static void va_range_fini(struct hl_device *hdev, struct hl_va_range *va_range)
2548 {
2549 	mutex_lock(&va_range->lock);
2550 	clear_va_list_locked(hdev, &va_range->list);
2551 	mutex_unlock(&va_range->lock);
2552 
2553 	mutex_destroy(&va_range->lock);
2554 	kfree(va_range);
2555 }
2556 
2557 /**
2558  * vm_ctx_init_with_ranges() - initialize virtual memory for context.
2559  * @ctx: pointer to the habanalabs context structure.
2560  * @host_range_start: host virtual addresses range start.
2561  * @host_range_end: host virtual addresses range end.
2562  * @host_page_size: host page size.
2563  * @host_huge_range_start: host virtual addresses range start for memory
2564  *                         allocated with huge pages.
2565  * @host_huge_range_end: host virtual addresses range end for memory allocated
2566  *                        with huge pages.
2567  * @host_huge_page_size: host huge page size.
2568  * @dram_range_start: dram virtual addresses range start.
2569  * @dram_range_end: dram virtual addresses range end.
2570  * @dram_page_size: dram page size.
2571  *
2572  * This function initializes the following:
2573  * - MMU for context.
2574  * - Virtual address to area descriptor hashtable.
2575  * - Virtual block list of available virtual memory.
2576  */
2577 static int vm_ctx_init_with_ranges(struct hl_ctx *ctx,
2578 					u64 host_range_start,
2579 					u64 host_range_end,
2580 					u32 host_page_size,
2581 					u64 host_huge_range_start,
2582 					u64 host_huge_range_end,
2583 					u32 host_huge_page_size,
2584 					u64 dram_range_start,
2585 					u64 dram_range_end,
2586 					u32 dram_page_size)
2587 {
2588 	struct hl_device *hdev = ctx->hdev;
2589 	int i, rc;
2590 
2591 	for (i = 0 ; i < HL_VA_RANGE_TYPE_MAX ; i++) {
2592 		ctx->va_range[i] =
2593 			kzalloc(sizeof(struct hl_va_range), GFP_KERNEL);
2594 		if (!ctx->va_range[i]) {
2595 			rc = -ENOMEM;
2596 			goto free_va_range;
2597 		}
2598 	}
2599 
2600 	rc = hl_mmu_ctx_init(ctx);
2601 	if (rc) {
2602 		dev_err(hdev->dev, "failed to init context %d\n", ctx->asid);
2603 		goto free_va_range;
2604 	}
2605 
2606 	mutex_init(&ctx->mem_hash_lock);
2607 	hash_init(ctx->mem_hash);
2608 
2609 	mutex_init(&ctx->va_range[HL_VA_RANGE_TYPE_HOST]->lock);
2610 
2611 	rc = va_range_init(hdev, ctx->va_range, HL_VA_RANGE_TYPE_HOST,
2612 			host_range_start, host_range_end, host_page_size);
2613 	if (rc) {
2614 		dev_err(hdev->dev, "failed to init host vm range\n");
2615 		goto mmu_ctx_fini;
2616 	}
2617 
2618 	if (hdev->pmmu_huge_range) {
2619 		mutex_init(&ctx->va_range[HL_VA_RANGE_TYPE_HOST_HUGE]->lock);
2620 
2621 		rc = va_range_init(hdev,
2622 			ctx->va_range, HL_VA_RANGE_TYPE_HOST_HUGE,
2623 			host_huge_range_start, host_huge_range_end,
2624 			host_huge_page_size);
2625 		if (rc) {
2626 			dev_err(hdev->dev,
2627 				"failed to init host huge vm range\n");
2628 			goto clear_host_va_range;
2629 		}
2630 	} else {
2631 		kfree(ctx->va_range[HL_VA_RANGE_TYPE_HOST_HUGE]);
2632 		ctx->va_range[HL_VA_RANGE_TYPE_HOST_HUGE] =
2633 				ctx->va_range[HL_VA_RANGE_TYPE_HOST];
2634 	}
2635 
2636 	mutex_init(&ctx->va_range[HL_VA_RANGE_TYPE_DRAM]->lock);
2637 
2638 	rc = va_range_init(hdev, ctx->va_range, HL_VA_RANGE_TYPE_DRAM,
2639 			dram_range_start, dram_range_end, dram_page_size);
2640 	if (rc) {
2641 		dev_err(hdev->dev, "failed to init dram vm range\n");
2642 		goto clear_host_huge_va_range;
2643 	}
2644 
2645 	hl_debugfs_add_ctx_mem_hash(hdev, ctx);
2646 
2647 	return 0;
2648 
2649 clear_host_huge_va_range:
2650 	mutex_destroy(&ctx->va_range[HL_VA_RANGE_TYPE_DRAM]->lock);
2651 
2652 	if (hdev->pmmu_huge_range) {
2653 		mutex_lock(&ctx->va_range[HL_VA_RANGE_TYPE_HOST_HUGE]->lock);
2654 		clear_va_list_locked(hdev,
2655 			&ctx->va_range[HL_VA_RANGE_TYPE_HOST_HUGE]->list);
2656 		mutex_unlock(&ctx->va_range[HL_VA_RANGE_TYPE_HOST_HUGE]->lock);
2657 	}
2658 clear_host_va_range:
2659 	if (hdev->pmmu_huge_range)
2660 		mutex_destroy(&ctx->va_range[HL_VA_RANGE_TYPE_HOST_HUGE]->lock);
2661 	mutex_lock(&ctx->va_range[HL_VA_RANGE_TYPE_HOST]->lock);
2662 	clear_va_list_locked(hdev, &ctx->va_range[HL_VA_RANGE_TYPE_HOST]->list);
2663 	mutex_unlock(&ctx->va_range[HL_VA_RANGE_TYPE_HOST]->lock);
2664 mmu_ctx_fini:
2665 	mutex_destroy(&ctx->va_range[HL_VA_RANGE_TYPE_HOST]->lock);
2666 	mutex_destroy(&ctx->mem_hash_lock);
2667 	hl_mmu_ctx_fini(ctx);
2668 free_va_range:
2669 	for (i = 0 ; i < HL_VA_RANGE_TYPE_MAX ; i++)
2670 		kfree(ctx->va_range[i]);
2671 
2672 	return rc;
2673 }
2674 
2675 int hl_vm_ctx_init(struct hl_ctx *ctx)
2676 {
2677 	struct asic_fixed_properties *prop = &ctx->hdev->asic_prop;
2678 	u64 host_range_start, host_range_end, host_huge_range_start,
2679 		host_huge_range_end, dram_range_start, dram_range_end;
2680 	u32 host_page_size, host_huge_page_size, dram_page_size;
2681 
2682 	atomic64_set(&ctx->dram_phys_mem, 0);
2683 
2684 	/*
2685 	 *   In case of DRAM mapping, the returned address is the physical
2686 	 *   address of the memory related to the given handle.
2687 	 */
2688 	if (ctx->hdev->mmu_disable)
2689 		return 0;
2690 
2691 	dram_range_start = prop->dmmu.start_addr;
2692 	dram_range_end = prop->dmmu.end_addr - 1;
2693 	dram_page_size = prop->dram_page_size ?
2694 				prop->dram_page_size : prop->dmmu.page_size;
2695 	host_range_start = prop->pmmu.start_addr;
2696 	host_range_end = prop->pmmu.end_addr - 1;
2697 	host_page_size = prop->pmmu.page_size;
2698 	host_huge_range_start = prop->pmmu_huge.start_addr;
2699 	host_huge_range_end = prop->pmmu_huge.end_addr - 1;
2700 	host_huge_page_size = prop->pmmu_huge.page_size;
2701 
2702 	return vm_ctx_init_with_ranges(ctx, host_range_start, host_range_end,
2703 			host_page_size, host_huge_range_start,
2704 			host_huge_range_end, host_huge_page_size,
2705 			dram_range_start, dram_range_end, dram_page_size);
2706 }
2707 
2708 /**
2709  * hl_vm_ctx_fini() - virtual memory teardown of context.
2710  * @ctx: pointer to the habanalabs context structure.
2711  *
2712  * This function perform teardown the following:
2713  * - Virtual block list of available virtual memory.
2714  * - Virtual address to area descriptor hashtable.
2715  * - MMU for context.
2716  *
2717  * In addition this function does the following:
2718  * - Unmaps the existing hashtable nodes if the hashtable is not empty. The
2719  *   hashtable should be empty as no valid mappings should exist at this
2720  *   point.
2721  * - Frees any existing physical page list from the idr which relates to the
2722  *   current context asid.
2723  * - This function checks the virtual block list for correctness. At this point
2724  *   the list should contain one element which describes the whole virtual
2725  *   memory range of the context. Otherwise, a warning is printed.
2726  */
2727 void hl_vm_ctx_fini(struct hl_ctx *ctx)
2728 {
2729 	struct hl_vm_phys_pg_pack *phys_pg_list, *tmp_phys_node;
2730 	struct hl_device *hdev = ctx->hdev;
2731 	struct hl_vm_hash_node *hnode;
2732 	struct hl_vm *vm = &hdev->vm;
2733 	struct hlist_node *tmp_node;
2734 	struct list_head free_list;
2735 	struct hl_mem_in args;
2736 	int i;
2737 
2738 	if (hdev->mmu_disable)
2739 		return;
2740 
2741 	hl_debugfs_remove_ctx_mem_hash(hdev, ctx);
2742 
2743 	/*
2744 	 * Clearly something went wrong on hard reset so no point in printing
2745 	 * another side effect error
2746 	 */
2747 	if (!hdev->reset_info.hard_reset_pending && !hash_empty(ctx->mem_hash))
2748 		dev_dbg(hdev->dev,
2749 			"user released device without removing its memory mappings\n");
2750 
2751 	hash_for_each_safe(ctx->mem_hash, i, tmp_node, hnode, node) {
2752 		dev_dbg(hdev->dev,
2753 			"hl_mem_hash_node of vaddr 0x%llx of asid %d is still alive\n",
2754 			hnode->vaddr, ctx->asid);
2755 		args.unmap.device_virt_addr = hnode->vaddr;
2756 		unmap_device_va(ctx, &args, true);
2757 	}
2758 
2759 	mutex_lock(&hdev->mmu_lock);
2760 
2761 	/* invalidate the cache once after the unmapping loop */
2762 	hl_mmu_invalidate_cache(hdev, true, MMU_OP_USERPTR);
2763 	hl_mmu_invalidate_cache(hdev, true, MMU_OP_PHYS_PACK);
2764 
2765 	mutex_unlock(&hdev->mmu_lock);
2766 
2767 	INIT_LIST_HEAD(&free_list);
2768 
2769 	spin_lock(&vm->idr_lock);
2770 	idr_for_each_entry(&vm->phys_pg_pack_handles, phys_pg_list, i)
2771 		if (phys_pg_list->asid == ctx->asid) {
2772 			dev_dbg(hdev->dev,
2773 				"page list 0x%px of asid %d is still alive\n",
2774 				phys_pg_list, ctx->asid);
2775 
2776 			atomic64_sub(phys_pg_list->total_size, &hdev->dram_used_mem);
2777 			idr_remove(&vm->phys_pg_pack_handles, i);
2778 			list_add(&phys_pg_list->node, &free_list);
2779 		}
2780 	spin_unlock(&vm->idr_lock);
2781 
2782 	list_for_each_entry_safe(phys_pg_list, tmp_phys_node, &free_list, node)
2783 		free_phys_pg_pack(hdev, phys_pg_list);
2784 
2785 	va_range_fini(hdev, ctx->va_range[HL_VA_RANGE_TYPE_DRAM]);
2786 	va_range_fini(hdev, ctx->va_range[HL_VA_RANGE_TYPE_HOST]);
2787 
2788 	if (hdev->pmmu_huge_range)
2789 		va_range_fini(hdev, ctx->va_range[HL_VA_RANGE_TYPE_HOST_HUGE]);
2790 
2791 	mutex_destroy(&ctx->mem_hash_lock);
2792 	hl_mmu_ctx_fini(ctx);
2793 
2794 	/* In this case we need to clear the global accounting of DRAM usage
2795 	 * because the user notifies us on allocations. If the user is no more,
2796 	 * all DRAM is available
2797 	 */
2798 	if (ctx->asid != HL_KERNEL_ASID_ID &&
2799 			!hdev->asic_prop.dram_supports_virtual_memory)
2800 		atomic64_set(&hdev->dram_used_mem, 0);
2801 }
2802 
2803 /**
2804  * hl_vm_init() - initialize virtual memory module.
2805  * @hdev: pointer to the habanalabs device structure.
2806  *
2807  * This function initializes the following:
2808  * - MMU module.
2809  * - DRAM physical pages pool of 2MB.
2810  * - Idr for device memory allocation handles.
2811  */
2812 int hl_vm_init(struct hl_device *hdev)
2813 {
2814 	struct asic_fixed_properties *prop = &hdev->asic_prop;
2815 	struct hl_vm *vm = &hdev->vm;
2816 	int rc;
2817 
2818 	if (is_power_of_2(prop->dram_page_size))
2819 		vm->dram_pg_pool =
2820 			gen_pool_create(__ffs(prop->dram_page_size), -1);
2821 	else
2822 		vm->dram_pg_pool =
2823 			gen_pool_create(__ffs(DRAM_POOL_PAGE_SIZE), -1);
2824 
2825 	if (!vm->dram_pg_pool) {
2826 		dev_err(hdev->dev, "Failed to create dram page pool\n");
2827 		return -ENOMEM;
2828 	}
2829 
2830 	kref_init(&vm->dram_pg_pool_refcount);
2831 
2832 	rc = gen_pool_add(vm->dram_pg_pool, prop->dram_user_base_address,
2833 			prop->dram_end_address - prop->dram_user_base_address,
2834 			-1);
2835 
2836 	if (rc) {
2837 		dev_err(hdev->dev,
2838 			"Failed to add memory to dram page pool %d\n", rc);
2839 		goto pool_add_err;
2840 	}
2841 
2842 	spin_lock_init(&vm->idr_lock);
2843 	idr_init(&vm->phys_pg_pack_handles);
2844 
2845 	atomic64_set(&hdev->dram_used_mem, 0);
2846 
2847 	vm->init_done = true;
2848 
2849 	return 0;
2850 
2851 pool_add_err:
2852 	gen_pool_destroy(vm->dram_pg_pool);
2853 
2854 	return rc;
2855 }
2856 
2857 /**
2858  * hl_vm_fini() - virtual memory module teardown.
2859  * @hdev: pointer to the habanalabs device structure.
2860  *
2861  * This function perform teardown to the following:
2862  * - Idr for device memory allocation handles.
2863  * - DRAM physical pages pool of 2MB.
2864  * - MMU module.
2865  */
2866 void hl_vm_fini(struct hl_device *hdev)
2867 {
2868 	struct hl_vm *vm = &hdev->vm;
2869 
2870 	if (!vm->init_done)
2871 		return;
2872 
2873 	/*
2874 	 * At this point all the contexts should be freed and hence no DRAM
2875 	 * memory should be in use. Hence the DRAM pool should be freed here.
2876 	 */
2877 	if (kref_put(&vm->dram_pg_pool_refcount, dram_pg_pool_do_release) != 1)
2878 		dev_warn(hdev->dev, "dram_pg_pool was not destroyed on %s\n",
2879 				__func__);
2880 
2881 	vm->init_done = false;
2882 }
2883 
2884 /**
2885  * hl_hw_block_mem_init() - HW block memory initialization.
2886  * @ctx: pointer to the habanalabs context structure.
2887  *
2888  * This function initializes the HW block virtual mapped addresses list and
2889  * it's lock.
2890  */
2891 void hl_hw_block_mem_init(struct hl_ctx *ctx)
2892 {
2893 	mutex_init(&ctx->hw_block_list_lock);
2894 	INIT_LIST_HEAD(&ctx->hw_block_mem_list);
2895 }
2896 
2897 /**
2898  * hl_hw_block_mem_fini() - HW block memory teardown.
2899  * @ctx: pointer to the habanalabs context structure.
2900  *
2901  * This function clears the HW block virtual mapped addresses list and destroys
2902  * it's lock.
2903  */
2904 void hl_hw_block_mem_fini(struct hl_ctx *ctx)
2905 {
2906 	struct hl_vm_hw_block_list_node *lnode, *tmp;
2907 
2908 	if (!list_empty(&ctx->hw_block_mem_list))
2909 		dev_crit(ctx->hdev->dev, "HW block mem list isn't empty\n");
2910 
2911 	list_for_each_entry_safe(lnode, tmp, &ctx->hw_block_mem_list, node) {
2912 		list_del(&lnode->node);
2913 		kfree(lnode);
2914 	}
2915 
2916 	mutex_destroy(&ctx->hw_block_list_lock);
2917 }
2918