Home | History | Annotate | Line # | Download | only in amdkfd
      1 /*	$NetBSD: kfd_events.c,v 1.3 2021/12/18 23:44:59 riastradh Exp $	*/
      2 
      3 /*
      4  * Copyright 2014 Advanced Micro Devices, Inc.
      5  *
      6  * Permission is hereby granted, free of charge, to any person obtaining a
      7  * copy of this software and associated documentation files (the "Software"),
      8  * to deal in the Software without restriction, including without limitation
      9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
     10  * and/or sell copies of the Software, and to permit persons to whom the
     11  * Software is furnished to do so, subject to the following conditions:
     12  *
     13  * The above copyright notice and this permission notice shall be included in
     14  * all copies or substantial portions of the Software.
     15  *
     16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
     19  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
     20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
     21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
     22  * OTHER DEALINGS IN THE SOFTWARE.
     23  */
     24 
     25 #include <sys/cdefs.h>
     26 __KERNEL_RCSID(0, "$NetBSD: kfd_events.c,v 1.3 2021/12/18 23:44:59 riastradh Exp $");
     27 
     28 #include <linux/mm_types.h>
     29 #include <linux/slab.h>
     30 #include <linux/types.h>
     31 #include <linux/sched/signal.h>
     32 #include <linux/sched/mm.h>
     33 #include <linux/uaccess.h>
     34 #include <linux/mman.h>
     35 #include <linux/memory.h>
     36 #include "kfd_priv.h"
     37 #include "kfd_events.h"
     38 #include "kfd_iommu.h"
     39 #include <linux/device.h>
     40 
     41 /*
     42  * Wrapper around wait_queue_entry_t
     43  */
     44 struct kfd_event_waiter {
     45 	wait_queue_entry_t wait;
     46 	struct kfd_event *event; /* Event to wait for */
     47 	bool activated;		 /* Becomes true when event is signaled */
     48 };
     49 
     50 /*
     51  * Each signal event needs a 64-bit signal slot where the signaler will write
     52  * a 1 before sending an interrupt. (This is needed because some interrupts
     53  * do not contain enough spare data bits to identify an event.)
     54  * We get whole pages and map them to the process VA.
     55  * Individual signal events use their event_id as slot index.
     56  */
     57 struct kfd_signal_page {
     58 	uint64_t *kernel_address;
     59 	uint64_t __user *user_address;
     60 	bool need_to_free_pages;
     61 };
     62 
     63 
     64 static uint64_t *page_slots(struct kfd_signal_page *page)
     65 {
     66 	return page->kernel_address;
     67 }
     68 
     69 static struct kfd_signal_page *allocate_signal_page(struct kfd_process *p)
     70 {
     71 	void *backing_store;
     72 	struct kfd_signal_page *page;
     73 
     74 	page = kzalloc(sizeof(*page), GFP_KERNEL);
     75 	if (!page)
     76 		return NULL;
     77 
     78 	backing_store = (void *) __get_free_pages(GFP_KERNEL,
     79 					get_order(KFD_SIGNAL_EVENT_LIMIT * 8));
     80 	if (!backing_store)
     81 		goto fail_alloc_signal_store;
     82 
     83 	/* Initialize all events to unsignaled */
     84 	memset(backing_store, (uint8_t) UNSIGNALED_EVENT_SLOT,
     85 	       KFD_SIGNAL_EVENT_LIMIT * 8);
     86 
     87 	page->kernel_address = backing_store;
     88 	page->need_to_free_pages = true;
     89 	pr_debug("Allocated new event signal page at %p, for process %p\n",
     90 			page, p);
     91 
     92 	return page;
     93 
     94 fail_alloc_signal_store:
     95 	kfree(page);
     96 	return NULL;
     97 }
     98 
     99 static int allocate_event_notification_slot(struct kfd_process *p,
    100 					    struct kfd_event *ev)
    101 {
    102 	int id;
    103 
    104 	if (!p->signal_page) {
    105 		p->signal_page = allocate_signal_page(p);
    106 		if (!p->signal_page)
    107 			return -ENOMEM;
    108 		/* Oldest user mode expects 256 event slots */
    109 		p->signal_mapped_size = 256*8;
    110 	}
    111 
    112 	/*
    113 	 * Compatibility with old user mode: Only use signal slots
    114 	 * user mode has mapped, may be less than
    115 	 * KFD_SIGNAL_EVENT_LIMIT. This also allows future increase
    116 	 * of the event limit without breaking user mode.
    117 	 */
    118 	id = idr_alloc(&p->event_idr, ev, 0, p->signal_mapped_size / 8,
    119 		       GFP_KERNEL);
    120 	if (id < 0)
    121 		return id;
    122 
    123 	ev->event_id = id;
    124 	page_slots(p->signal_page)[id] = UNSIGNALED_EVENT_SLOT;
    125 
    126 	return 0;
    127 }
    128 
    129 /*
    130  * Assumes that p->event_mutex is held and of course that p is not going
    131  * away (current or locked).
    132  */
    133 static struct kfd_event *lookup_event_by_id(struct kfd_process *p, uint32_t id)
    134 {
    135 	return idr_find(&p->event_idr, id);
    136 }
    137 
    138 /**
    139  * lookup_signaled_event_by_partial_id - Lookup signaled event from partial ID
    140  * @p:     Pointer to struct kfd_process
    141  * @id:    ID to look up
    142  * @bits:  Number of valid bits in @id
    143  *
    144  * Finds the first signaled event with a matching partial ID. If no
    145  * matching signaled event is found, returns NULL. In that case the
    146  * caller should assume that the partial ID is invalid and do an
    147  * exhaustive search of all siglaned events.
    148  *
    149  * If multiple events with the same partial ID signal at the same
    150  * time, they will be found one interrupt at a time, not necessarily
    151  * in the same order the interrupts occurred. As long as the number of
    152  * interrupts is correct, all signaled events will be seen by the
    153  * driver.
    154  */
    155 static struct kfd_event *lookup_signaled_event_by_partial_id(
    156 	struct kfd_process *p, uint32_t id, uint32_t bits)
    157 {
    158 	struct kfd_event *ev;
    159 
    160 	if (!p->signal_page || id >= KFD_SIGNAL_EVENT_LIMIT)
    161 		return NULL;
    162 
    163 	/* Fast path for the common case that @id is not a partial ID
    164 	 * and we only need a single lookup.
    165 	 */
    166 	if (bits > 31 || (1U << bits) >= KFD_SIGNAL_EVENT_LIMIT) {
    167 		if (page_slots(p->signal_page)[id] == UNSIGNALED_EVENT_SLOT)
    168 			return NULL;
    169 
    170 		return idr_find(&p->event_idr, id);
    171 	}
    172 
    173 	/* General case for partial IDs: Iterate over all matching IDs
    174 	 * and find the first one that has signaled.
    175 	 */
    176 	for (ev = NULL; id < KFD_SIGNAL_EVENT_LIMIT && !ev; id += 1U << bits) {
    177 		if (page_slots(p->signal_page)[id] == UNSIGNALED_EVENT_SLOT)
    178 			continue;
    179 
    180 		ev = idr_find(&p->event_idr, id);
    181 	}
    182 
    183 	return ev;
    184 }
    185 
    186 static int create_signal_event(struct file *devkfd,
    187 				struct kfd_process *p,
    188 				struct kfd_event *ev)
    189 {
    190 	int ret;
    191 
    192 	if (p->signal_mapped_size &&
    193 	    p->signal_event_count == p->signal_mapped_size / 8) {
    194 		if (!p->signal_event_limit_reached) {
    195 			pr_warn("Signal event wasn't created because limit was reached\n");
    196 			p->signal_event_limit_reached = true;
    197 		}
    198 		return -ENOSPC;
    199 	}
    200 
    201 	ret = allocate_event_notification_slot(p, ev);
    202 	if (ret) {
    203 		pr_warn("Signal event wasn't created because out of kernel memory\n");
    204 		return ret;
    205 	}
    206 
    207 	p->signal_event_count++;
    208 
    209 	ev->user_signal_address = &p->signal_page->user_address[ev->event_id];
    210 	pr_debug("Signal event number %zu created with id %d, address %p\n",
    211 			p->signal_event_count, ev->event_id,
    212 			ev->user_signal_address);
    213 
    214 	return 0;
    215 }
    216 
    217 static int create_other_event(struct kfd_process *p, struct kfd_event *ev)
    218 {
    219 	/* Cast KFD_LAST_NONSIGNAL_EVENT to uint32_t. This allows an
    220 	 * intentional integer overflow to -1 without a compiler
    221 	 * warning. idr_alloc treats a negative value as "maximum
    222 	 * signed integer".
    223 	 */
    224 	int id = idr_alloc(&p->event_idr, ev, KFD_FIRST_NONSIGNAL_EVENT_ID,
    225 			   (uint32_t)KFD_LAST_NONSIGNAL_EVENT_ID + 1,
    226 			   GFP_KERNEL);
    227 
    228 	if (id < 0)
    229 		return id;
    230 	ev->event_id = id;
    231 
    232 	return 0;
    233 }
    234 
    235 void kfd_event_init_process(struct kfd_process *p)
    236 {
    237 	mutex_init(&p->event_mutex);
    238 	idr_init(&p->event_idr);
    239 	p->signal_page = NULL;
    240 	p->signal_event_count = 0;
    241 }
    242 
    243 static void destroy_event(struct kfd_process *p, struct kfd_event *ev)
    244 {
    245 	struct kfd_event_waiter *waiter;
    246 
    247 	/* Wake up pending waiters. They will return failure */
    248 	list_for_each_entry(waiter, &ev->wq.head, wait.entry)
    249 		waiter->event = NULL;
    250 	wake_up_all(&ev->wq);
    251 
    252 	if (ev->type == KFD_EVENT_TYPE_SIGNAL ||
    253 	    ev->type == KFD_EVENT_TYPE_DEBUG)
    254 		p->signal_event_count--;
    255 
    256 	idr_remove(&p->event_idr, ev->event_id);
    257 	kfree(ev);
    258 }
    259 
    260 static void destroy_events(struct kfd_process *p)
    261 {
    262 	struct kfd_event *ev;
    263 	uint32_t id;
    264 
    265 	idr_for_each_entry(&p->event_idr, ev, id)
    266 		destroy_event(p, ev);
    267 	idr_destroy(&p->event_idr);
    268 }
    269 
    270 /*
    271  * We assume that the process is being destroyed and there is no need to
    272  * unmap the pages or keep bookkeeping data in order.
    273  */
    274 static void shutdown_signal_page(struct kfd_process *p)
    275 {
    276 	struct kfd_signal_page *page = p->signal_page;
    277 
    278 	if (page) {
    279 		if (page->need_to_free_pages)
    280 			free_pages((unsigned long)page->kernel_address,
    281 				   get_order(KFD_SIGNAL_EVENT_LIMIT * 8));
    282 		kfree(page);
    283 	}
    284 }
    285 
    286 void kfd_event_free_process(struct kfd_process *p)
    287 {
    288 	destroy_events(p);
    289 	shutdown_signal_page(p);
    290 }
    291 
    292 static bool event_can_be_gpu_signaled(const struct kfd_event *ev)
    293 {
    294 	return ev->type == KFD_EVENT_TYPE_SIGNAL ||
    295 					ev->type == KFD_EVENT_TYPE_DEBUG;
    296 }
    297 
    298 static bool event_can_be_cpu_signaled(const struct kfd_event *ev)
    299 {
    300 	return ev->type == KFD_EVENT_TYPE_SIGNAL;
    301 }
    302 
    303 int kfd_event_page_set(struct kfd_process *p, void *kernel_address,
    304 		       uint64_t size)
    305 {
    306 	struct kfd_signal_page *page;
    307 
    308 	if (p->signal_page)
    309 		return -EBUSY;
    310 
    311 	page = kzalloc(sizeof(*page), GFP_KERNEL);
    312 	if (!page)
    313 		return -ENOMEM;
    314 
    315 	/* Initialize all events to unsignaled */
    316 	memset(kernel_address, (uint8_t) UNSIGNALED_EVENT_SLOT,
    317 	       KFD_SIGNAL_EVENT_LIMIT * 8);
    318 
    319 	page->kernel_address = kernel_address;
    320 
    321 	p->signal_page = page;
    322 	p->signal_mapped_size = size;
    323 
    324 	return 0;
    325 }
    326 
    327 int kfd_event_create(struct file *devkfd, struct kfd_process *p,
    328 		     uint32_t event_type, bool auto_reset, uint32_t node_id,
    329 		     uint32_t *event_id, uint32_t *event_trigger_data,
    330 		     uint64_t *event_page_offset, uint32_t *event_slot_index)
    331 {
    332 	int ret = 0;
    333 	struct kfd_event *ev = kzalloc(sizeof(*ev), GFP_KERNEL);
    334 
    335 	if (!ev)
    336 		return -ENOMEM;
    337 
    338 	ev->type = event_type;
    339 	ev->auto_reset = auto_reset;
    340 	ev->signaled = false;
    341 
    342 	init_waitqueue_head(&ev->wq);
    343 
    344 	*event_page_offset = 0;
    345 
    346 	mutex_lock(&p->event_mutex);
    347 
    348 	switch (event_type) {
    349 	case KFD_EVENT_TYPE_SIGNAL:
    350 	case KFD_EVENT_TYPE_DEBUG:
    351 		ret = create_signal_event(devkfd, p, ev);
    352 		if (!ret) {
    353 			*event_page_offset = KFD_MMAP_TYPE_EVENTS;
    354 			*event_slot_index = ev->event_id;
    355 		}
    356 		break;
    357 	default:
    358 		ret = create_other_event(p, ev);
    359 		break;
    360 	}
    361 
    362 	if (!ret) {
    363 		*event_id = ev->event_id;
    364 		*event_trigger_data = ev->event_id;
    365 	} else {
    366 		kfree(ev);
    367 	}
    368 
    369 	mutex_unlock(&p->event_mutex);
    370 
    371 	return ret;
    372 }
    373 
    374 /* Assumes that p is current. */
    375 int kfd_event_destroy(struct kfd_process *p, uint32_t event_id)
    376 {
    377 	struct kfd_event *ev;
    378 	int ret = 0;
    379 
    380 	mutex_lock(&p->event_mutex);
    381 
    382 	ev = lookup_event_by_id(p, event_id);
    383 
    384 	if (ev)
    385 		destroy_event(p, ev);
    386 	else
    387 		ret = -EINVAL;
    388 
    389 	mutex_unlock(&p->event_mutex);
    390 	return ret;
    391 }
    392 
    393 static void set_event(struct kfd_event *ev)
    394 {
    395 	struct kfd_event_waiter *waiter;
    396 
    397 	/* Auto reset if the list is non-empty and we're waking
    398 	 * someone. waitqueue_active is safe here because we're
    399 	 * protected by the p->event_mutex, which is also held when
    400 	 * updating the wait queues in kfd_wait_on_events.
    401 	 */
    402 	ev->signaled = !ev->auto_reset || !waitqueue_active(&ev->wq);
    403 
    404 	list_for_each_entry(waiter, &ev->wq.head, wait.entry)
    405 		waiter->activated = true;
    406 
    407 	wake_up_all(&ev->wq);
    408 }
    409 
    410 /* Assumes that p is current. */
    411 int kfd_set_event(struct kfd_process *p, uint32_t event_id)
    412 {
    413 	int ret = 0;
    414 	struct kfd_event *ev;
    415 
    416 	mutex_lock(&p->event_mutex);
    417 
    418 	ev = lookup_event_by_id(p, event_id);
    419 
    420 	if (ev && event_can_be_cpu_signaled(ev))
    421 		set_event(ev);
    422 	else
    423 		ret = -EINVAL;
    424 
    425 	mutex_unlock(&p->event_mutex);
    426 	return ret;
    427 }
    428 
    429 static void reset_event(struct kfd_event *ev)
    430 {
    431 	ev->signaled = false;
    432 }
    433 
    434 /* Assumes that p is current. */
    435 int kfd_reset_event(struct kfd_process *p, uint32_t event_id)
    436 {
    437 	int ret = 0;
    438 	struct kfd_event *ev;
    439 
    440 	mutex_lock(&p->event_mutex);
    441 
    442 	ev = lookup_event_by_id(p, event_id);
    443 
    444 	if (ev && event_can_be_cpu_signaled(ev))
    445 		reset_event(ev);
    446 	else
    447 		ret = -EINVAL;
    448 
    449 	mutex_unlock(&p->event_mutex);
    450 	return ret;
    451 
    452 }
    453 
    454 static void acknowledge_signal(struct kfd_process *p, struct kfd_event *ev)
    455 {
    456 	page_slots(p->signal_page)[ev->event_id] = UNSIGNALED_EVENT_SLOT;
    457 }
    458 
    459 static void set_event_from_interrupt(struct kfd_process *p,
    460 					struct kfd_event *ev)
    461 {
    462 	if (ev && event_can_be_gpu_signaled(ev)) {
    463 		acknowledge_signal(p, ev);
    464 		set_event(ev);
    465 	}
    466 }
    467 
    468 void kfd_signal_event_interrupt(unsigned int pasid, uint32_t partial_id,
    469 				uint32_t valid_id_bits)
    470 {
    471 	struct kfd_event *ev = NULL;
    472 
    473 	/*
    474 	 * Because we are called from arbitrary context (workqueue) as opposed
    475 	 * to process context, kfd_process could attempt to exit while we are
    476 	 * running so the lookup function increments the process ref count.
    477 	 */
    478 	struct kfd_process *p = kfd_lookup_process_by_pasid(pasid);
    479 
    480 	if (!p)
    481 		return; /* Presumably process exited. */
    482 
    483 	mutex_lock(&p->event_mutex);
    484 
    485 	if (valid_id_bits)
    486 		ev = lookup_signaled_event_by_partial_id(p, partial_id,
    487 							 valid_id_bits);
    488 	if (ev) {
    489 		set_event_from_interrupt(p, ev);
    490 	} else if (p->signal_page) {
    491 		/*
    492 		 * Partial ID lookup failed. Assume that the event ID
    493 		 * in the interrupt payload was invalid and do an
    494 		 * exhaustive search of signaled events.
    495 		 */
    496 		uint64_t *slots = page_slots(p->signal_page);
    497 		uint32_t id;
    498 
    499 		if (valid_id_bits)
    500 			pr_debug_ratelimited("Partial ID invalid: %u (%u valid bits)\n",
    501 					     partial_id, valid_id_bits);
    502 
    503 		if (p->signal_event_count < KFD_SIGNAL_EVENT_LIMIT / 64) {
    504 			/* With relatively few events, it's faster to
    505 			 * iterate over the event IDR
    506 			 */
    507 			idr_for_each_entry(&p->event_idr, ev, id) {
    508 				if (id >= KFD_SIGNAL_EVENT_LIMIT)
    509 					break;
    510 
    511 				if (slots[id] != UNSIGNALED_EVENT_SLOT)
    512 					set_event_from_interrupt(p, ev);
    513 			}
    514 		} else {
    515 			/* With relatively many events, it's faster to
    516 			 * iterate over the signal slots and lookup
    517 			 * only signaled events from the IDR.
    518 			 */
    519 			for (id = 0; id < KFD_SIGNAL_EVENT_LIMIT; id++)
    520 				if (slots[id] != UNSIGNALED_EVENT_SLOT) {
    521 					ev = lookup_event_by_id(p, id);
    522 					set_event_from_interrupt(p, ev);
    523 				}
    524 		}
    525 	}
    526 
    527 	mutex_unlock(&p->event_mutex);
    528 	kfd_unref_process(p);
    529 }
    530 
    531 static struct kfd_event_waiter *alloc_event_waiters(uint32_t num_events)
    532 {
    533 	struct kfd_event_waiter *event_waiters;
    534 	uint32_t i;
    535 
    536 	event_waiters = kmalloc_array(num_events,
    537 					sizeof(struct kfd_event_waiter),
    538 					GFP_KERNEL);
    539 
    540 	for (i = 0; (event_waiters) && (i < num_events) ; i++) {
    541 		init_wait(&event_waiters[i].wait);
    542 		event_waiters[i].activated = false;
    543 	}
    544 
    545 	return event_waiters;
    546 }
    547 
    548 static int init_event_waiter_get_status(struct kfd_process *p,
    549 		struct kfd_event_waiter *waiter,
    550 		uint32_t event_id)
    551 {
    552 	struct kfd_event *ev = lookup_event_by_id(p, event_id);
    553 
    554 	if (!ev)
    555 		return -EINVAL;
    556 
    557 	waiter->event = ev;
    558 	waiter->activated = ev->signaled;
    559 	ev->signaled = ev->signaled && !ev->auto_reset;
    560 
    561 	return 0;
    562 }
    563 
    564 static void init_event_waiter_add_to_waitlist(struct kfd_event_waiter *waiter)
    565 {
    566 	struct kfd_event *ev = waiter->event;
    567 
    568 	/* Only add to the wait list if we actually need to
    569 	 * wait on this event.
    570 	 */
    571 	if (!waiter->activated)
    572 		add_wait_queue(&ev->wq, &waiter->wait);
    573 }
    574 
    575 /* test_event_condition - Test condition of events being waited for
    576  * @all:           Return completion only if all events have signaled
    577  * @num_events:    Number of events to wait for
    578  * @event_waiters: Array of event waiters, one per event
    579  *
    580  * Returns KFD_IOC_WAIT_RESULT_COMPLETE if all (or one) event(s) have
    581  * signaled. Returns KFD_IOC_WAIT_RESULT_TIMEOUT if no (or not all)
    582  * events have signaled. Returns KFD_IOC_WAIT_RESULT_FAIL if any of
    583  * the events have been destroyed.
    584  */
    585 static uint32_t test_event_condition(bool all, uint32_t num_events,
    586 				struct kfd_event_waiter *event_waiters)
    587 {
    588 	uint32_t i;
    589 	uint32_t activated_count = 0;
    590 
    591 	for (i = 0; i < num_events; i++) {
    592 		if (!event_waiters[i].event)
    593 			return KFD_IOC_WAIT_RESULT_FAIL;
    594 
    595 		if (event_waiters[i].activated) {
    596 			if (!all)
    597 				return KFD_IOC_WAIT_RESULT_COMPLETE;
    598 
    599 			activated_count++;
    600 		}
    601 	}
    602 
    603 	return activated_count == num_events ?
    604 		KFD_IOC_WAIT_RESULT_COMPLETE : KFD_IOC_WAIT_RESULT_TIMEOUT;
    605 }
    606 
    607 /*
    608  * Copy event specific data, if defined.
    609  * Currently only memory exception events have additional data to copy to user
    610  */
    611 static int copy_signaled_event_data(uint32_t num_events,
    612 		struct kfd_event_waiter *event_waiters,
    613 		struct kfd_event_data __user *data)
    614 {
    615 	struct kfd_hsa_memory_exception_data *src;
    616 	struct kfd_hsa_memory_exception_data __user *dst;
    617 	struct kfd_event_waiter *waiter;
    618 	struct kfd_event *event;
    619 	uint32_t i;
    620 
    621 	for (i = 0; i < num_events; i++) {
    622 		waiter = &event_waiters[i];
    623 		event = waiter->event;
    624 		if (waiter->activated && event->type == KFD_EVENT_TYPE_MEMORY) {
    625 			dst = &data[i].memory_exception_data;
    626 			src = &event->memory_exception_data;
    627 			if (copy_to_user(dst, src,
    628 				sizeof(struct kfd_hsa_memory_exception_data)))
    629 				return -EFAULT;
    630 		}
    631 	}
    632 
    633 	return 0;
    634 
    635 }
    636 
    637 
    638 
    639 static long user_timeout_to_jiffies(uint32_t user_timeout_ms)
    640 {
    641 	if (user_timeout_ms == KFD_EVENT_TIMEOUT_IMMEDIATE)
    642 		return 0;
    643 
    644 	if (user_timeout_ms == KFD_EVENT_TIMEOUT_INFINITE)
    645 		return MAX_SCHEDULE_TIMEOUT;
    646 
    647 	/*
    648 	 * msecs_to_jiffies interprets all values above 2^31-1 as infinite,
    649 	 * but we consider them finite.
    650 	 * This hack is wrong, but nobody is likely to notice.
    651 	 */
    652 	user_timeout_ms = min_t(uint32_t, user_timeout_ms, 0x7FFFFFFF);
    653 
    654 	return msecs_to_jiffies(user_timeout_ms) + 1;
    655 }
    656 
    657 static void free_waiters(uint32_t num_events, struct kfd_event_waiter *waiters)
    658 {
    659 	uint32_t i;
    660 
    661 	for (i = 0; i < num_events; i++)
    662 		if (waiters[i].event)
    663 			remove_wait_queue(&waiters[i].event->wq,
    664 					  &waiters[i].wait);
    665 
    666 	kfree(waiters);
    667 }
    668 
    669 int kfd_wait_on_events(struct kfd_process *p,
    670 		       uint32_t num_events, void __user *data,
    671 		       bool all, uint32_t user_timeout_ms,
    672 		       uint32_t *wait_result)
    673 {
    674 	struct kfd_event_data __user *events =
    675 			(struct kfd_event_data __user *) data;
    676 	uint32_t i;
    677 	int ret = 0;
    678 
    679 	struct kfd_event_waiter *event_waiters = NULL;
    680 	long timeout = user_timeout_to_jiffies(user_timeout_ms);
    681 
    682 	event_waiters = alloc_event_waiters(num_events);
    683 	if (!event_waiters) {
    684 		ret = -ENOMEM;
    685 		goto out;
    686 	}
    687 
    688 	mutex_lock(&p->event_mutex);
    689 
    690 	for (i = 0; i < num_events; i++) {
    691 		struct kfd_event_data event_data;
    692 
    693 		if (copy_from_user(&event_data, &events[i],
    694 				sizeof(struct kfd_event_data))) {
    695 			ret = -EFAULT;
    696 			goto out_unlock;
    697 		}
    698 
    699 		ret = init_event_waiter_get_status(p, &event_waiters[i],
    700 				event_data.event_id);
    701 		if (ret)
    702 			goto out_unlock;
    703 	}
    704 
    705 	/* Check condition once. */
    706 	*wait_result = test_event_condition(all, num_events, event_waiters);
    707 	if (*wait_result == KFD_IOC_WAIT_RESULT_COMPLETE) {
    708 		ret = copy_signaled_event_data(num_events,
    709 					       event_waiters, events);
    710 		goto out_unlock;
    711 	} else if (WARN_ON(*wait_result == KFD_IOC_WAIT_RESULT_FAIL)) {
    712 		/* This should not happen. Events shouldn't be
    713 		 * destroyed while we're holding the event_mutex
    714 		 */
    715 		goto out_unlock;
    716 	}
    717 
    718 	/* Add to wait lists if we need to wait. */
    719 	for (i = 0; i < num_events; i++)
    720 		init_event_waiter_add_to_waitlist(&event_waiters[i]);
    721 
    722 	mutex_unlock(&p->event_mutex);
    723 
    724 	while (true) {
    725 		if (fatal_signal_pending(current)) {
    726 			ret = -EINTR;
    727 			break;
    728 		}
    729 
    730 		if (signal_pending(current)) {
    731 			/*
    732 			 * This is wrong when a nonzero, non-infinite timeout
    733 			 * is specified. We need to use
    734 			 * ERESTARTSYS_RESTARTBLOCK, but struct restart_block
    735 			 * contains a union with data for each user and it's
    736 			 * in generic kernel code that I don't want to
    737 			 * touch yet.
    738 			 */
    739 			ret = -ERESTARTSYS;
    740 			break;
    741 		}
    742 
    743 		/* Set task state to interruptible sleep before
    744 		 * checking wake-up conditions. A concurrent wake-up
    745 		 * will put the task back into runnable state. In that
    746 		 * case schedule_timeout will not put the task to
    747 		 * sleep and we'll get a chance to re-check the
    748 		 * updated conditions almost immediately. Otherwise,
    749 		 * this race condition would lead to a soft hang or a
    750 		 * very long sleep.
    751 		 */
    752 		set_current_state(TASK_INTERRUPTIBLE);
    753 
    754 		*wait_result = test_event_condition(all, num_events,
    755 						    event_waiters);
    756 		if (*wait_result != KFD_IOC_WAIT_RESULT_TIMEOUT)
    757 			break;
    758 
    759 		if (timeout <= 0)
    760 			break;
    761 
    762 		timeout = schedule_timeout(timeout);
    763 	}
    764 	__set_current_state(TASK_RUNNING);
    765 
    766 	/* copy_signaled_event_data may sleep. So this has to happen
    767 	 * after the task state is set back to RUNNING.
    768 	 */
    769 	if (!ret && *wait_result == KFD_IOC_WAIT_RESULT_COMPLETE)
    770 		ret = copy_signaled_event_data(num_events,
    771 					       event_waiters, events);
    772 
    773 	mutex_lock(&p->event_mutex);
    774 out_unlock:
    775 	free_waiters(num_events, event_waiters);
    776 	mutex_unlock(&p->event_mutex);
    777 out:
    778 	if (ret)
    779 		*wait_result = KFD_IOC_WAIT_RESULT_FAIL;
    780 	else if (*wait_result == KFD_IOC_WAIT_RESULT_FAIL)
    781 		ret = -EIO;
    782 
    783 	return ret;
    784 }
    785 
    786 int kfd_event_mmap(struct kfd_process *p, struct vm_area_struct *vma)
    787 {
    788 	unsigned long pfn;
    789 	struct kfd_signal_page *page;
    790 	int ret;
    791 
    792 	/* check required size doesn't exceed the allocated size */
    793 	if (get_order(KFD_SIGNAL_EVENT_LIMIT * 8) <
    794 			get_order(vma->vm_end - vma->vm_start)) {
    795 		pr_err("Event page mmap requested illegal size\n");
    796 		return -EINVAL;
    797 	}
    798 
    799 	page = p->signal_page;
    800 	if (!page) {
    801 		/* Probably KFD bug, but mmap is user-accessible. */
    802 		pr_debug("Signal page could not be found\n");
    803 		return -EINVAL;
    804 	}
    805 
    806 	pfn = __pa(page->kernel_address);
    807 	pfn >>= PAGE_SHIFT;
    808 
    809 	vma->vm_flags |= VM_IO | VM_DONTCOPY | VM_DONTEXPAND | VM_NORESERVE
    810 		       | VM_DONTDUMP | VM_PFNMAP;
    811 
    812 	pr_debug("Mapping signal page\n");
    813 	pr_debug("     start user address  == 0x%08lx\n", vma->vm_start);
    814 	pr_debug("     end user address    == 0x%08lx\n", vma->vm_end);
    815 	pr_debug("     pfn                 == 0x%016lX\n", pfn);
    816 	pr_debug("     vm_flags            == 0x%08lX\n", vma->vm_flags);
    817 	pr_debug("     size                == 0x%08lX\n",
    818 			vma->vm_end - vma->vm_start);
    819 
    820 	page->user_address = (uint64_t __user *)vma->vm_start;
    821 
    822 	/* mapping the page to user process */
    823 	ret = remap_pfn_range(vma, vma->vm_start, pfn,
    824 			vma->vm_end - vma->vm_start, vma->vm_page_prot);
    825 	if (!ret)
    826 		p->signal_mapped_size = vma->vm_end - vma->vm_start;
    827 
    828 	return ret;
    829 }
    830 
    831 /*
    832  * Assumes that p->event_mutex is held and of course
    833  * that p is not going away (current or locked).
    834  */
    835 static void lookup_events_by_type_and_signal(struct kfd_process *p,
    836 		int type, void *event_data)
    837 {
    838 	struct kfd_hsa_memory_exception_data *ev_data;
    839 	struct kfd_event *ev;
    840 	uint32_t id;
    841 	bool send_signal = true;
    842 
    843 	ev_data = (struct kfd_hsa_memory_exception_data *) event_data;
    844 
    845 	id = KFD_FIRST_NONSIGNAL_EVENT_ID;
    846 	idr_for_each_entry_continue(&p->event_idr, ev, id)
    847 		if (ev->type == type) {
    848 			send_signal = false;
    849 			dev_dbg(kfd_device,
    850 					"Event found: id %X type %d",
    851 					ev->event_id, ev->type);
    852 			set_event(ev);
    853 			if (ev->type == KFD_EVENT_TYPE_MEMORY && ev_data)
    854 				ev->memory_exception_data = *ev_data;
    855 		}
    856 
    857 	if (type == KFD_EVENT_TYPE_MEMORY) {
    858 		dev_warn(kfd_device,
    859 			"Sending SIGSEGV to process %d (pasid 0x%x)",
    860 				p->lead_thread->pid, p->pasid);
    861 		send_sig(SIGSEGV, p->lead_thread, 0);
    862 	}
    863 
    864 	/* Send SIGTERM no event of type "type" has been found*/
    865 	if (send_signal) {
    866 		if (send_sigterm) {
    867 			dev_warn(kfd_device,
    868 				"Sending SIGTERM to process %d (pasid 0x%x)",
    869 					p->lead_thread->pid, p->pasid);
    870 			send_sig(SIGTERM, p->lead_thread, 0);
    871 		} else {
    872 			dev_err(kfd_device,
    873 				"Process %d (pasid 0x%x) got unhandled exception",
    874 				p->lead_thread->pid, p->pasid);
    875 		}
    876 	}
    877 }
    878 
    879 #ifdef KFD_SUPPORT_IOMMU_V2
    880 void kfd_signal_iommu_event(struct kfd_dev *dev, unsigned int pasid,
    881 		unsigned long address, bool is_write_requested,
    882 		bool is_execute_requested)
    883 {
    884 	struct kfd_hsa_memory_exception_data memory_exception_data;
    885 	struct vm_area_struct *vma;
    886 
    887 	/*
    888 	 * Because we are called from arbitrary context (workqueue) as opposed
    889 	 * to process context, kfd_process could attempt to exit while we are
    890 	 * running so the lookup function increments the process ref count.
    891 	 */
    892 	struct kfd_process *p = kfd_lookup_process_by_pasid(pasid);
    893 	struct mm_struct *mm;
    894 
    895 	if (!p)
    896 		return; /* Presumably process exited. */
    897 
    898 	/* Take a safe reference to the mm_struct, which may otherwise
    899 	 * disappear even while the kfd_process is still referenced.
    900 	 */
    901 	mm = get_task_mm(p->lead_thread);
    902 	if (!mm) {
    903 		kfd_unref_process(p);
    904 		return; /* Process is exiting */
    905 	}
    906 
    907 	memset(&memory_exception_data, 0, sizeof(memory_exception_data));
    908 
    909 	down_read(&mm->mmap_sem);
    910 	vma = find_vma(mm, address);
    911 
    912 	memory_exception_data.gpu_id = dev->id;
    913 	memory_exception_data.va = address;
    914 	/* Set failure reason */
    915 	memory_exception_data.failure.NotPresent = 1;
    916 	memory_exception_data.failure.NoExecute = 0;
    917 	memory_exception_data.failure.ReadOnly = 0;
    918 	if (vma && address >= vma->vm_start) {
    919 		memory_exception_data.failure.NotPresent = 0;
    920 
    921 		if (is_write_requested && !(vma->vm_flags & VM_WRITE))
    922 			memory_exception_data.failure.ReadOnly = 1;
    923 		else
    924 			memory_exception_data.failure.ReadOnly = 0;
    925 
    926 		if (is_execute_requested && !(vma->vm_flags & VM_EXEC))
    927 			memory_exception_data.failure.NoExecute = 1;
    928 		else
    929 			memory_exception_data.failure.NoExecute = 0;
    930 	}
    931 
    932 	up_read(&mm->mmap_sem);
    933 	mmput(mm);
    934 
    935 	pr_debug("notpresent %d, noexecute %d, readonly %d\n",
    936 			memory_exception_data.failure.NotPresent,
    937 			memory_exception_data.failure.NoExecute,
    938 			memory_exception_data.failure.ReadOnly);
    939 
    940 	/* Workaround on Raven to not kill the process when memory is freed
    941 	 * before IOMMU is able to finish processing all the excessive PPRs
    942 	 */
    943 	if (dev->device_info->asic_family != CHIP_RAVEN &&
    944 	    dev->device_info->asic_family != CHIP_RENOIR) {
    945 		mutex_lock(&p->event_mutex);
    946 
    947 		/* Lookup events by type and signal them */
    948 		lookup_events_by_type_and_signal(p, KFD_EVENT_TYPE_MEMORY,
    949 				&memory_exception_data);
    950 
    951 		mutex_unlock(&p->event_mutex);
    952 	}
    953 
    954 	kfd_unref_process(p);
    955 }
    956 #endif /* KFD_SUPPORT_IOMMU_V2 */
    957 
    958 void kfd_signal_hw_exception_event(unsigned int pasid)
    959 {
    960 	/*
    961 	 * Because we are called from arbitrary context (workqueue) as opposed
    962 	 * to process context, kfd_process could attempt to exit while we are
    963 	 * running so the lookup function increments the process ref count.
    964 	 */
    965 	struct kfd_process *p = kfd_lookup_process_by_pasid(pasid);
    966 
    967 	if (!p)
    968 		return; /* Presumably process exited. */
    969 
    970 	mutex_lock(&p->event_mutex);
    971 
    972 	/* Lookup events by type and signal them */
    973 	lookup_events_by_type_and_signal(p, KFD_EVENT_TYPE_HW_EXCEPTION, NULL);
    974 
    975 	mutex_unlock(&p->event_mutex);
    976 	kfd_unref_process(p);
    977 }
    978 
    979 void kfd_signal_vm_fault_event(struct kfd_dev *dev, unsigned int pasid,
    980 				struct kfd_vm_fault_info *info)
    981 {
    982 	struct kfd_event *ev;
    983 	uint32_t id;
    984 	struct kfd_process *p = kfd_lookup_process_by_pasid(pasid);
    985 	struct kfd_hsa_memory_exception_data memory_exception_data;
    986 
    987 	if (!p)
    988 		return; /* Presumably process exited. */
    989 	memset(&memory_exception_data, 0, sizeof(memory_exception_data));
    990 	memory_exception_data.gpu_id = dev->id;
    991 	memory_exception_data.failure.imprecise = true;
    992 	/* Set failure reason */
    993 	if (info) {
    994 		memory_exception_data.va = (info->page_addr) << PAGE_SHIFT;
    995 		memory_exception_data.failure.NotPresent =
    996 			info->prot_valid ? 1 : 0;
    997 		memory_exception_data.failure.NoExecute =
    998 			info->prot_exec ? 1 : 0;
    999 		memory_exception_data.failure.ReadOnly =
   1000 			info->prot_write ? 1 : 0;
   1001 		memory_exception_data.failure.imprecise = 0;
   1002 	}
   1003 	mutex_lock(&p->event_mutex);
   1004 
   1005 	id = KFD_FIRST_NONSIGNAL_EVENT_ID;
   1006 	idr_for_each_entry_continue(&p->event_idr, ev, id)
   1007 		if (ev->type == KFD_EVENT_TYPE_MEMORY) {
   1008 			ev->memory_exception_data = memory_exception_data;
   1009 			set_event(ev);
   1010 		}
   1011 
   1012 	mutex_unlock(&p->event_mutex);
   1013 	kfd_unref_process(p);
   1014 }
   1015 
   1016 void kfd_signal_reset_event(struct kfd_dev *dev)
   1017 {
   1018 	struct kfd_hsa_hw_exception_data hw_exception_data;
   1019 	struct kfd_hsa_memory_exception_data memory_exception_data;
   1020 	struct kfd_process *p;
   1021 	struct kfd_event *ev;
   1022 	unsigned int temp;
   1023 	uint32_t id, idx;
   1024 	int reset_cause = atomic_read(&dev->sram_ecc_flag) ?
   1025 			KFD_HW_EXCEPTION_ECC :
   1026 			KFD_HW_EXCEPTION_GPU_HANG;
   1027 
   1028 	/* Whole gpu reset caused by GPU hang and memory is lost */
   1029 	memset(&hw_exception_data, 0, sizeof(hw_exception_data));
   1030 	hw_exception_data.gpu_id = dev->id;
   1031 	hw_exception_data.memory_lost = 1;
   1032 	hw_exception_data.reset_cause = reset_cause;
   1033 
   1034 	memset(&memory_exception_data, 0, sizeof(memory_exception_data));
   1035 	memory_exception_data.ErrorType = KFD_MEM_ERR_SRAM_ECC;
   1036 	memory_exception_data.gpu_id = dev->id;
   1037 	memory_exception_data.failure.imprecise = true;
   1038 
   1039 	idx = srcu_read_lock(&kfd_processes_srcu);
   1040 	hash_for_each_rcu(kfd_processes_table, temp, p, kfd_processes) {
   1041 		mutex_lock(&p->event_mutex);
   1042 		id = KFD_FIRST_NONSIGNAL_EVENT_ID;
   1043 		idr_for_each_entry_continue(&p->event_idr, ev, id) {
   1044 			if (ev->type == KFD_EVENT_TYPE_HW_EXCEPTION) {
   1045 				ev->hw_exception_data = hw_exception_data;
   1046 				set_event(ev);
   1047 			}
   1048 			if (ev->type == KFD_EVENT_TYPE_MEMORY &&
   1049 			    reset_cause == KFD_HW_EXCEPTION_ECC) {
   1050 				ev->memory_exception_data = memory_exception_data;
   1051 				set_event(ev);
   1052 			}
   1053 		}
   1054 		mutex_unlock(&p->event_mutex);
   1055 	}
   1056 	srcu_read_unlock(&kfd_processes_srcu, idx);
   1057 }
   1058