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