1 /*
2  * Copyright (c) 2005 Topspin Communications.  All rights reserved.
3  * Copyright (c) 2005 Mellanox Technologies. All rights reserved.
4  * Copyright (c) 2013 Cisco Systems.  All rights reserved.
5  *
6  * This software is available to you under a choice of one of two
7  * licenses.  You may choose to be licensed under the terms of the GNU
8  * General Public License (GPL) Version 2, available from the file
9  * COPYING in the main directory of this source tree, or the
10  * BSD license below:
11  *
12  *     Redistribution and use in source and binary forms, with or
13  *     without modification, are permitted provided that the following
14  *     conditions are met:
15  *
16  *      - Redistributions of source code must retain the above
17  *        copyright notice, this list of conditions and the following
18  *        disclaimer.
19  *
20  *      - Redistributions in binary form must reproduce the above
21  *        copyright notice, this list of conditions and the following
22  *        disclaimer in the documentation and/or other materials
23  *        provided with the distribution.
24  *
25  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
29  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
30  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
31  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32  * SOFTWARE.
33  */
34 
35 #include <linux/mm.h>
36 #include <linux/dma-mapping.h>
37 #include <linux/sched/signal.h>
38 #include <linux/sched/mm.h>
39 #include <linux/hugetlb.h>
40 #include <linux/iommu.h>
41 #include <linux/workqueue.h>
42 #include <linux/list.h>
43 #include <rdma/ib_verbs.h>
44 
45 #include "usnic_log.h"
46 #include "usnic_uiom.h"
47 #include "usnic_uiom_interval_tree.h"
48 
49 #define USNIC_UIOM_PAGE_CHUNK						\
50 	((PAGE_SIZE - offsetof(struct usnic_uiom_chunk, page_list))	/\
51 	((void *) &((struct usnic_uiom_chunk *) 0)->page_list[1] -	\
52 	(void *) &((struct usnic_uiom_chunk *) 0)->page_list[0]))
53 
54 static int usnic_uiom_dma_fault(struct iommu_domain *domain,
55 				struct device *dev,
56 				unsigned long iova, int flags,
57 				void *token)
58 {
59 	usnic_err("Device %s iommu fault domain 0x%pK va 0x%lx flags 0x%x\n",
60 		dev_name(dev),
61 		domain, iova, flags);
62 	return -ENOSYS;
63 }
64 
65 static void usnic_uiom_put_pages(struct list_head *chunk_list, int dirty)
66 {
67 	struct usnic_uiom_chunk *chunk, *tmp;
68 	struct page *page;
69 	struct scatterlist *sg;
70 	int i;
71 	dma_addr_t pa;
72 
73 	list_for_each_entry_safe(chunk, tmp, chunk_list, list) {
74 		for_each_sg(chunk->page_list, sg, chunk->nents, i) {
75 			page = sg_page(sg);
76 			pa = sg_phys(sg);
77 			unpin_user_pages_dirty_lock(&page, 1, dirty);
78 			usnic_dbg("pa: %pa\n", &pa);
79 		}
80 		kfree(chunk);
81 	}
82 }
83 
84 static int usnic_uiom_get_pages(unsigned long addr, size_t size, int writable,
85 				int dmasync, struct usnic_uiom_reg *uiomr)
86 {
87 	struct list_head *chunk_list = &uiomr->chunk_list;
88 	struct page **page_list;
89 	struct scatterlist *sg;
90 	struct usnic_uiom_chunk *chunk;
91 	unsigned long locked;
92 	unsigned long lock_limit;
93 	unsigned long cur_base;
94 	unsigned long npages;
95 	int ret;
96 	int off;
97 	int i;
98 	dma_addr_t pa;
99 	unsigned int gup_flags;
100 	struct mm_struct *mm;
101 
102 	/*
103 	 * If the combination of the addr and size requested for this memory
104 	 * region causes an integer overflow, return error.
105 	 */
106 	if (((addr + size) < addr) || PAGE_ALIGN(addr + size) < (addr + size))
107 		return -EINVAL;
108 
109 	if (!size)
110 		return -EINVAL;
111 
112 	if (!can_do_mlock())
113 		return -EPERM;
114 
115 	INIT_LIST_HEAD(chunk_list);
116 
117 	page_list = (struct page **) __get_free_page(GFP_KERNEL);
118 	if (!page_list)
119 		return -ENOMEM;
120 
121 	npages = PAGE_ALIGN(size + (addr & ~PAGE_MASK)) >> PAGE_SHIFT;
122 
123 	uiomr->owning_mm = mm = current->mm;
124 	mmap_read_lock(mm);
125 
126 	locked = atomic64_add_return(npages, &current->mm->pinned_vm);
127 	lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
128 
129 	if ((locked > lock_limit) && !capable(CAP_IPC_LOCK)) {
130 		ret = -ENOMEM;
131 		goto out;
132 	}
133 
134 	gup_flags = FOLL_WRITE;
135 	gup_flags |= (writable) ? 0 : FOLL_FORCE;
136 	cur_base = addr & PAGE_MASK;
137 	ret = 0;
138 
139 	while (npages) {
140 		ret = pin_user_pages(cur_base,
141 				     min_t(unsigned long, npages,
142 				     PAGE_SIZE / sizeof(struct page *)),
143 				     gup_flags | FOLL_LONGTERM,
144 				     page_list, NULL);
145 
146 		if (ret < 0)
147 			goto out;
148 
149 		npages -= ret;
150 		off = 0;
151 
152 		while (ret) {
153 			chunk = kmalloc(struct_size(chunk, page_list,
154 					min_t(int, ret, USNIC_UIOM_PAGE_CHUNK)),
155 					GFP_KERNEL);
156 			if (!chunk) {
157 				ret = -ENOMEM;
158 				goto out;
159 			}
160 
161 			chunk->nents = min_t(int, ret, USNIC_UIOM_PAGE_CHUNK);
162 			sg_init_table(chunk->page_list, chunk->nents);
163 			for_each_sg(chunk->page_list, sg, chunk->nents, i) {
164 				sg_set_page(sg, page_list[i + off],
165 						PAGE_SIZE, 0);
166 				pa = sg_phys(sg);
167 				usnic_dbg("va: 0x%lx pa: %pa\n",
168 						cur_base + i*PAGE_SIZE, &pa);
169 			}
170 			cur_base += chunk->nents * PAGE_SIZE;
171 			ret -= chunk->nents;
172 			off += chunk->nents;
173 			list_add_tail(&chunk->list, chunk_list);
174 		}
175 
176 		ret = 0;
177 	}
178 
179 out:
180 	if (ret < 0) {
181 		usnic_uiom_put_pages(chunk_list, 0);
182 		atomic64_sub(npages, &current->mm->pinned_vm);
183 	} else
184 		mmgrab(uiomr->owning_mm);
185 
186 	mmap_read_unlock(mm);
187 	free_page((unsigned long) page_list);
188 	return ret;
189 }
190 
191 static void usnic_uiom_unmap_sorted_intervals(struct list_head *intervals,
192 						struct usnic_uiom_pd *pd)
193 {
194 	struct usnic_uiom_interval_node *interval, *tmp;
195 	long unsigned va, size;
196 
197 	list_for_each_entry_safe(interval, tmp, intervals, link) {
198 		va = interval->start << PAGE_SHIFT;
199 		size = ((interval->last - interval->start) + 1) << PAGE_SHIFT;
200 		while (size > 0) {
201 			/* Workaround for RH 970401 */
202 			usnic_dbg("va 0x%lx size 0x%lx", va, PAGE_SIZE);
203 			iommu_unmap(pd->domain, va, PAGE_SIZE);
204 			va += PAGE_SIZE;
205 			size -= PAGE_SIZE;
206 		}
207 	}
208 }
209 
210 static void __usnic_uiom_reg_release(struct usnic_uiom_pd *pd,
211 					struct usnic_uiom_reg *uiomr,
212 					int dirty)
213 {
214 	int npages;
215 	unsigned long vpn_start, vpn_last;
216 	struct usnic_uiom_interval_node *interval, *tmp;
217 	int writable = 0;
218 	LIST_HEAD(rm_intervals);
219 
220 	npages = PAGE_ALIGN(uiomr->length + uiomr->offset) >> PAGE_SHIFT;
221 	vpn_start = (uiomr->va & PAGE_MASK) >> PAGE_SHIFT;
222 	vpn_last = vpn_start + npages - 1;
223 
224 	spin_lock(&pd->lock);
225 	usnic_uiom_remove_interval(&pd->root, vpn_start,
226 					vpn_last, &rm_intervals);
227 	usnic_uiom_unmap_sorted_intervals(&rm_intervals, pd);
228 
229 	list_for_each_entry_safe(interval, tmp, &rm_intervals, link) {
230 		if (interval->flags & IOMMU_WRITE)
231 			writable = 1;
232 		list_del(&interval->link);
233 		kfree(interval);
234 	}
235 
236 	usnic_uiom_put_pages(&uiomr->chunk_list, dirty & writable);
237 	spin_unlock(&pd->lock);
238 }
239 
240 static int usnic_uiom_map_sorted_intervals(struct list_head *intervals,
241 						struct usnic_uiom_reg *uiomr)
242 {
243 	int i, err;
244 	size_t size;
245 	struct usnic_uiom_chunk *chunk;
246 	struct usnic_uiom_interval_node *interval_node;
247 	dma_addr_t pa;
248 	dma_addr_t pa_start = 0;
249 	dma_addr_t pa_end = 0;
250 	long int va_start = -EINVAL;
251 	struct usnic_uiom_pd *pd = uiomr->pd;
252 	long int va = uiomr->va & PAGE_MASK;
253 	int flags = IOMMU_READ | IOMMU_CACHE;
254 
255 	flags |= (uiomr->writable) ? IOMMU_WRITE : 0;
256 	chunk = list_first_entry(&uiomr->chunk_list, struct usnic_uiom_chunk,
257 									list);
258 	list_for_each_entry(interval_node, intervals, link) {
259 iter_chunk:
260 		for (i = 0; i < chunk->nents; i++, va += PAGE_SIZE) {
261 			pa = sg_phys(&chunk->page_list[i]);
262 			if ((va >> PAGE_SHIFT) < interval_node->start)
263 				continue;
264 
265 			if ((va >> PAGE_SHIFT) == interval_node->start) {
266 				/* First page of the interval */
267 				va_start = va;
268 				pa_start = pa;
269 				pa_end = pa;
270 			}
271 
272 			WARN_ON(va_start == -EINVAL);
273 
274 			if ((pa_end + PAGE_SIZE != pa) &&
275 					(pa != pa_start)) {
276 				/* PAs are not contiguous */
277 				size = pa_end - pa_start + PAGE_SIZE;
278 				usnic_dbg("va 0x%lx pa %pa size 0x%zx flags 0x%x",
279 					va_start, &pa_start, size, flags);
280 				err = iommu_map(pd->domain, va_start, pa_start,
281 							size, flags);
282 				if (err) {
283 					usnic_err("Failed to map va 0x%lx pa %pa size 0x%zx with err %d\n",
284 						va_start, &pa_start, size, err);
285 					goto err_out;
286 				}
287 				va_start = va;
288 				pa_start = pa;
289 				pa_end = pa;
290 			}
291 
292 			if ((va >> PAGE_SHIFT) == interval_node->last) {
293 				/* Last page of the interval */
294 				size = pa - pa_start + PAGE_SIZE;
295 				usnic_dbg("va 0x%lx pa %pa size 0x%zx flags 0x%x\n",
296 					va_start, &pa_start, size, flags);
297 				err = iommu_map(pd->domain, va_start, pa_start,
298 						size, flags);
299 				if (err) {
300 					usnic_err("Failed to map va 0x%lx pa %pa size 0x%zx with err %d\n",
301 						va_start, &pa_start, size, err);
302 					goto err_out;
303 				}
304 				break;
305 			}
306 
307 			if (pa != pa_start)
308 				pa_end += PAGE_SIZE;
309 		}
310 
311 		if (i == chunk->nents) {
312 			/*
313 			 * Hit last entry of the chunk,
314 			 * hence advance to next chunk
315 			 */
316 			chunk = list_first_entry(&chunk->list,
317 							struct usnic_uiom_chunk,
318 							list);
319 			goto iter_chunk;
320 		}
321 	}
322 
323 	return 0;
324 
325 err_out:
326 	usnic_uiom_unmap_sorted_intervals(intervals, pd);
327 	return err;
328 }
329 
330 struct usnic_uiom_reg *usnic_uiom_reg_get(struct usnic_uiom_pd *pd,
331 						unsigned long addr, size_t size,
332 						int writable, int dmasync)
333 {
334 	struct usnic_uiom_reg *uiomr;
335 	unsigned long va_base, vpn_start, vpn_last;
336 	unsigned long npages;
337 	int offset, err;
338 	LIST_HEAD(sorted_diff_intervals);
339 
340 	/*
341 	 * Intel IOMMU map throws an error if a translation entry is
342 	 * changed from read to write.  This module may not unmap
343 	 * and then remap the entry after fixing the permission
344 	 * b/c this open up a small windows where hw DMA may page fault
345 	 * Hence, make all entries to be writable.
346 	 */
347 	writable = 1;
348 
349 	va_base = addr & PAGE_MASK;
350 	offset = addr & ~PAGE_MASK;
351 	npages = PAGE_ALIGN(size + offset) >> PAGE_SHIFT;
352 	vpn_start = (addr & PAGE_MASK) >> PAGE_SHIFT;
353 	vpn_last = vpn_start + npages - 1;
354 
355 	uiomr = kmalloc(sizeof(*uiomr), GFP_KERNEL);
356 	if (!uiomr)
357 		return ERR_PTR(-ENOMEM);
358 
359 	uiomr->va = va_base;
360 	uiomr->offset = offset;
361 	uiomr->length = size;
362 	uiomr->writable = writable;
363 	uiomr->pd = pd;
364 
365 	err = usnic_uiom_get_pages(addr, size, writable, dmasync,
366 				   uiomr);
367 	if (err) {
368 		usnic_err("Failed get_pages vpn [0x%lx,0x%lx] err %d\n",
369 				vpn_start, vpn_last, err);
370 		goto out_free_uiomr;
371 	}
372 
373 	spin_lock(&pd->lock);
374 	err = usnic_uiom_get_intervals_diff(vpn_start, vpn_last,
375 						(writable) ? IOMMU_WRITE : 0,
376 						IOMMU_WRITE,
377 						&pd->root,
378 						&sorted_diff_intervals);
379 	if (err) {
380 		usnic_err("Failed disjoint interval vpn [0x%lx,0x%lx] err %d\n",
381 						vpn_start, vpn_last, err);
382 		goto out_put_pages;
383 	}
384 
385 	err = usnic_uiom_map_sorted_intervals(&sorted_diff_intervals, uiomr);
386 	if (err) {
387 		usnic_err("Failed map interval vpn [0x%lx,0x%lx] err %d\n",
388 						vpn_start, vpn_last, err);
389 		goto out_put_intervals;
390 
391 	}
392 
393 	err = usnic_uiom_insert_interval(&pd->root, vpn_start, vpn_last,
394 					(writable) ? IOMMU_WRITE : 0);
395 	if (err) {
396 		usnic_err("Failed insert interval vpn [0x%lx,0x%lx] err %d\n",
397 						vpn_start, vpn_last, err);
398 		goto out_unmap_intervals;
399 	}
400 
401 	usnic_uiom_put_interval_set(&sorted_diff_intervals);
402 	spin_unlock(&pd->lock);
403 
404 	return uiomr;
405 
406 out_unmap_intervals:
407 	usnic_uiom_unmap_sorted_intervals(&sorted_diff_intervals, pd);
408 out_put_intervals:
409 	usnic_uiom_put_interval_set(&sorted_diff_intervals);
410 out_put_pages:
411 	usnic_uiom_put_pages(&uiomr->chunk_list, 0);
412 	spin_unlock(&pd->lock);
413 	mmdrop(uiomr->owning_mm);
414 out_free_uiomr:
415 	kfree(uiomr);
416 	return ERR_PTR(err);
417 }
418 
419 static void __usnic_uiom_release_tail(struct usnic_uiom_reg *uiomr)
420 {
421 	mmdrop(uiomr->owning_mm);
422 	kfree(uiomr);
423 }
424 
425 static inline size_t usnic_uiom_num_pages(struct usnic_uiom_reg *uiomr)
426 {
427 	return PAGE_ALIGN(uiomr->length + uiomr->offset) >> PAGE_SHIFT;
428 }
429 
430 void usnic_uiom_reg_release(struct usnic_uiom_reg *uiomr)
431 {
432 	__usnic_uiom_reg_release(uiomr->pd, uiomr, 1);
433 
434 	atomic64_sub(usnic_uiom_num_pages(uiomr), &uiomr->owning_mm->pinned_vm);
435 	__usnic_uiom_release_tail(uiomr);
436 }
437 
438 struct usnic_uiom_pd *usnic_uiom_alloc_pd(struct device *dev)
439 {
440 	struct usnic_uiom_pd *pd;
441 	void *domain;
442 
443 	pd = kzalloc(sizeof(*pd), GFP_KERNEL);
444 	if (!pd)
445 		return ERR_PTR(-ENOMEM);
446 
447 	pd->domain = domain = iommu_domain_alloc(dev->bus);
448 	if (!domain) {
449 		usnic_err("Failed to allocate IOMMU domain");
450 		kfree(pd);
451 		return ERR_PTR(-ENOMEM);
452 	}
453 
454 	iommu_set_fault_handler(pd->domain, usnic_uiom_dma_fault, NULL);
455 
456 	spin_lock_init(&pd->lock);
457 	INIT_LIST_HEAD(&pd->devs);
458 
459 	return pd;
460 }
461 
462 void usnic_uiom_dealloc_pd(struct usnic_uiom_pd *pd)
463 {
464 	iommu_domain_free(pd->domain);
465 	kfree(pd);
466 }
467 
468 int usnic_uiom_attach_dev_to_pd(struct usnic_uiom_pd *pd, struct device *dev)
469 {
470 	struct usnic_uiom_dev *uiom_dev;
471 	int err;
472 
473 	uiom_dev = kzalloc(sizeof(*uiom_dev), GFP_ATOMIC);
474 	if (!uiom_dev)
475 		return -ENOMEM;
476 	uiom_dev->dev = dev;
477 
478 	err = iommu_attach_device(pd->domain, dev);
479 	if (err)
480 		goto out_free_dev;
481 
482 	if (!device_iommu_capable(dev, IOMMU_CAP_CACHE_COHERENCY)) {
483 		usnic_err("IOMMU of %s does not support cache coherency\n",
484 				dev_name(dev));
485 		err = -EINVAL;
486 		goto out_detach_device;
487 	}
488 
489 	spin_lock(&pd->lock);
490 	list_add_tail(&uiom_dev->link, &pd->devs);
491 	pd->dev_cnt++;
492 	spin_unlock(&pd->lock);
493 
494 	return 0;
495 
496 out_detach_device:
497 	iommu_detach_device(pd->domain, dev);
498 out_free_dev:
499 	kfree(uiom_dev);
500 	return err;
501 }
502 
503 void usnic_uiom_detach_dev_from_pd(struct usnic_uiom_pd *pd, struct device *dev)
504 {
505 	struct usnic_uiom_dev *uiom_dev;
506 	int found = 0;
507 
508 	spin_lock(&pd->lock);
509 	list_for_each_entry(uiom_dev, &pd->devs, link) {
510 		if (uiom_dev->dev == dev) {
511 			found = 1;
512 			break;
513 		}
514 	}
515 
516 	if (!found) {
517 		usnic_err("Unable to free dev %s - not found\n",
518 				dev_name(dev));
519 		spin_unlock(&pd->lock);
520 		return;
521 	}
522 
523 	list_del(&uiom_dev->link);
524 	pd->dev_cnt--;
525 	spin_unlock(&pd->lock);
526 
527 	return iommu_detach_device(pd->domain, dev);
528 }
529 
530 struct device **usnic_uiom_get_dev_list(struct usnic_uiom_pd *pd)
531 {
532 	struct usnic_uiom_dev *uiom_dev;
533 	struct device **devs;
534 	int i = 0;
535 
536 	spin_lock(&pd->lock);
537 	devs = kcalloc(pd->dev_cnt + 1, sizeof(*devs), GFP_ATOMIC);
538 	if (!devs) {
539 		devs = ERR_PTR(-ENOMEM);
540 		goto out;
541 	}
542 
543 	list_for_each_entry(uiom_dev, &pd->devs, link) {
544 		devs[i++] = uiom_dev->dev;
545 	}
546 out:
547 	spin_unlock(&pd->lock);
548 	return devs;
549 }
550 
551 void usnic_uiom_free_dev_list(struct device **devs)
552 {
553 	kfree(devs);
554 }
555