1 // SPDX-License-Identifier: GPL-2.0
4 * Copyright 2016-2019 HabanaLabs, Ltd.
8 #include <uapi/misc/habanalabs.h>
9 #include "habanalabs.h"
10 #include "include/hw_ip/mmu/mmu_general.h"
12 #include <linux/uaccess.h>
13 #include <linux/slab.h>
14 #include <linux/genalloc.h>
16 #define PGS_IN_2MB_PAGE (PAGE_SIZE_2MB >> PAGE_SHIFT)
17 #define HL_MMU_DEBUG 0
20 * The va ranges in context object contain a list with the available chunks of
21 * device virtual memory.
22 * There is one range for host allocations and one for DRAM allocations.
24 * On initialization each range contains one chunk of all of its available
25 * virtual range which is a half of the total device virtual range.
27 * On each mapping of physical pages, a suitable virtual range chunk (with a
28 * minimum size) is selected from the list. If the chunk size equals the
29 * requested size, the chunk is returned. Otherwise, the chunk is split into
30 * two chunks - one to return as result and a remainder to stay in the list.
32 * On each Unmapping of a virtual address, the relevant virtual chunk is
33 * returned to the list. The chunk is added to the list and if its edges match
34 * the edges of the adjacent chunks (means a contiguous chunk can be created),
35 * the chunks are merged.
37 * On finish, the list is checked to have only one chunk of all the relevant
38 * virtual range (which is a half of the device total virtual range).
39 * If not (means not all mappings were unmapped), a warning is printed.
43 * alloc_device_memory - allocate device memory
45 * @ctx : current context
46 * @args : host parameters containing the requested size
47 * @ret_handle : result handle
49 * This function does the following:
50 * - Allocate the requested size rounded up to 2MB pages
51 * - Return unique handle
53 static int alloc_device_memory(struct hl_ctx *ctx, struct hl_mem_in *args,
56 struct hl_device *hdev = ctx->hdev;
57 struct hl_vm *vm = &hdev->vm;
58 struct hl_vm_phys_pg_pack *phys_pg_pack;
59 u64 paddr = 0, total_size, num_pgs, i;
60 u32 num_curr_pgs, page_size, page_shift;
65 page_size = hdev->asic_prop.dram_page_size;
66 page_shift = __ffs(page_size);
67 num_pgs = (args->alloc.mem_size + (page_size - 1)) >> page_shift;
68 total_size = num_pgs << page_shift;
70 contiguous = args->flags & HL_MEM_CONTIGUOUS;
73 paddr = (u64) gen_pool_alloc(vm->dram_pg_pool, total_size);
76 "failed to allocate %llu huge contiguous pages\n",
82 phys_pg_pack = kzalloc(sizeof(*phys_pg_pack), GFP_KERNEL);
88 phys_pg_pack->vm_type = VM_TYPE_PHYS_PACK;
89 phys_pg_pack->asid = ctx->asid;
90 phys_pg_pack->npages = num_pgs;
91 phys_pg_pack->page_size = page_size;
92 phys_pg_pack->total_size = total_size;
93 phys_pg_pack->flags = args->flags;
94 phys_pg_pack->contiguous = contiguous;
96 phys_pg_pack->pages = kvmalloc_array(num_pgs, sizeof(u64), GFP_KERNEL);
97 if (!phys_pg_pack->pages) {
102 if (phys_pg_pack->contiguous) {
103 for (i = 0 ; i < num_pgs ; i++)
104 phys_pg_pack->pages[i] = paddr + i * page_size;
106 for (i = 0 ; i < num_pgs ; i++) {
107 phys_pg_pack->pages[i] = (u64) gen_pool_alloc(
110 if (!phys_pg_pack->pages[i]) {
112 "Failed to allocate device memory (out of memory)\n");
121 spin_lock(&vm->idr_lock);
122 handle = idr_alloc(&vm->phys_pg_pack_handles, phys_pg_pack, 1, 0,
124 spin_unlock(&vm->idr_lock);
127 dev_err(hdev->dev, "Failed to get handle for page\n");
132 for (i = 0 ; i < num_pgs ; i++)
133 kref_get(&vm->dram_pg_pool_refcount);
135 phys_pg_pack->handle = handle;
137 atomic64_add(phys_pg_pack->total_size, &ctx->dram_phys_mem);
138 atomic64_add(phys_pg_pack->total_size, &hdev->dram_used_mem);
140 *ret_handle = handle;
146 if (!phys_pg_pack->contiguous)
147 for (i = 0 ; i < num_curr_pgs ; i++)
148 gen_pool_free(vm->dram_pg_pool, phys_pg_pack->pages[i],
151 kvfree(phys_pg_pack->pages);
156 gen_pool_free(vm->dram_pg_pool, paddr, total_size);
162 * get_userptr_from_host_va - initialize userptr structure from given host
165 * @hdev : habanalabs device structure
166 * @args : parameters containing the virtual address and size
167 * @p_userptr : pointer to result userptr structure
169 * This function does the following:
170 * - Allocate userptr structure
171 * - Pin the given host memory using the userptr structure
172 * - Perform DMA mapping to have the DMA addresses of the pages
174 static int get_userptr_from_host_va(struct hl_device *hdev,
175 struct hl_mem_in *args, struct hl_userptr **p_userptr)
177 struct hl_userptr *userptr;
180 userptr = kzalloc(sizeof(*userptr), GFP_KERNEL);
186 rc = hl_pin_host_memory(hdev, args->map_host.host_virt_addr,
187 args->map_host.mem_size, userptr);
189 dev_err(hdev->dev, "Failed to pin host memory\n");
193 rc = hdev->asic_funcs->asic_dma_map_sg(hdev, userptr->sgt->sgl,
194 userptr->sgt->nents, DMA_BIDIRECTIONAL);
196 dev_err(hdev->dev, "failed to map sgt with DMA region\n");
200 userptr->dma_mapped = true;
201 userptr->dir = DMA_BIDIRECTIONAL;
202 userptr->vm_type = VM_TYPE_USERPTR;
204 *p_userptr = userptr;
209 hl_unpin_host_memory(hdev, userptr);
218 * free_userptr - free userptr structure
220 * @hdev : habanalabs device structure
221 * @userptr : userptr to free
223 * This function does the following:
224 * - Unpins the physical pages
225 * - Frees the userptr structure
227 static void free_userptr(struct hl_device *hdev, struct hl_userptr *userptr)
229 hl_unpin_host_memory(hdev, userptr);
234 * dram_pg_pool_do_release - free DRAM pages pool
236 * @ref : pointer to reference object
238 * This function does the following:
239 * - Frees the idr structure of physical pages handles
240 * - Frees the generic pool of DRAM physical pages
242 static void dram_pg_pool_do_release(struct kref *ref)
244 struct hl_vm *vm = container_of(ref, struct hl_vm,
245 dram_pg_pool_refcount);
248 * free the idr here as only here we know for sure that there are no
249 * allocated physical pages and hence there are no handles in use
251 idr_destroy(&vm->phys_pg_pack_handles);
252 gen_pool_destroy(vm->dram_pg_pool);
256 * free_phys_pg_pack - free physical page pack
258 * @hdev : habanalabs device structure
259 * @phys_pg_pack : physical page pack to free
261 * This function does the following:
262 * - For DRAM memory only, iterate over the pack and free each physical block
263 * structure by returning it to the general pool
264 * - Free the hl_vm_phys_pg_pack structure
266 static void free_phys_pg_pack(struct hl_device *hdev,
267 struct hl_vm_phys_pg_pack *phys_pg_pack)
269 struct hl_vm *vm = &hdev->vm;
272 if (!phys_pg_pack->created_from_userptr) {
273 if (phys_pg_pack->contiguous) {
274 gen_pool_free(vm->dram_pg_pool, phys_pg_pack->pages[0],
275 phys_pg_pack->total_size);
277 for (i = 0; i < phys_pg_pack->npages ; i++)
278 kref_put(&vm->dram_pg_pool_refcount,
279 dram_pg_pool_do_release);
281 for (i = 0 ; i < phys_pg_pack->npages ; i++) {
282 gen_pool_free(vm->dram_pg_pool,
283 phys_pg_pack->pages[i],
284 phys_pg_pack->page_size);
285 kref_put(&vm->dram_pg_pool_refcount,
286 dram_pg_pool_do_release);
291 kvfree(phys_pg_pack->pages);
296 * free_device_memory - free device memory
298 * @ctx : current context
299 * @handle : handle of the memory chunk to free
301 * This function does the following:
302 * - Free the device memory related to the given handle
304 static int free_device_memory(struct hl_ctx *ctx, u32 handle)
306 struct hl_device *hdev = ctx->hdev;
307 struct hl_vm *vm = &hdev->vm;
308 struct hl_vm_phys_pg_pack *phys_pg_pack;
310 spin_lock(&vm->idr_lock);
311 phys_pg_pack = idr_find(&vm->phys_pg_pack_handles, handle);
313 if (atomic_read(&phys_pg_pack->mapping_cnt) > 0) {
314 dev_err(hdev->dev, "handle %u is mapped, cannot free\n",
316 spin_unlock(&vm->idr_lock);
321 * must remove from idr before the freeing of the physical
322 * pages as the refcount of the pool is also the trigger of the
325 idr_remove(&vm->phys_pg_pack_handles, handle);
326 spin_unlock(&vm->idr_lock);
328 atomic64_sub(phys_pg_pack->total_size, &ctx->dram_phys_mem);
329 atomic64_sub(phys_pg_pack->total_size, &hdev->dram_used_mem);
331 free_phys_pg_pack(hdev, phys_pg_pack);
333 spin_unlock(&vm->idr_lock);
335 "free device memory failed, no match for handle %u\n",
344 * clear_va_list_locked - free virtual addresses list
346 * @hdev : habanalabs device structure
347 * @va_list : list of virtual addresses to free
349 * This function does the following:
350 * - Iterate over the list and free each virtual addresses block
352 * This function should be called only when va_list lock is taken
354 static void clear_va_list_locked(struct hl_device *hdev,
355 struct list_head *va_list)
357 struct hl_vm_va_block *va_block, *tmp;
359 list_for_each_entry_safe(va_block, tmp, va_list, node) {
360 list_del(&va_block->node);
366 * print_va_list_locked - print virtual addresses list
368 * @hdev : habanalabs device structure
369 * @va_list : list of virtual addresses to print
371 * This function does the following:
372 * - Iterate over the list and print each virtual addresses block
374 * This function should be called only when va_list lock is taken
376 static void print_va_list_locked(struct hl_device *hdev,
377 struct list_head *va_list)
380 struct hl_vm_va_block *va_block;
382 dev_dbg(hdev->dev, "print va list:\n");
384 list_for_each_entry(va_block, va_list, node)
386 "va block, start: 0x%llx, end: 0x%llx, size: %llu\n",
387 va_block->start, va_block->end, va_block->size);
392 * merge_va_blocks_locked - merge a virtual block if possible
394 * @hdev : pointer to the habanalabs device structure
395 * @va_list : pointer to the virtual addresses block list
396 * @va_block : virtual block to merge with adjacent blocks
398 * This function does the following:
399 * - Merge the given blocks with the adjacent blocks if their virtual ranges
400 * create a contiguous virtual range
402 * This Function should be called only when va_list lock is taken
404 static void merge_va_blocks_locked(struct hl_device *hdev,
405 struct list_head *va_list, struct hl_vm_va_block *va_block)
407 struct hl_vm_va_block *prev, *next;
409 prev = list_prev_entry(va_block, node);
410 if (&prev->node != va_list && prev->end + 1 == va_block->start) {
411 prev->end = va_block->end;
412 prev->size = prev->end - prev->start;
413 list_del(&va_block->node);
418 next = list_next_entry(va_block, node);
419 if (&next->node != va_list && va_block->end + 1 == next->start) {
420 next->start = va_block->start;
421 next->size = next->end - next->start;
422 list_del(&va_block->node);
428 * add_va_block_locked - add a virtual block to the virtual addresses list
430 * @hdev : pointer to the habanalabs device structure
431 * @va_list : pointer to the virtual addresses block list
432 * @start : start virtual address
433 * @end : end virtual address
435 * This function does the following:
436 * - Add the given block to the virtual blocks list and merge with other
437 * blocks if a contiguous virtual block can be created
439 * This Function should be called only when va_list lock is taken
441 static int add_va_block_locked(struct hl_device *hdev,
442 struct list_head *va_list, u64 start, u64 end)
444 struct hl_vm_va_block *va_block, *res = NULL;
445 u64 size = end - start;
447 print_va_list_locked(hdev, va_list);
449 list_for_each_entry(va_block, va_list, node) {
450 /* TODO: remove upon matureness */
451 if (hl_mem_area_crosses_range(start, size, va_block->start,
454 "block crossing ranges at start 0x%llx, end 0x%llx\n",
455 va_block->start, va_block->end);
459 if (va_block->end < start)
463 va_block = kmalloc(sizeof(*va_block), GFP_KERNEL);
467 va_block->start = start;
469 va_block->size = size;
472 list_add(&va_block->node, va_list);
474 list_add(&va_block->node, &res->node);
476 merge_va_blocks_locked(hdev, va_list, va_block);
478 print_va_list_locked(hdev, va_list);
484 * add_va_block - wrapper for add_va_block_locked
486 * @hdev : pointer to the habanalabs device structure
487 * @va_list : pointer to the virtual addresses block list
488 * @start : start virtual address
489 * @end : end virtual address
491 * This function does the following:
492 * - Takes the list lock and calls add_va_block_locked
494 static inline int add_va_block(struct hl_device *hdev,
495 struct hl_va_range *va_range, u64 start, u64 end)
499 mutex_lock(&va_range->lock);
500 rc = add_va_block_locked(hdev, &va_range->list, start, end);
501 mutex_unlock(&va_range->lock);
507 * get_va_block - get a virtual block with the requested size
509 * @hdev : pointer to the habanalabs device structure
510 * @va_range : pointer to the virtual addresses range
511 * @size : requested block size
512 * @hint_addr : hint for request address by the user
513 * @is_userptr : is host or DRAM memory
515 * This function does the following:
516 * - Iterate on the virtual block list to find a suitable virtual block for the
518 * - Reserve the requested block and update the list
519 * - Return the start address of the virtual block
521 static u64 get_va_block(struct hl_device *hdev,
522 struct hl_va_range *va_range, u64 size, u64 hint_addr,
525 struct hl_vm_va_block *va_block, *new_va_block = NULL;
526 u64 valid_start, valid_size, prev_start, prev_end, page_mask,
527 res_valid_start = 0, res_valid_size = 0;
529 bool add_prev = false;
533 * We cannot know if the user allocated memory with huge pages
534 * or not, hence we continue with the biggest possible
537 page_size = PAGE_SIZE_2MB;
538 page_mask = PAGE_MASK_2MB;
540 page_size = hdev->asic_prop.dram_page_size;
541 page_mask = ~((u64)page_size - 1);
544 mutex_lock(&va_range->lock);
546 print_va_list_locked(hdev, &va_range->list);
548 list_for_each_entry(va_block, &va_range->list, node) {
549 /* calc the first possible aligned addr */
550 valid_start = va_block->start;
553 if (valid_start & (page_size - 1)) {
554 valid_start &= page_mask;
555 valid_start += page_size;
556 if (valid_start > va_block->end)
560 valid_size = va_block->end - valid_start;
562 if (valid_size >= size &&
563 (!new_va_block || valid_size < res_valid_size)) {
565 new_va_block = va_block;
566 res_valid_start = valid_start;
567 res_valid_size = valid_size;
570 if (hint_addr && hint_addr >= valid_start &&
571 ((hint_addr + size) <= va_block->end)) {
572 new_va_block = va_block;
573 res_valid_start = hint_addr;
574 res_valid_size = valid_size;
580 dev_err(hdev->dev, "no available va block for size %llu\n",
585 if (res_valid_start > new_va_block->start) {
586 prev_start = new_va_block->start;
587 prev_end = res_valid_start - 1;
589 new_va_block->start = res_valid_start;
590 new_va_block->size = res_valid_size;
595 if (new_va_block->size > size) {
596 new_va_block->start += size;
597 new_va_block->size = new_va_block->end - new_va_block->start;
599 list_del(&new_va_block->node);
604 add_va_block_locked(hdev, &va_range->list, prev_start,
607 print_va_list_locked(hdev, &va_range->list);
609 mutex_unlock(&va_range->lock);
611 return res_valid_start;
615 * get_sg_info - get number of pages and the DMA address from SG list
618 * @dma_addr : pointer to DMA address to return
620 * Calculate the number of consecutive pages described by the SG list. Take the
621 * offset of the address in the first page, add to it the length and round it up
622 * to the number of needed pages.
624 static u32 get_sg_info(struct scatterlist *sg, dma_addr_t *dma_addr)
626 *dma_addr = sg_dma_address(sg);
628 return ((((*dma_addr) & (PAGE_SIZE - 1)) + sg_dma_len(sg)) +
629 (PAGE_SIZE - 1)) >> PAGE_SHIFT;
633 * init_phys_pg_pack_from_userptr - initialize physical page pack from host
636 * @ctx : current context
637 * @userptr : userptr to initialize from
638 * @pphys_pg_pack : res pointer
640 * This function does the following:
641 * - Pin the physical pages related to the given virtual block
642 * - Create a physical page pack from the physical pages related to the given
645 static int init_phys_pg_pack_from_userptr(struct hl_ctx *ctx,
646 struct hl_userptr *userptr,
647 struct hl_vm_phys_pg_pack **pphys_pg_pack)
649 struct hl_vm_phys_pg_pack *phys_pg_pack;
650 struct scatterlist *sg;
652 u64 page_mask, total_npages;
653 u32 npages, page_size = PAGE_SIZE;
654 bool first = true, is_huge_page_opt = true;
657 phys_pg_pack = kzalloc(sizeof(*phys_pg_pack), GFP_KERNEL);
661 phys_pg_pack->vm_type = userptr->vm_type;
662 phys_pg_pack->created_from_userptr = true;
663 phys_pg_pack->asid = ctx->asid;
664 atomic_set(&phys_pg_pack->mapping_cnt, 1);
666 /* Only if all dma_addrs are aligned to 2MB and their
667 * sizes is at least 2MB, we can use huge page mapping.
668 * We limit the 2MB optimization to this condition,
669 * since later on we acquire the related VA range as one
673 for_each_sg(userptr->sgt->sgl, sg, userptr->sgt->nents, i) {
674 npages = get_sg_info(sg, &dma_addr);
676 total_npages += npages;
678 if ((npages % PGS_IN_2MB_PAGE) ||
679 (dma_addr & (PAGE_SIZE_2MB - 1)))
680 is_huge_page_opt = false;
683 if (is_huge_page_opt) {
684 page_size = PAGE_SIZE_2MB;
685 total_npages /= PGS_IN_2MB_PAGE;
688 page_mask = ~(((u64) page_size) - 1);
690 phys_pg_pack->pages = kvmalloc_array(total_npages, sizeof(u64),
692 if (!phys_pg_pack->pages) {
694 goto page_pack_arr_mem_err;
697 phys_pg_pack->npages = total_npages;
698 phys_pg_pack->page_size = page_size;
699 phys_pg_pack->total_size = total_npages * page_size;
702 for_each_sg(userptr->sgt->sgl, sg, userptr->sgt->nents, i) {
703 npages = get_sg_info(sg, &dma_addr);
705 /* align down to physical page size and save the offset */
708 phys_pg_pack->offset = dma_addr & (page_size - 1);
709 dma_addr &= page_mask;
713 phys_pg_pack->pages[j++] = dma_addr;
714 dma_addr += page_size;
716 if (is_huge_page_opt)
717 npages -= PGS_IN_2MB_PAGE;
723 *pphys_pg_pack = phys_pg_pack;
727 page_pack_arr_mem_err:
734 * map_phys_page_pack - maps the physical page pack
736 * @ctx : current context
737 * @vaddr : start address of the virtual area to map from
738 * @phys_pg_pack : the pack of physical pages to map to
740 * This function does the following:
741 * - Maps each chunk of virtual memory to matching physical chunk
742 * - Stores number of successful mappings in the given argument
743 * - Returns 0 on success, error code otherwise.
745 static int map_phys_page_pack(struct hl_ctx *ctx, u64 vaddr,
746 struct hl_vm_phys_pg_pack *phys_pg_pack)
748 struct hl_device *hdev = ctx->hdev;
749 u64 next_vaddr = vaddr, paddr, mapped_pg_cnt = 0, i;
750 u32 page_size = phys_pg_pack->page_size;
753 for (i = 0 ; i < phys_pg_pack->npages ; i++) {
754 paddr = phys_pg_pack->pages[i];
756 rc = hl_mmu_map(ctx, next_vaddr, paddr, page_size);
759 "map failed for handle %u, npages: %llu, mapped: %llu",
760 phys_pg_pack->handle, phys_pg_pack->npages,
766 next_vaddr += page_size;
773 for (i = 0 ; i < mapped_pg_cnt ; i++) {
774 if (hl_mmu_unmap(ctx, next_vaddr, page_size))
775 dev_warn_ratelimited(hdev->dev,
776 "failed to unmap handle %u, va: 0x%llx, pa: 0x%llx, page size: %u\n",
777 phys_pg_pack->handle, next_vaddr,
778 phys_pg_pack->pages[i], page_size);
780 next_vaddr += page_size;
786 static int get_paddr_from_handle(struct hl_ctx *ctx, struct hl_mem_in *args,
789 struct hl_device *hdev = ctx->hdev;
790 struct hl_vm *vm = &hdev->vm;
791 struct hl_vm_phys_pg_pack *phys_pg_pack;
794 handle = lower_32_bits(args->map_device.handle);
795 spin_lock(&vm->idr_lock);
796 phys_pg_pack = idr_find(&vm->phys_pg_pack_handles, handle);
798 spin_unlock(&vm->idr_lock);
799 dev_err(hdev->dev, "no match for handle %u\n", handle);
803 *paddr = phys_pg_pack->pages[0];
805 spin_unlock(&vm->idr_lock);
811 * map_device_va - map the given memory
813 * @ctx : current context
814 * @args : host parameters with handle/host virtual address
815 * @device_addr : pointer to result device virtual address
817 * This function does the following:
818 * - If given a physical device memory handle, map to a device virtual block
819 * and return the start address of this block
820 * - If given a host virtual address and size, find the related physical pages,
821 * map a device virtual block to this pages and return the start address of
824 static int map_device_va(struct hl_ctx *ctx, struct hl_mem_in *args,
827 struct hl_device *hdev = ctx->hdev;
828 struct hl_vm *vm = &hdev->vm;
829 struct hl_vm_phys_pg_pack *phys_pg_pack;
830 struct hl_userptr *userptr = NULL;
831 struct hl_vm_hash_node *hnode;
832 enum vm_type_t *vm_type;
833 u64 ret_vaddr, hint_addr;
836 bool is_userptr = args->flags & HL_MEM_USERPTR;
842 rc = get_userptr_from_host_va(hdev, args, &userptr);
844 dev_err(hdev->dev, "failed to get userptr from va\n");
848 rc = init_phys_pg_pack_from_userptr(ctx, userptr,
852 "unable to init page pack for vaddr 0x%llx\n",
853 args->map_host.host_virt_addr);
854 goto init_page_pack_err;
857 vm_type = (enum vm_type_t *) userptr;
858 hint_addr = args->map_host.hint_addr;
860 handle = lower_32_bits(args->map_device.handle);
862 spin_lock(&vm->idr_lock);
863 phys_pg_pack = idr_find(&vm->phys_pg_pack_handles, handle);
865 spin_unlock(&vm->idr_lock);
867 "no match for handle %u\n", handle);
871 /* increment now to avoid freeing device memory while mapping */
872 atomic_inc(&phys_pg_pack->mapping_cnt);
874 spin_unlock(&vm->idr_lock);
876 vm_type = (enum vm_type_t *) phys_pg_pack;
878 hint_addr = args->map_device.hint_addr;
882 * relevant for mapping device physical memory only, as host memory is
885 if (!is_userptr && !(phys_pg_pack->flags & HL_MEM_SHARED) &&
886 phys_pg_pack->asid != ctx->asid) {
888 "Failed to map memory, handle %u is not shared\n",
894 hnode = kzalloc(sizeof(*hnode), GFP_KERNEL);
900 ret_vaddr = get_va_block(hdev,
901 is_userptr ? &ctx->host_va_range : &ctx->dram_va_range,
902 phys_pg_pack->total_size, hint_addr, is_userptr);
904 dev_err(hdev->dev, "no available va block for handle %u\n",
910 mutex_lock(&ctx->mmu_lock);
912 rc = map_phys_page_pack(ctx, ret_vaddr, phys_pg_pack);
914 mutex_unlock(&ctx->mmu_lock);
915 dev_err(hdev->dev, "mapping page pack failed for handle %u\n",
920 hdev->asic_funcs->mmu_invalidate_cache(hdev, false);
922 mutex_unlock(&ctx->mmu_lock);
924 ret_vaddr += phys_pg_pack->offset;
926 hnode->ptr = vm_type;
927 hnode->vaddr = ret_vaddr;
929 mutex_lock(&ctx->mem_hash_lock);
930 hash_add(ctx->mem_hash, &hnode->node, ret_vaddr);
931 mutex_unlock(&ctx->mem_hash_lock);
933 *device_addr = ret_vaddr;
936 free_phys_pg_pack(hdev, phys_pg_pack);
941 if (add_va_block(hdev,
942 is_userptr ? &ctx->host_va_range : &ctx->dram_va_range,
944 ret_vaddr + phys_pg_pack->total_size - 1))
946 "release va block failed for handle 0x%x, vaddr: 0x%llx\n",
953 atomic_dec(&phys_pg_pack->mapping_cnt);
955 free_phys_pg_pack(hdev, phys_pg_pack);
958 free_userptr(hdev, userptr);
964 * unmap_device_va - unmap the given device virtual address
966 * @ctx : current context
967 * @vaddr : device virtual address to unmap
969 * This function does the following:
970 * - Unmap the physical pages related to the given virtual address
971 * - return the device virtual block to the virtual block list
973 static int unmap_device_va(struct hl_ctx *ctx, u64 vaddr)
975 struct hl_device *hdev = ctx->hdev;
976 struct hl_vm_phys_pg_pack *phys_pg_pack = NULL;
977 struct hl_vm_hash_node *hnode = NULL;
978 struct hl_userptr *userptr = NULL;
979 enum vm_type_t *vm_type;
985 /* protect from double entrance */
986 mutex_lock(&ctx->mem_hash_lock);
987 hash_for_each_possible(ctx->mem_hash, hnode, node, (unsigned long)vaddr)
988 if (vaddr == hnode->vaddr)
992 mutex_unlock(&ctx->mem_hash_lock);
994 "unmap failed, no mem hnode for vaddr 0x%llx\n",
999 hash_del(&hnode->node);
1000 mutex_unlock(&ctx->mem_hash_lock);
1002 vm_type = hnode->ptr;
1004 if (*vm_type == VM_TYPE_USERPTR) {
1006 userptr = hnode->ptr;
1007 rc = init_phys_pg_pack_from_userptr(ctx, userptr,
1011 "unable to init page pack for vaddr 0x%llx\n",
1015 } else if (*vm_type == VM_TYPE_PHYS_PACK) {
1017 phys_pg_pack = hnode->ptr;
1020 "unmap failed, unknown vm desc for vaddr 0x%llx\n",
1026 if (atomic_read(&phys_pg_pack->mapping_cnt) == 0) {
1027 dev_err(hdev->dev, "vaddr 0x%llx is not mapped\n", vaddr);
1029 goto mapping_cnt_err;
1032 page_size = phys_pg_pack->page_size;
1033 vaddr &= ~(((u64) page_size) - 1);
1037 mutex_lock(&ctx->mmu_lock);
1039 for (i = 0 ; i < phys_pg_pack->npages ; i++, next_vaddr += page_size) {
1040 if (hl_mmu_unmap(ctx, next_vaddr, page_size))
1041 dev_warn_ratelimited(hdev->dev,
1042 "unmap failed for vaddr: 0x%llx\n", next_vaddr);
1044 /* unmapping on Palladium can be really long, so avoid a CPU
1045 * soft lockup bug by sleeping a little between unmapping pages
1048 usleep_range(500, 1000);
1051 hdev->asic_funcs->mmu_invalidate_cache(hdev, true);
1053 mutex_unlock(&ctx->mmu_lock);
1055 if (add_va_block(hdev,
1056 is_userptr ? &ctx->host_va_range : &ctx->dram_va_range,
1058 vaddr + phys_pg_pack->total_size - 1))
1059 dev_warn(hdev->dev, "add va block failed for vaddr: 0x%llx\n",
1062 atomic_dec(&phys_pg_pack->mapping_cnt);
1066 free_phys_pg_pack(hdev, phys_pg_pack);
1067 free_userptr(hdev, userptr);
1074 free_phys_pg_pack(hdev, phys_pg_pack);
1076 mutex_lock(&ctx->mem_hash_lock);
1077 hash_add(ctx->mem_hash, &hnode->node, vaddr);
1078 mutex_unlock(&ctx->mem_hash_lock);
1083 static int mem_ioctl_no_mmu(struct hl_fpriv *hpriv, union hl_mem_args *args)
1085 struct hl_device *hdev = hpriv->hdev;
1086 struct hl_ctx *ctx = hpriv->ctx;
1087 u64 device_addr = 0;
1091 switch (args->in.op) {
1092 case HL_MEM_OP_ALLOC:
1093 if (args->in.alloc.mem_size == 0) {
1095 "alloc size must be larger than 0\n");
1100 /* Force contiguous as there are no real MMU
1101 * translations to overcome physical memory gaps
1103 args->in.flags |= HL_MEM_CONTIGUOUS;
1104 rc = alloc_device_memory(ctx, &args->in, &handle);
1106 memset(args, 0, sizeof(*args));
1107 args->out.handle = (__u64) handle;
1110 case HL_MEM_OP_FREE:
1111 rc = free_device_memory(ctx, args->in.free.handle);
1115 if (args->in.flags & HL_MEM_USERPTR) {
1116 device_addr = args->in.map_host.host_virt_addr;
1119 rc = get_paddr_from_handle(ctx, &args->in,
1123 memset(args, 0, sizeof(*args));
1124 args->out.device_virt_addr = device_addr;
1127 case HL_MEM_OP_UNMAP:
1132 dev_err(hdev->dev, "Unknown opcode for memory IOCTL\n");
1141 int hl_mem_ioctl(struct hl_fpriv *hpriv, void *data)
1143 union hl_mem_args *args = data;
1144 struct hl_device *hdev = hpriv->hdev;
1145 struct hl_ctx *ctx = hpriv->ctx;
1146 u64 device_addr = 0;
1150 if (hl_device_disabled_or_in_reset(hdev)) {
1151 dev_warn_ratelimited(hdev->dev,
1152 "Device is %s. Can't execute MEMORY IOCTL\n",
1153 atomic_read(&hdev->in_reset) ? "in_reset" : "disabled");
1157 if (!hdev->mmu_enable)
1158 return mem_ioctl_no_mmu(hpriv, args);
1160 switch (args->in.op) {
1161 case HL_MEM_OP_ALLOC:
1162 if (!hdev->dram_supports_virtual_memory) {
1163 dev_err(hdev->dev, "DRAM alloc is not supported\n");
1168 if (args->in.alloc.mem_size == 0) {
1170 "alloc size must be larger than 0\n");
1174 rc = alloc_device_memory(ctx, &args->in, &handle);
1176 memset(args, 0, sizeof(*args));
1177 args->out.handle = (__u64) handle;
1180 case HL_MEM_OP_FREE:
1181 rc = free_device_memory(ctx, args->in.free.handle);
1185 rc = map_device_va(ctx, &args->in, &device_addr);
1187 memset(args, 0, sizeof(*args));
1188 args->out.device_virt_addr = device_addr;
1191 case HL_MEM_OP_UNMAP:
1192 rc = unmap_device_va(ctx,
1193 args->in.unmap.device_virt_addr);
1197 dev_err(hdev->dev, "Unknown opcode for memory IOCTL\n");
1207 * hl_pin_host_memory - pins a chunk of host memory
1209 * @hdev : pointer to the habanalabs device structure
1210 * @addr : the user-space virtual address of the memory area
1211 * @size : the size of the memory area
1212 * @userptr : pointer to hl_userptr structure
1214 * This function does the following:
1215 * - Pins the physical pages
1216 * - Create a SG list from those pages
1218 int hl_pin_host_memory(struct hl_device *hdev, u64 addr, u64 size,
1219 struct hl_userptr *userptr)
1226 dev_err(hdev->dev, "size to pin is invalid - %llu\n", size);
1230 if (!access_ok((void __user *) (uintptr_t) addr, size)) {
1231 dev_err(hdev->dev, "user pointer is invalid - 0x%llx\n", addr);
1236 * If the combination of the address and size requested for this memory
1237 * region causes an integer overflow, return error.
1239 if (((addr + size) < addr) ||
1240 PAGE_ALIGN(addr + size) < (addr + size)) {
1242 "user pointer 0x%llx + %llu causes integer overflow\n",
1247 start = addr & PAGE_MASK;
1248 offset = addr & ~PAGE_MASK;
1249 end = PAGE_ALIGN(addr + size);
1250 npages = (end - start) >> PAGE_SHIFT;
1252 userptr->size = size;
1253 userptr->addr = addr;
1254 userptr->dma_mapped = false;
1255 INIT_LIST_HEAD(&userptr->job_node);
1257 userptr->vec = frame_vector_create(npages);
1258 if (!userptr->vec) {
1259 dev_err(hdev->dev, "Failed to create frame vector\n");
1263 rc = get_vaddr_frames(start, npages, FOLL_FORCE | FOLL_WRITE,
1268 "Failed to map host memory, user ptr probably wrong\n");
1270 goto destroy_framevec;
1275 if (frame_vector_to_pages(userptr->vec) < 0) {
1277 "Failed to translate frame vector to pages\n");
1282 userptr->sgt = kzalloc(sizeof(*userptr->sgt), GFP_ATOMIC);
1283 if (!userptr->sgt) {
1288 rc = sg_alloc_table_from_pages(userptr->sgt,
1289 frame_vector_pages(userptr->vec),
1290 npages, offset, size, GFP_ATOMIC);
1292 dev_err(hdev->dev, "failed to create SG table from pages\n");
1296 hl_debugfs_add_userptr(hdev, userptr);
1301 kfree(userptr->sgt);
1303 put_vaddr_frames(userptr->vec);
1305 frame_vector_destroy(userptr->vec);
1310 * hl_unpin_host_memory - unpins a chunk of host memory
1312 * @hdev : pointer to the habanalabs device structure
1313 * @userptr : pointer to hl_userptr structure
1315 * This function does the following:
1316 * - Unpins the physical pages related to the host memory
1317 * - Free the SG list
1319 int hl_unpin_host_memory(struct hl_device *hdev, struct hl_userptr *userptr)
1321 struct page **pages;
1323 hl_debugfs_remove_userptr(hdev, userptr);
1325 if (userptr->dma_mapped)
1326 hdev->asic_funcs->hl_dma_unmap_sg(hdev,
1328 userptr->sgt->nents,
1331 pages = frame_vector_pages(userptr->vec);
1332 if (!IS_ERR(pages)) {
1335 for (i = 0; i < frame_vector_count(userptr->vec); i++)
1336 set_page_dirty_lock(pages[i]);
1338 put_vaddr_frames(userptr->vec);
1339 frame_vector_destroy(userptr->vec);
1341 list_del(&userptr->job_node);
1343 sg_free_table(userptr->sgt);
1344 kfree(userptr->sgt);
1350 * hl_userptr_delete_list - clear userptr list
1352 * @hdev : pointer to the habanalabs device structure
1353 * @userptr_list : pointer to the list to clear
1355 * This function does the following:
1356 * - Iterates over the list and unpins the host memory and frees the userptr
1359 void hl_userptr_delete_list(struct hl_device *hdev,
1360 struct list_head *userptr_list)
1362 struct hl_userptr *userptr, *tmp;
1364 list_for_each_entry_safe(userptr, tmp, userptr_list, job_node) {
1365 hl_unpin_host_memory(hdev, userptr);
1369 INIT_LIST_HEAD(userptr_list);
1373 * hl_userptr_is_pinned - returns whether the given userptr is pinned
1375 * @hdev : pointer to the habanalabs device structure
1376 * @userptr_list : pointer to the list to clear
1377 * @userptr : pointer to userptr to check
1379 * This function does the following:
1380 * - Iterates over the list and checks if the given userptr is in it, means is
1381 * pinned. If so, returns true, otherwise returns false.
1383 bool hl_userptr_is_pinned(struct hl_device *hdev, u64 addr,
1384 u32 size, struct list_head *userptr_list,
1385 struct hl_userptr **userptr)
1387 list_for_each_entry((*userptr), userptr_list, job_node) {
1388 if ((addr == (*userptr)->addr) && (size == (*userptr)->size))
1396 * hl_va_range_init - initialize virtual addresses range
1398 * @hdev : pointer to the habanalabs device structure
1399 * @va_range : pointer to the range to initialize
1400 * @start : range start address
1401 * @end : range end address
1403 * This function does the following:
1404 * - Initializes the virtual addresses list of the given range with the given
1407 static int hl_va_range_init(struct hl_device *hdev,
1408 struct hl_va_range *va_range, u64 start, u64 end)
1412 INIT_LIST_HEAD(&va_range->list);
1414 /* PAGE_SIZE alignment */
1416 if (start & (PAGE_SIZE - 1)) {
1421 if (end & (PAGE_SIZE - 1))
1425 dev_err(hdev->dev, "too small vm range for va list\n");
1429 rc = add_va_block(hdev, va_range, start, end);
1432 dev_err(hdev->dev, "Failed to init host va list\n");
1436 va_range->start_addr = start;
1437 va_range->end_addr = end;
1443 * hl_vm_ctx_init_with_ranges - initialize virtual memory for context
1445 * @ctx : pointer to the habanalabs context structure
1446 * @host_range_start : host virtual addresses range start
1447 * @host_range_end : host virtual addresses range end
1448 * @dram_range_start : dram virtual addresses range start
1449 * @dram_range_end : dram virtual addresses range end
1451 * This function initializes the following:
1453 * - Virtual address to area descriptor hashtable
1454 * - Virtual block list of available virtual memory
1456 static int hl_vm_ctx_init_with_ranges(struct hl_ctx *ctx, u64 host_range_start,
1457 u64 host_range_end, u64 dram_range_start,
1460 struct hl_device *hdev = ctx->hdev;
1463 rc = hl_mmu_ctx_init(ctx);
1465 dev_err(hdev->dev, "failed to init context %d\n", ctx->asid);
1469 mutex_init(&ctx->mem_hash_lock);
1470 hash_init(ctx->mem_hash);
1472 mutex_init(&ctx->host_va_range.lock);
1474 rc = hl_va_range_init(hdev, &ctx->host_va_range, host_range_start,
1477 dev_err(hdev->dev, "failed to init host vm range\n");
1481 mutex_init(&ctx->dram_va_range.lock);
1483 rc = hl_va_range_init(hdev, &ctx->dram_va_range, dram_range_start,
1486 dev_err(hdev->dev, "failed to init dram vm range\n");
1490 hl_debugfs_add_ctx_mem_hash(hdev, ctx);
1495 mutex_destroy(&ctx->dram_va_range.lock);
1497 mutex_lock(&ctx->host_va_range.lock);
1498 clear_va_list_locked(hdev, &ctx->host_va_range.list);
1499 mutex_unlock(&ctx->host_va_range.lock);
1501 mutex_destroy(&ctx->host_va_range.lock);
1502 mutex_destroy(&ctx->mem_hash_lock);
1503 hl_mmu_ctx_fini(ctx);
1508 int hl_vm_ctx_init(struct hl_ctx *ctx)
1510 struct asic_fixed_properties *prop = &ctx->hdev->asic_prop;
1511 u64 host_range_start, host_range_end, dram_range_start,
1514 atomic64_set(&ctx->dram_phys_mem, 0);
1517 * - If MMU is enabled, init the ranges as usual.
1518 * - If MMU is disabled, in case of host mapping, the returned address
1520 * In case of DRAM mapping, the returned address is the physical
1521 * address of the memory related to the given handle.
1523 if (ctx->hdev->mmu_enable) {
1524 dram_range_start = prop->va_space_dram_start_address;
1525 dram_range_end = prop->va_space_dram_end_address;
1526 host_range_start = prop->va_space_host_start_address;
1527 host_range_end = prop->va_space_host_end_address;
1529 dram_range_start = prop->dram_user_base_address;
1530 dram_range_end = prop->dram_end_address;
1531 host_range_start = prop->dram_user_base_address;
1532 host_range_end = prop->dram_end_address;
1535 return hl_vm_ctx_init_with_ranges(ctx, host_range_start, host_range_end,
1536 dram_range_start, dram_range_end);
1540 * hl_va_range_fini - clear a virtual addresses range
1542 * @hdev : pointer to the habanalabs structure
1543 * va_range : pointer to virtual addresses range
1545 * This function initializes the following:
1546 * - Checks that the given range contains the whole initial range
1547 * - Frees the virtual addresses block list and its lock
1549 static void hl_va_range_fini(struct hl_device *hdev,
1550 struct hl_va_range *va_range)
1552 struct hl_vm_va_block *va_block;
1554 if (list_empty(&va_range->list)) {
1556 "va list should not be empty on cleanup!\n");
1560 if (!list_is_singular(&va_range->list)) {
1562 "va list should not contain multiple blocks on cleanup!\n");
1566 va_block = list_first_entry(&va_range->list, typeof(*va_block), node);
1568 if (va_block->start != va_range->start_addr ||
1569 va_block->end != va_range->end_addr) {
1571 "wrong va block on cleanup, from 0x%llx to 0x%llx\n",
1572 va_block->start, va_block->end);
1577 mutex_lock(&va_range->lock);
1578 clear_va_list_locked(hdev, &va_range->list);
1579 mutex_unlock(&va_range->lock);
1582 mutex_destroy(&va_range->lock);
1586 * hl_vm_ctx_fini - virtual memory teardown of context
1588 * @ctx : pointer to the habanalabs context structure
1590 * This function perform teardown the following:
1591 * - Virtual block list of available virtual memory
1592 * - Virtual address to area descriptor hashtable
1595 * In addition this function does the following:
1596 * - Unmaps the existing hashtable nodes if the hashtable is not empty. The
1597 * hashtable should be empty as no valid mappings should exist at this
1599 * - Frees any existing physical page list from the idr which relates to the
1600 * current context asid.
1601 * - This function checks the virtual block list for correctness. At this point
1602 * the list should contain one element which describes the whole virtual
1603 * memory range of the context. Otherwise, a warning is printed.
1605 void hl_vm_ctx_fini(struct hl_ctx *ctx)
1607 struct hl_device *hdev = ctx->hdev;
1608 struct hl_vm *vm = &hdev->vm;
1609 struct hl_vm_phys_pg_pack *phys_pg_list;
1610 struct hl_vm_hash_node *hnode;
1611 struct hlist_node *tmp_node;
1614 hl_debugfs_remove_ctx_mem_hash(hdev, ctx);
1616 if (!hash_empty(ctx->mem_hash))
1617 dev_notice(hdev->dev, "ctx is freed while it has va in use\n");
1619 hash_for_each_safe(ctx->mem_hash, i, tmp_node, hnode, node) {
1621 "hl_mem_hash_node of vaddr 0x%llx of asid %d is still alive\n",
1622 hnode->vaddr, ctx->asid);
1623 unmap_device_va(ctx, hnode->vaddr);
1626 spin_lock(&vm->idr_lock);
1627 idr_for_each_entry(&vm->phys_pg_pack_handles, phys_pg_list, i)
1628 if (phys_pg_list->asid == ctx->asid) {
1630 "page list 0x%p of asid %d is still alive\n",
1631 phys_pg_list, ctx->asid);
1632 atomic64_sub(phys_pg_list->total_size,
1633 &hdev->dram_used_mem);
1634 free_phys_pg_pack(hdev, phys_pg_list);
1635 idr_remove(&vm->phys_pg_pack_handles, i);
1637 spin_unlock(&vm->idr_lock);
1639 hl_va_range_fini(hdev, &ctx->dram_va_range);
1640 hl_va_range_fini(hdev, &ctx->host_va_range);
1642 mutex_destroy(&ctx->mem_hash_lock);
1643 hl_mmu_ctx_fini(ctx);
1647 * hl_vm_init - initialize virtual memory module
1649 * @hdev : pointer to the habanalabs device structure
1651 * This function initializes the following:
1653 * - DRAM physical pages pool of 2MB
1654 * - Idr for device memory allocation handles
1656 int hl_vm_init(struct hl_device *hdev)
1658 struct asic_fixed_properties *prop = &hdev->asic_prop;
1659 struct hl_vm *vm = &hdev->vm;
1662 vm->dram_pg_pool = gen_pool_create(__ffs(prop->dram_page_size), -1);
1663 if (!vm->dram_pg_pool) {
1664 dev_err(hdev->dev, "Failed to create dram page pool\n");
1668 kref_init(&vm->dram_pg_pool_refcount);
1670 rc = gen_pool_add(vm->dram_pg_pool, prop->dram_user_base_address,
1671 prop->dram_end_address - prop->dram_user_base_address,
1676 "Failed to add memory to dram page pool %d\n", rc);
1680 spin_lock_init(&vm->idr_lock);
1681 idr_init(&vm->phys_pg_pack_handles);
1683 atomic64_set(&hdev->dram_used_mem, 0);
1685 vm->init_done = true;
1690 gen_pool_destroy(vm->dram_pg_pool);
1696 * hl_vm_fini - virtual memory module teardown
1698 * @hdev : pointer to the habanalabs device structure
1700 * This function perform teardown to the following:
1701 * - Idr for device memory allocation handles
1702 * - DRAM physical pages pool of 2MB
1705 void hl_vm_fini(struct hl_device *hdev)
1707 struct hl_vm *vm = &hdev->vm;
1713 * At this point all the contexts should be freed and hence no DRAM
1714 * memory should be in use. Hence the DRAM pool should be freed here.
1716 if (kref_put(&vm->dram_pg_pool_refcount, dram_pg_pool_do_release) != 1)
1717 dev_warn(hdev->dev, "dram_pg_pool was not destroyed on %s\n",
1720 vm->init_done = false;