xref: /linux/drivers/gpu/drm/vc4/vc4_gem.c (revision af1cf92e8617a7f7aa24b415596cbf64b76a12e7)
1 /*
2  * Copyright © 2014 Broadcom
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 (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #include <linux/module.h>
25 #include <linux/platform_device.h>
26 #include <linux/reset.h>
27 #include <linux/device.h>
28 #include <linux/io.h>
29 #include <linux/sched/signal.h>
30 #include <linux/dma-fence-array.h>
31 
32 #include <drm/drm_exec.h>
33 #include <drm/drm_print.h>
34 #include <drm/drm_syncobj.h>
35 #include <drm/drm_timeout.h>
36 
37 #include "vc4_drv.h"
38 #include "vc4_regs.h"
39 #include "vc4_trace.h"
40 
41 static void
42 vc4_queue_hangcheck(struct drm_device *dev)
43 {
44 	struct vc4_dev *vc4 = to_vc4_dev(dev);
45 
46 	mod_timer(&vc4->hangcheck.timer, jiffies + msecs_to_jiffies(100));
47 }
48 
49 struct vc4_hang_state {
50 	struct drm_vc4_get_hang_state user_state;
51 
52 	u32 bo_count;
53 	struct drm_gem_object **bo;
54 };
55 
56 static void
57 vc4_free_hang_state(struct drm_device *dev, struct vc4_hang_state *state)
58 {
59 	unsigned int i;
60 
61 	for (i = 0; i < state->user_state.bo_count; i++)
62 		drm_gem_object_put(state->bo[i]);
63 
64 	kfree(state->bo);
65 	kfree(state);
66 }
67 
68 int
69 vc4_get_hang_state_ioctl(struct drm_device *dev, void *data,
70 			 struct drm_file *file_priv)
71 {
72 	struct drm_vc4_get_hang_state *get_state = data;
73 	struct drm_vc4_get_hang_state_bo *bo_state;
74 	struct vc4_hang_state *kernel_state;
75 	struct drm_vc4_get_hang_state *state;
76 	struct vc4_dev *vc4 = to_vc4_dev(dev);
77 	unsigned long irqflags;
78 	u32 i;
79 	int ret = 0;
80 
81 	if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4))
82 		return -ENODEV;
83 
84 	if (!vc4->v3d) {
85 		DRM_DEBUG("VC4_GET_HANG_STATE with no VC4 V3D probed\n");
86 		return -ENODEV;
87 	}
88 
89 	spin_lock_irqsave(&vc4->job_lock, irqflags);
90 	kernel_state = vc4->hang_state;
91 	if (!kernel_state) {
92 		spin_unlock_irqrestore(&vc4->job_lock, irqflags);
93 		return -ENOENT;
94 	}
95 	state = &kernel_state->user_state;
96 
97 	/* If the user's array isn't big enough, just return the
98 	 * required array size.
99 	 */
100 	if (get_state->bo_count < state->bo_count) {
101 		get_state->bo_count = state->bo_count;
102 		spin_unlock_irqrestore(&vc4->job_lock, irqflags);
103 		return 0;
104 	}
105 
106 	vc4->hang_state = NULL;
107 	spin_unlock_irqrestore(&vc4->job_lock, irqflags);
108 
109 	/* Save the user's BO pointer, so we don't stomp it with the memcpy. */
110 	state->bo = get_state->bo;
111 	memcpy(get_state, state, sizeof(*state));
112 
113 	bo_state = kzalloc_objs(*bo_state, state->bo_count);
114 	if (!bo_state) {
115 		ret = -ENOMEM;
116 		goto err_free;
117 	}
118 
119 	for (i = 0; i < state->bo_count; i++) {
120 		struct vc4_bo *vc4_bo = to_vc4_bo(kernel_state->bo[i]);
121 		u32 handle;
122 
123 		ret = drm_gem_handle_create(file_priv, kernel_state->bo[i],
124 					    &handle);
125 
126 		if (ret) {
127 			state->bo_count = i;
128 			goto err_delete_handle;
129 		}
130 		bo_state[i].handle = handle;
131 		bo_state[i].paddr = vc4_bo->base.dma_addr;
132 		bo_state[i].size = vc4_bo->base.base.size;
133 	}
134 
135 	if (copy_to_user(u64_to_user_ptr(get_state->bo),
136 			 bo_state,
137 			 state->bo_count * sizeof(*bo_state)))
138 		ret = -EFAULT;
139 
140 err_delete_handle:
141 	if (ret) {
142 		for (i = 0; i < state->bo_count; i++)
143 			drm_gem_handle_delete(file_priv, bo_state[i].handle);
144 	}
145 
146 err_free:
147 	vc4_free_hang_state(dev, kernel_state);
148 	kfree(bo_state);
149 
150 	return ret;
151 }
152 
153 static void
154 vc4_save_hang_state(struct drm_device *dev)
155 {
156 	struct vc4_dev *vc4 = to_vc4_dev(dev);
157 	struct drm_vc4_get_hang_state *state;
158 	struct vc4_hang_state *kernel_state;
159 	struct vc4_exec_info *exec[2];
160 	struct vc4_bo *bo;
161 	unsigned long irqflags;
162 	unsigned int i, j, k, unref_list_count;
163 
164 	kernel_state = kzalloc_objs(*kernel_state, 1);
165 	if (!kernel_state)
166 		return;
167 
168 	state = &kernel_state->user_state;
169 
170 	spin_lock_irqsave(&vc4->job_lock, irqflags);
171 	exec[0] = vc4_first_bin_job(vc4);
172 	exec[1] = vc4_first_render_job(vc4);
173 	if (!exec[0] && !exec[1])
174 		goto err_free_state;
175 
176 	/* Get the bos from both binner and renderer into hang state. */
177 	state->bo_count = 0;
178 	for (i = 0; i < 2; i++) {
179 		if (!exec[i])
180 			continue;
181 
182 		unref_list_count = 0;
183 		list_for_each_entry(bo, &exec[i]->unref_list, unref_head)
184 			unref_list_count++;
185 		state->bo_count += exec[i]->bo_count + unref_list_count;
186 	}
187 
188 	kernel_state->bo = kzalloc_objs(*kernel_state->bo, state->bo_count,
189 					GFP_ATOMIC);
190 
191 	if (!kernel_state->bo)
192 		goto err_free_state;
193 
194 	k = 0;
195 	for (i = 0; i < 2; i++) {
196 		if (!exec[i])
197 			continue;
198 
199 		for (j = 0; j < exec[i]->bo_count; j++) {
200 			bo = to_vc4_bo(exec[i]->bo[j]);
201 
202 			/* Retain BOs just in case they were marked purgeable.
203 			 * This prevents the BO from being purged before
204 			 * someone had a chance to dump the hang state.
205 			 */
206 			WARN_ON(!refcount_read(&bo->usecnt));
207 			refcount_inc(&bo->usecnt);
208 			drm_gem_object_get(exec[i]->bo[j]);
209 			kernel_state->bo[k++] = exec[i]->bo[j];
210 		}
211 
212 		list_for_each_entry(bo, &exec[i]->unref_list, unref_head) {
213 			/* No need to retain BOs coming from the ->unref_list
214 			 * because they are naturally unpurgeable.
215 			 */
216 			drm_gem_object_get(&bo->base.base);
217 			kernel_state->bo[k++] = &bo->base.base;
218 		}
219 	}
220 
221 	WARN_ON_ONCE(k != state->bo_count);
222 
223 	if (exec[0])
224 		state->start_bin = exec[0]->ct0ca;
225 	if (exec[1])
226 		state->start_render = exec[1]->ct1ca;
227 
228 	spin_unlock_irqrestore(&vc4->job_lock, irqflags);
229 
230 	state->ct0ca = V3D_READ(V3D_CTNCA(0));
231 	state->ct0ea = V3D_READ(V3D_CTNEA(0));
232 
233 	state->ct1ca = V3D_READ(V3D_CTNCA(1));
234 	state->ct1ea = V3D_READ(V3D_CTNEA(1));
235 
236 	state->ct0cs = V3D_READ(V3D_CTNCS(0));
237 	state->ct1cs = V3D_READ(V3D_CTNCS(1));
238 
239 	state->ct0ra0 = V3D_READ(V3D_CT00RA0);
240 	state->ct1ra0 = V3D_READ(V3D_CT01RA0);
241 
242 	state->bpca = V3D_READ(V3D_BPCA);
243 	state->bpcs = V3D_READ(V3D_BPCS);
244 	state->bpoa = V3D_READ(V3D_BPOA);
245 	state->bpos = V3D_READ(V3D_BPOS);
246 
247 	state->vpmbase = V3D_READ(V3D_VPMBASE);
248 
249 	state->dbge = V3D_READ(V3D_DBGE);
250 	state->fdbgo = V3D_READ(V3D_FDBGO);
251 	state->fdbgb = V3D_READ(V3D_FDBGB);
252 	state->fdbgr = V3D_READ(V3D_FDBGR);
253 	state->fdbgs = V3D_READ(V3D_FDBGS);
254 	state->errstat = V3D_READ(V3D_ERRSTAT);
255 
256 	/* We need to turn purgeable BOs into unpurgeable ones so that
257 	 * userspace has a chance to dump the hang state before the kernel
258 	 * decides to purge those BOs.
259 	 * Note that BO consistency at dump time cannot be guaranteed. For
260 	 * example, if the owner of these BOs decides to re-use them or mark
261 	 * them purgeable again there's nothing we can do to prevent it.
262 	 */
263 	for (i = 0; i < kernel_state->user_state.bo_count; i++) {
264 		struct vc4_bo *bo = to_vc4_bo(kernel_state->bo[i]);
265 
266 		if (bo->madv == __VC4_MADV_NOTSUPP)
267 			continue;
268 
269 		mutex_lock(&bo->madv_lock);
270 		if (!WARN_ON(bo->madv == __VC4_MADV_PURGED))
271 			bo->madv = VC4_MADV_WILLNEED;
272 		refcount_dec(&bo->usecnt);
273 		mutex_unlock(&bo->madv_lock);
274 	}
275 
276 	spin_lock_irqsave(&vc4->job_lock, irqflags);
277 	if (vc4->hang_state) {
278 		spin_unlock_irqrestore(&vc4->job_lock, irqflags);
279 		vc4_free_hang_state(dev, kernel_state);
280 	} else {
281 		vc4->hang_state = kernel_state;
282 		spin_unlock_irqrestore(&vc4->job_lock, irqflags);
283 	}
284 
285 	return;
286 
287 err_free_state:
288 	spin_unlock_irqrestore(&vc4->job_lock, irqflags);
289 	kfree(kernel_state);
290 }
291 
292 static void
293 vc4_reset(struct drm_device *dev)
294 {
295 	struct vc4_v3d *v3d = to_vc4_dev(dev)->v3d;
296 	int ret;
297 
298 	vc4_irq_disable(dev);
299 
300 	if (v3d->reset) {
301 		drm_info(dev, "Resetting GPU.\n");
302 
303 		ret = reset_control_reset(v3d->reset);
304 		if (ret)
305 			drm_err(dev, "Failed to reset the GPU: %d\n", ret);
306 
307 		vc4_v3d_init_hw(dev);
308 	} else {
309 		drm_info_once(dev, "No reset line; GPU state is not reset.\n");
310 	}
311 
312 	vc4_irq_reset(dev);
313 
314 	/* Rearm the hangcheck -- another job might have been waiting
315 	 * for our hung one to get kicked off, and vc4_irq_reset()
316 	 * would have started it.
317 	 */
318 	vc4_queue_hangcheck(dev);
319 }
320 
321 static void
322 vc4_reset_work(struct work_struct *work)
323 {
324 	struct vc4_dev *vc4 =
325 		container_of(work, struct vc4_dev, hangcheck.reset_work);
326 	int ret;
327 
328 	/* Make sure the device is not suspended during the reset. */
329 	ret = vc4_v3d_pm_get(vc4);
330 	if (ret) {
331 		drm_err(&vc4->base, "Failed to resume V3D for GPU reset: %d\n", ret);
332 		return;
333 	}
334 
335 	vc4_save_hang_state(&vc4->base);
336 	vc4_reset(&vc4->base);
337 
338 	vc4_v3d_pm_put(vc4);
339 }
340 
341 static void
342 vc4_hangcheck_elapsed(struct timer_list *t)
343 {
344 	struct vc4_dev *vc4 = timer_container_of(vc4, t, hangcheck.timer);
345 	struct drm_device *dev = &vc4->base;
346 	uint32_t ct0ca, ct1ca;
347 	unsigned long irqflags;
348 	struct vc4_exec_info *bin_exec, *render_exec;
349 
350 	spin_lock_irqsave(&vc4->job_lock, irqflags);
351 
352 	bin_exec = vc4_first_bin_job(vc4);
353 	render_exec = vc4_first_render_job(vc4);
354 
355 	/* If idle, we can stop watching for hangs. */
356 	if (!bin_exec && !render_exec) {
357 		vc4->hangcheck.caches_cleared = false;
358 		spin_unlock_irqrestore(&vc4->job_lock, irqflags);
359 		return;
360 	}
361 
362 	ct0ca = V3D_READ(V3D_CTNCA(0));
363 	ct1ca = V3D_READ(V3D_CTNCA(1));
364 
365 	/* If we've made any progress in execution, rearm the timer
366 	 * and wait.
367 	 */
368 	if ((bin_exec && ct0ca != bin_exec->last_ct0ca) ||
369 	    (render_exec && ct1ca != render_exec->last_ct1ca)) {
370 		if (bin_exec)
371 			bin_exec->last_ct0ca = ct0ca;
372 		if (render_exec)
373 			render_exec->last_ct1ca = ct1ca;
374 
375 		vc4->hangcheck.caches_cleared = false;
376 
377 		spin_unlock_irqrestore(&vc4->job_lock, irqflags);
378 		vc4_queue_hangcheck(dev);
379 		return;
380 	}
381 
382 	/* Clear the slice caches to workaround GFXH-16 */
383 	if (!vc4->hangcheck.caches_cleared) {
384 		V3D_WRITE(V3D_SLCACTL, VC4_SET_FIELD(0xf, V3D_SLCACTL_ICC) |
385 			  VC4_SET_FIELD(0xf, V3D_SLCACTL_UCC));
386 
387 		vc4->hangcheck.caches_cleared = true;
388 		spin_unlock_irqrestore(&vc4->job_lock, irqflags);
389 		vc4_queue_hangcheck(dev);
390 		return;
391 	}
392 
393 	vc4->hangcheck.caches_cleared = false;
394 
395 	spin_unlock_irqrestore(&vc4->job_lock, irqflags);
396 
397 	/* We've gone too long with no progress, reset.  This has to
398 	 * be done from a work struct, since resetting can sleep and
399 	 * this timer hook isn't allowed to.
400 	 */
401 	schedule_work(&vc4->hangcheck.reset_work);
402 }
403 
404 static void
405 submit_cl(struct drm_device *dev, uint32_t thread, uint32_t start, uint32_t end)
406 {
407 	struct vc4_dev *vc4 = to_vc4_dev(dev);
408 
409 	/* Set the current and end address of the control list.
410 	 * Writing the end register is what starts the job.
411 	 */
412 	V3D_WRITE(V3D_CTNCA(thread), start);
413 	V3D_WRITE(V3D_CTNEA(thread), end);
414 }
415 
416 int
417 vc4_wait_for_seqno(struct drm_device *dev, uint64_t seqno, uint64_t timeout_ns,
418 		   bool interruptible)
419 {
420 	struct vc4_dev *vc4 = to_vc4_dev(dev);
421 	int ret = 0;
422 	unsigned long timeout_expire;
423 	DEFINE_WAIT(wait);
424 
425 	if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4))
426 		return -ENODEV;
427 
428 	if (vc4->finished_seqno >= seqno)
429 		return 0;
430 
431 	if (timeout_ns == 0)
432 		return -ETIME;
433 
434 	timeout_expire = jiffies + nsecs_to_jiffies(timeout_ns);
435 
436 	trace_vc4_wait_for_seqno_begin(dev, seqno, timeout_ns);
437 	for (;;) {
438 		prepare_to_wait(&vc4->job_wait_queue, &wait,
439 				interruptible ? TASK_INTERRUPTIBLE :
440 				TASK_UNINTERRUPTIBLE);
441 
442 		if (interruptible && signal_pending(current)) {
443 			ret = -ERESTARTSYS;
444 			break;
445 		}
446 
447 		if (vc4->finished_seqno >= seqno)
448 			break;
449 
450 		if (timeout_ns != ~0ull) {
451 			if (time_after_eq(jiffies, timeout_expire)) {
452 				ret = -ETIME;
453 				break;
454 			}
455 			schedule_timeout(timeout_expire - jiffies);
456 		} else {
457 			schedule();
458 		}
459 	}
460 
461 	finish_wait(&vc4->job_wait_queue, &wait);
462 	trace_vc4_wait_for_seqno_end(dev, seqno);
463 
464 	return ret;
465 }
466 
467 static void
468 vc4_flush_caches(struct drm_device *dev)
469 {
470 	struct vc4_dev *vc4 = to_vc4_dev(dev);
471 
472 	/* Flush the GPU L2 caches.  These caches sit on top of system
473 	 * L3 (the 128kb or so shared with the CPU), and are
474 	 * non-allocating in the L3.
475 	 */
476 	V3D_WRITE(V3D_L2CACTL,
477 		  V3D_L2CACTL_L2CCLR);
478 
479 	V3D_WRITE(V3D_SLCACTL,
480 		  VC4_SET_FIELD(0xf, V3D_SLCACTL_T1CC) |
481 		  VC4_SET_FIELD(0xf, V3D_SLCACTL_T0CC) |
482 		  VC4_SET_FIELD(0xf, V3D_SLCACTL_UCC) |
483 		  VC4_SET_FIELD(0xf, V3D_SLCACTL_ICC));
484 }
485 
486 static void
487 vc4_flush_texture_caches(struct drm_device *dev)
488 {
489 	struct vc4_dev *vc4 = to_vc4_dev(dev);
490 
491 	V3D_WRITE(V3D_L2CACTL,
492 		  V3D_L2CACTL_L2CCLR);
493 
494 	V3D_WRITE(V3D_SLCACTL,
495 		  VC4_SET_FIELD(0xf, V3D_SLCACTL_T1CC) |
496 		  VC4_SET_FIELD(0xf, V3D_SLCACTL_T0CC));
497 }
498 
499 /* Sets the registers for the next job to be actually be executed in
500  * the hardware.
501  *
502  * The job_lock should be held during this.
503  */
504 void
505 vc4_submit_next_bin_job(struct drm_device *dev)
506 {
507 	struct vc4_dev *vc4 = to_vc4_dev(dev);
508 	struct vc4_exec_info *exec;
509 
510 	if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4))
511 		return;
512 
513 again:
514 	exec = vc4_first_bin_job(vc4);
515 	if (!exec)
516 		return;
517 
518 	vc4_flush_caches(dev);
519 
520 	/* Only start the perfmon if it was not already started by a previous
521 	 * job.
522 	 */
523 	if (exec->perfmon && vc4->active_perfmon != exec->perfmon)
524 		vc4_perfmon_start(vc4, exec->perfmon);
525 
526 	/* Either put the job in the binner if it uses the binner, or
527 	 * immediately move it to the to-be-rendered queue.
528 	 */
529 	if (exec->ct0ca != exec->ct0ea) {
530 		trace_vc4_submit_cl(dev, false, exec->seqno, exec->ct0ca,
531 				    exec->ct0ea);
532 		submit_cl(dev, 0, exec->ct0ca, exec->ct0ea);
533 	} else {
534 		struct vc4_exec_info *next;
535 
536 		vc4_move_job_to_render(dev, exec);
537 		next = vc4_first_bin_job(vc4);
538 
539 		/* We can't start the next bin job if the previous job had a
540 		 * different perfmon instance attached to it. The same goes
541 		 * if one of them had a perfmon attached to it and the other
542 		 * one doesn't.
543 		 */
544 		if (next && next->perfmon == exec->perfmon)
545 			goto again;
546 	}
547 }
548 
549 void
550 vc4_submit_next_render_job(struct drm_device *dev)
551 {
552 	struct vc4_dev *vc4 = to_vc4_dev(dev);
553 	struct vc4_exec_info *exec = vc4_first_render_job(vc4);
554 
555 	if (!exec)
556 		return;
557 
558 	if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4))
559 		return;
560 
561 	/* A previous RCL may have written to one of our textures, and
562 	 * our full cache flush at bin time may have occurred before
563 	 * that RCL completed.  Flush the texture cache now, but not
564 	 * the instructions or uniforms (since we don't write those
565 	 * from an RCL).
566 	 */
567 	vc4_flush_texture_caches(dev);
568 
569 	trace_vc4_submit_cl(dev, true, exec->seqno, exec->ct1ca, exec->ct1ea);
570 	submit_cl(dev, 1, exec->ct1ca, exec->ct1ea);
571 }
572 
573 void
574 vc4_move_job_to_render(struct drm_device *dev, struct vc4_exec_info *exec)
575 {
576 	struct vc4_dev *vc4 = to_vc4_dev(dev);
577 	bool was_empty = list_empty(&vc4->render_job_list);
578 
579 	if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4))
580 		return;
581 
582 	list_move_tail(&exec->head, &vc4->render_job_list);
583 	if (was_empty)
584 		vc4_submit_next_render_job(dev);
585 }
586 
587 static void
588 vc4_attach_fences(struct vc4_exec_info *exec)
589 {
590 	struct vc4_bo *bo;
591 	unsigned i;
592 
593 	for (i = 0; i < exec->bo_count; i++) {
594 		bo = to_vc4_bo(exec->bo[i]);
595 		dma_resv_add_fence(bo->base.base.resv, exec->fence,
596 				   DMA_RESV_USAGE_READ);
597 	}
598 
599 	for (i = 0; i < exec->rcl_write_bo_count; i++) {
600 		bo = to_vc4_bo(&exec->rcl_write_bo[i]->base);
601 		dma_resv_add_fence(bo->base.base.resv, exec->fence,
602 				   DMA_RESV_USAGE_WRITE);
603 	}
604 }
605 
606 /* Takes the reservation lock on all the BOs being referenced, so that
607  * at queue submit time we can update the reservations.
608  *
609  * We don't lock the RCL the tile alloc/state BOs, or overflow memory
610  * (all of which are on exec->unref_list).  They're entirely private
611  * to vc4, so we don't attach dma-buf fences to them.
612  */
613 static int
614 vc4_lock_bo_reservations(struct vc4_exec_info *exec,
615 			 struct drm_exec *exec_ctx)
616 {
617 	int ret;
618 
619 	/* Reserve space for our shared (read-only) fence references,
620 	 * before we commit the CL to the hardware.
621 	 */
622 	drm_exec_init(exec_ctx, DRM_EXEC_INTERRUPTIBLE_WAIT, exec->bo_count);
623 	drm_exec_until_all_locked(exec_ctx) {
624 		ret = drm_exec_prepare_array(exec_ctx, exec->bo,
625 					     exec->bo_count, 1);
626 	}
627 
628 	if (ret) {
629 		drm_exec_fini(exec_ctx);
630 		return ret;
631 	}
632 
633 	return 0;
634 }
635 
636 /* Queues a struct vc4_exec_info for execution.  If no job is
637  * currently executing, then submits it.
638  *
639  * Unlike most GPUs, our hardware only handles one command list at a
640  * time.  To queue multiple jobs at once, we'd need to edit the
641  * previous command list to have a jump to the new one at the end, and
642  * then bump the end address.  That's a change for a later date,
643  * though.
644  */
645 static int
646 vc4_queue_submit(struct drm_device *dev, struct vc4_exec_info *exec,
647 		 struct drm_exec *exec_ctx,
648 		 struct drm_syncobj *out_sync)
649 {
650 	struct vc4_dev *vc4 = to_vc4_dev(dev);
651 	struct vc4_exec_info *renderjob;
652 	uint64_t seqno;
653 	unsigned long irqflags;
654 	struct vc4_fence *fence;
655 
656 	fence = kzalloc_obj(*fence);
657 	if (!fence)
658 		return -ENOMEM;
659 	fence->dev = dev;
660 
661 	spin_lock_irqsave(&vc4->job_lock, irqflags);
662 
663 	seqno = ++vc4->emit_seqno;
664 	exec->seqno = seqno;
665 
666 	dma_fence_init(&fence->base, &vc4_fence_ops, &vc4->job_lock,
667 		       vc4->dma_fence_context, exec->seqno);
668 	fence->seqno = exec->seqno;
669 	exec->fence = &fence->base;
670 
671 	/* The job can complete and drop exec->fence as soon as job_lock is
672 	 * released, so hold our own reference.
673 	 */
674 	if (out_sync)
675 		dma_fence_get(&fence->base);
676 
677 	vc4_attach_fences(exec);
678 
679 	list_add_tail(&exec->head, &vc4->bin_job_list);
680 
681 	/* If no bin job was executing and if the render job (if any) has the
682 	 * same perfmon as our job attached to it (or if both jobs don't have
683 	 * perfmon activated), then kick ours off.  Otherwise, it'll get
684 	 * started when the previous job's flush/render done interrupt occurs.
685 	 */
686 	renderjob = vc4_first_render_job(vc4);
687 	if (vc4_first_bin_job(vc4) == exec &&
688 	    (!renderjob || renderjob->perfmon == exec->perfmon)) {
689 		vc4_submit_next_bin_job(dev);
690 		vc4_queue_hangcheck(dev);
691 	}
692 
693 	spin_unlock_irqrestore(&vc4->job_lock, irqflags);
694 
695 	drm_exec_fini(exec_ctx);
696 
697 	if (out_sync) {
698 		drm_syncobj_replace_fence(out_sync, &fence->base);
699 		dma_fence_put(&fence->base);
700 	}
701 
702 	return 0;
703 }
704 
705 /**
706  * vc4_cl_lookup_bos() - Sets up exec->bo[] with the GEM objects
707  * referenced by the job.
708  * @dev: DRM device
709  * @file_priv: DRM file for this fd
710  * @exec: V3D job being set up
711  *
712  * The command validator needs to reference BOs by their index within
713  * the submitted job's BO list.  This does the validation of the job's
714  * BO list and reference counting for the lifetime of the job.
715  */
716 static int
717 vc4_cl_lookup_bos(struct drm_device *dev,
718 		  struct drm_file *file_priv,
719 		  struct vc4_exec_info *exec)
720 {
721 	struct drm_vc4_submit_cl *args = exec->args;
722 	int ret = 0;
723 	int i;
724 
725 	exec->bo_count = args->bo_handle_count;
726 
727 	if (!exec->bo_count) {
728 		/* See comment on bo_index for why we have to check
729 		 * this.
730 		 */
731 		DRM_DEBUG("Rendering requires BOs to validate\n");
732 		return -EINVAL;
733 	}
734 
735 	ret = drm_gem_objects_lookup(file_priv, u64_to_user_ptr(args->bo_handles),
736 				     exec->bo_count, &exec->bo);
737 
738 	if (ret)
739 		goto fail_put_bo;
740 
741 	for (i = 0; i < exec->bo_count; i++) {
742 		ret = vc4_bo_inc_usecnt(to_vc4_bo(exec->bo[i]));
743 		if (ret)
744 			goto fail_dec_usecnt;
745 	}
746 
747 	return 0;
748 
749 fail_dec_usecnt:
750 	/* Decrease usecnt on acquired objects.
751 	 * We cannot rely on  vc4_complete_exec() to release resources here,
752 	 * because vc4_complete_exec() has no information about which BO has
753 	 * had its ->usecnt incremented.
754 	 * To make things easier we just free everything explicitly and set
755 	 * exec->bo to NULL so that vc4_complete_exec() skips the 'BO release'
756 	 * step.
757 	 */
758 	for (i-- ; i >= 0; i--)
759 		vc4_bo_dec_usecnt(to_vc4_bo(exec->bo[i]));
760 
761 fail_put_bo:
762 	/* Release any reference to acquired objects. */
763 	for (i = 0; i < exec->bo_count && exec->bo[i]; i++)
764 		drm_gem_object_put(exec->bo[i]);
765 
766 	kvfree(exec->bo);
767 	exec->bo = NULL;
768 	return ret;
769 }
770 
771 static int
772 vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec)
773 {
774 	struct drm_vc4_submit_cl *args = exec->args;
775 	struct vc4_dev *vc4 = to_vc4_dev(dev);
776 	void *temp = NULL;
777 	void *bin;
778 	int ret = 0;
779 	uint32_t bin_offset = 0;
780 	uint32_t shader_rec_offset = roundup(bin_offset + args->bin_cl_size,
781 					     16);
782 	uint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size;
783 	uint32_t exec_size = uniforms_offset + args->uniforms_size;
784 	uint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) *
785 					  args->shader_rec_count);
786 	struct vc4_bo *bo;
787 
788 	if (shader_rec_offset < args->bin_cl_size ||
789 	    uniforms_offset < shader_rec_offset ||
790 	    exec_size < uniforms_offset ||
791 	    args->shader_rec_count >= (UINT_MAX /
792 					  sizeof(struct vc4_shader_state)) ||
793 	    temp_size < exec_size) {
794 		DRM_DEBUG("overflow in exec arguments\n");
795 		ret = -EINVAL;
796 		goto fail;
797 	}
798 
799 	/* Allocate space where we'll store the copied in user command lists
800 	 * and shader records.
801 	 *
802 	 * We don't just copy directly into the BOs because we need to
803 	 * read the contents back for validation, and I think the
804 	 * bo->vaddr is uncached access.
805 	 */
806 	temp = kvmalloc_array(temp_size, 1, GFP_KERNEL);
807 	if (!temp) {
808 		drm_err(dev, "Failed to allocate storage for copying "
809 			"in bin/render CLs.\n");
810 		ret = -ENOMEM;
811 		goto fail;
812 	}
813 	bin = temp + bin_offset;
814 	exec->shader_rec_u = temp + shader_rec_offset;
815 	exec->uniforms_u = temp + uniforms_offset;
816 	exec->shader_state = temp + exec_size;
817 	exec->shader_state_size = args->shader_rec_count;
818 
819 	if (copy_from_user(bin,
820 			   u64_to_user_ptr(args->bin_cl),
821 			   args->bin_cl_size)) {
822 		ret = -EFAULT;
823 		goto fail;
824 	}
825 
826 	if (copy_from_user(exec->shader_rec_u,
827 			   u64_to_user_ptr(args->shader_rec),
828 			   args->shader_rec_size)) {
829 		ret = -EFAULT;
830 		goto fail;
831 	}
832 
833 	if (copy_from_user(exec->uniforms_u,
834 			   u64_to_user_ptr(args->uniforms),
835 			   args->uniforms_size)) {
836 		ret = -EFAULT;
837 		goto fail;
838 	}
839 
840 	bo = vc4_bo_create(dev, exec_size, true, VC4_BO_TYPE_BCL);
841 	if (IS_ERR(bo)) {
842 		drm_err(dev, "Couldn't allocate BO for binning\n");
843 		ret = PTR_ERR(bo);
844 		goto fail;
845 	}
846 	exec->exec_bo = &bo->base;
847 
848 	list_add_tail(&to_vc4_bo(&exec->exec_bo->base)->unref_head,
849 		      &exec->unref_list);
850 
851 	exec->ct0ca = exec->exec_bo->dma_addr + bin_offset;
852 
853 	exec->bin_u = bin;
854 
855 	exec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset;
856 	exec->shader_rec_p = exec->exec_bo->dma_addr + shader_rec_offset;
857 	exec->shader_rec_size = args->shader_rec_size;
858 
859 	exec->uniforms_v = exec->exec_bo->vaddr + uniforms_offset;
860 	exec->uniforms_p = exec->exec_bo->dma_addr + uniforms_offset;
861 	exec->uniforms_size = args->uniforms_size;
862 
863 	ret = vc4_validate_bin_cl(dev,
864 				  exec->exec_bo->vaddr + bin_offset,
865 				  bin,
866 				  exec);
867 	if (ret)
868 		goto fail;
869 
870 	ret = vc4_validate_shader_recs(dev, exec);
871 	if (ret)
872 		goto fail;
873 
874 	if (exec->found_tile_binning_mode_config_packet) {
875 		ret = vc4_v3d_bin_bo_get(vc4, &exec->bin_bo_used);
876 		if (ret)
877 			goto fail;
878 	}
879 
880 fail:
881 	kvfree(temp);
882 	return ret;
883 }
884 
885 static void
886 vc4_complete_exec(struct drm_device *dev, struct vc4_exec_info *exec)
887 {
888 	struct vc4_dev *vc4 = to_vc4_dev(dev);
889 	unsigned long irqflags;
890 	unsigned i;
891 
892 	/* If we got force-completed because of GPU reset rather than
893 	 * through our IRQ handler, signal the fence now.
894 	 */
895 	if (exec->fence) {
896 		dma_fence_signal(exec->fence);
897 		dma_fence_put(exec->fence);
898 	}
899 
900 	if (exec->bo) {
901 		for (i = 0; i < exec->bo_count; i++) {
902 			struct vc4_bo *bo = to_vc4_bo(exec->bo[i]);
903 
904 			vc4_bo_dec_usecnt(bo);
905 			drm_gem_object_put(exec->bo[i]);
906 		}
907 		kvfree(exec->bo);
908 	}
909 
910 	while (!list_empty(&exec->unref_list)) {
911 		struct vc4_bo *bo = list_first_entry(&exec->unref_list,
912 						     struct vc4_bo, unref_head);
913 		list_del(&bo->unref_head);
914 		drm_gem_object_put(&bo->base.base);
915 	}
916 
917 	/* Free up the allocation of any bin slots we used. Jobs that ran to
918 	 * completion had their slots released in vc4_irq_finish_render_job().
919 	 * Only jobs that never completed still have slots to be released here.
920 	 */
921 	spin_lock_irqsave(&vc4->job_lock, irqflags);
922 	vc4->bin_alloc_used &= ~exec->bin_slots;
923 	spin_unlock_irqrestore(&vc4->job_lock, irqflags);
924 
925 	/* Let anyone waiting on the binner pool retry. */
926 	wake_up_all(&vc4->job_wait_queue);
927 
928 	/* Release the reference on the binner BO if needed. */
929 	if (exec->bin_bo_used)
930 		vc4_v3d_bin_bo_put(vc4);
931 
932 	/* Release the reference we had on the perf monitor. */
933 	vc4_perfmon_put(exec->perfmon);
934 
935 	vc4_v3d_pm_put(vc4);
936 
937 	kfree(exec);
938 }
939 
940 void
941 vc4_job_handle_completed(struct vc4_dev *vc4)
942 {
943 	unsigned long irqflags;
944 
945 	if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4))
946 		return;
947 
948 	spin_lock_irqsave(&vc4->job_lock, irqflags);
949 	while (!list_empty(&vc4->job_done_list)) {
950 		struct vc4_exec_info *exec =
951 			list_first_entry(&vc4->job_done_list,
952 					 struct vc4_exec_info, head);
953 		list_del(&exec->head);
954 
955 		spin_unlock_irqrestore(&vc4->job_lock, irqflags);
956 		vc4_complete_exec(&vc4->base, exec);
957 		spin_lock_irqsave(&vc4->job_lock, irqflags);
958 	}
959 
960 	spin_unlock_irqrestore(&vc4->job_lock, irqflags);
961 }
962 
963 /* Scheduled when any job has been completed, this walks the list of
964  * jobs that had completed and unrefs their BOs and frees their exec
965  * structs.
966  */
967 static void
968 vc4_job_done_work(struct work_struct *work)
969 {
970 	struct vc4_dev *vc4 =
971 		container_of(work, struct vc4_dev, job_done_work);
972 
973 	vc4_job_handle_completed(vc4);
974 }
975 
976 static int
977 vc4_wait_for_seqno_ioctl_helper(struct drm_device *dev,
978 				uint64_t seqno,
979 				uint64_t *timeout_ns)
980 {
981 	unsigned long start = jiffies;
982 	int ret = vc4_wait_for_seqno(dev, seqno, *timeout_ns, true);
983 
984 	if ((ret == -EINTR || ret == -ERESTARTSYS) && *timeout_ns != ~0ull) {
985 		uint64_t delta = jiffies_to_nsecs(jiffies - start);
986 
987 		if (*timeout_ns >= delta)
988 			*timeout_ns -= delta;
989 	}
990 
991 	return ret;
992 }
993 
994 int
995 vc4_wait_seqno_ioctl(struct drm_device *dev, void *data,
996 		     struct drm_file *file_priv)
997 {
998 	struct vc4_dev *vc4 = to_vc4_dev(dev);
999 	struct drm_vc4_wait_seqno *args = data;
1000 
1001 	if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4))
1002 		return -ENODEV;
1003 
1004 	return vc4_wait_for_seqno_ioctl_helper(dev, args->seqno,
1005 					       &args->timeout_ns);
1006 }
1007 
1008 int
1009 vc4_wait_bo_ioctl(struct drm_device *dev, void *data,
1010 		  struct drm_file *file_priv)
1011 {
1012 	struct vc4_dev *vc4 = to_vc4_dev(dev);
1013 	int ret;
1014 	struct drm_vc4_wait_bo *args = data;
1015 	unsigned long timeout_jiffies =
1016 		drm_timeout_rel_to_jiffies(args->timeout_ns);
1017 	ktime_t start = ktime_get();
1018 	u64 delta_ns;
1019 
1020 	if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4))
1021 		return -ENODEV;
1022 
1023 	if (args->pad != 0)
1024 		return -EINVAL;
1025 
1026 	ret = drm_gem_dma_resv_wait(file_priv, args->handle,
1027 				    true, timeout_jiffies);
1028 
1029 	/* Decrement the user's timeout, in case we got interrupted
1030 	 * such that the ioctl will be restarted.
1031 	 */
1032 	delta_ns = ktime_to_ns(ktime_sub(ktime_get(), start));
1033 	if (delta_ns < args->timeout_ns)
1034 		args->timeout_ns -= delta_ns;
1035 	else
1036 		args->timeout_ns = 0;
1037 
1038 	return ret;
1039 }
1040 
1041 /**
1042  * vc4_submit_cl_ioctl() - Submits a job (frame) to the VC4.
1043  * @dev: DRM device
1044  * @data: ioctl argument
1045  * @file_priv: DRM file for this fd
1046  *
1047  * This is the main entrypoint for userspace to submit a 3D frame to
1048  * the GPU.  Userspace provides the binner command list (if
1049  * applicable), and the kernel sets up the render command list to draw
1050  * to the framebuffer described in the ioctl, using the command lists
1051  * that the 3D engine's binner will produce.
1052  */
1053 int
1054 vc4_submit_cl_ioctl(struct drm_device *dev, void *data,
1055 		    struct drm_file *file_priv)
1056 {
1057 	struct vc4_dev *vc4 = to_vc4_dev(dev);
1058 	struct vc4_file *vc4file = file_priv->driver_priv;
1059 	struct drm_vc4_submit_cl *args = data;
1060 	struct drm_syncobj *out_sync = NULL;
1061 	struct vc4_exec_info *exec;
1062 	struct drm_exec exec_ctx;
1063 	struct dma_fence *in_fence;
1064 	int ret = 0;
1065 
1066 	trace_vc4_submit_cl_ioctl(dev, args->bin_cl_size,
1067 				  args->shader_rec_size,
1068 				  args->bo_handle_count);
1069 
1070 	if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4))
1071 		return -ENODEV;
1072 
1073 	if (!vc4->v3d) {
1074 		DRM_DEBUG("VC4_SUBMIT_CL with no VC4 V3D probed\n");
1075 		return -ENODEV;
1076 	}
1077 
1078 	if ((args->flags & ~(VC4_SUBMIT_CL_USE_CLEAR_COLOR |
1079 			     VC4_SUBMIT_CL_FIXED_RCL_ORDER |
1080 			     VC4_SUBMIT_CL_RCL_ORDER_INCREASING_X |
1081 			     VC4_SUBMIT_CL_RCL_ORDER_INCREASING_Y)) != 0) {
1082 		DRM_DEBUG("Unknown flags: 0x%02x\n", args->flags);
1083 		return -EINVAL;
1084 	}
1085 
1086 	if (args->pad2 != 0) {
1087 		DRM_DEBUG("Invalid pad: 0x%08x\n", args->pad2);
1088 		return -EINVAL;
1089 	}
1090 
1091 	exec = kzalloc_objs(*exec, 1);
1092 	if (!exec)
1093 		return -ENOMEM;
1094 
1095 	exec->dev = vc4;
1096 
1097 	ret = vc4_v3d_pm_get(vc4);
1098 	if (ret) {
1099 		kfree(exec);
1100 		return ret;
1101 	}
1102 
1103 	exec->args = args;
1104 	INIT_LIST_HEAD(&exec->unref_list);
1105 
1106 	ret = vc4_cl_lookup_bos(dev, file_priv, exec);
1107 	if (ret)
1108 		goto fail;
1109 
1110 	if (args->perfmonid) {
1111 		exec->perfmon = vc4_perfmon_find(vc4file,
1112 						 args->perfmonid);
1113 		if (!exec->perfmon) {
1114 			ret = -ENOENT;
1115 			goto fail;
1116 		}
1117 	}
1118 
1119 	if (args->in_sync) {
1120 		ret = drm_syncobj_find_fence(file_priv, args->in_sync,
1121 					     0, 0, &in_fence);
1122 		if (ret)
1123 			goto fail;
1124 
1125 		/* When the fence (or fence array) is exclusively from our
1126 		 * context we can skip the wait since jobs are executed in
1127 		 * order of their submission through this ioctl and this can
1128 		 * only have fences from a prior job.
1129 		 */
1130 		if (!dma_fence_match_context(in_fence,
1131 					     vc4->dma_fence_context)) {
1132 			ret = dma_fence_wait(in_fence, true);
1133 			if (ret) {
1134 				dma_fence_put(in_fence);
1135 				goto fail;
1136 			}
1137 		}
1138 
1139 		dma_fence_put(in_fence);
1140 	}
1141 
1142 	if (exec->args->bin_cl_size != 0) {
1143 		ret = vc4_get_bcl(dev, exec);
1144 		if (ret)
1145 			goto fail;
1146 	} else {
1147 		exec->ct0ca = 0;
1148 		exec->ct0ea = 0;
1149 	}
1150 
1151 	ret = vc4_get_rcl(dev, exec);
1152 	if (ret)
1153 		goto fail;
1154 
1155 	ret = vc4_lock_bo_reservations(exec, &exec_ctx);
1156 	if (ret)
1157 		goto fail;
1158 
1159 	if (args->out_sync) {
1160 		out_sync = drm_syncobj_find(file_priv, args->out_sync);
1161 		if (!out_sync) {
1162 			ret = -EINVAL;
1163 			goto fail_unreserve;
1164 		}
1165 
1166 		/* We replace the fence in out_sync in vc4_queue_submit since
1167 		 * the render job could execute immediately after that call.
1168 		 * If it finishes before our ioctl processing resumes the
1169 		 * render job fence could already have been freed.
1170 		 */
1171 	}
1172 
1173 	/* Clear this out of the struct we'll be putting in the queue,
1174 	 * since it's part of our stack.
1175 	 */
1176 	exec->args = NULL;
1177 
1178 	ret = vc4_queue_submit(dev, exec, &exec_ctx, out_sync);
1179 
1180 	/* The syncobj isn't part of the exec data and we need to free our
1181 	 * reference even if job submission failed.
1182 	 */
1183 	if (out_sync)
1184 		drm_syncobj_put(out_sync);
1185 
1186 	if (ret)
1187 		goto fail_unreserve;
1188 
1189 	/* Return the seqno for our job. */
1190 	args->seqno = vc4->emit_seqno;
1191 
1192 	return 0;
1193 
1194 fail_unreserve:
1195 	drm_exec_fini(&exec_ctx);
1196 fail:
1197 	vc4_complete_exec(&vc4->base, exec);
1198 
1199 	return ret;
1200 }
1201 
1202 static void vc4_gem_destroy(struct drm_device *dev, void *unused);
1203 int vc4_gem_init(struct drm_device *dev)
1204 {
1205 	struct vc4_dev *vc4 = to_vc4_dev(dev);
1206 	int ret;
1207 
1208 	if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4))
1209 		return -ENODEV;
1210 
1211 	vc4->dma_fence_context = dma_fence_context_alloc(1);
1212 
1213 	INIT_LIST_HEAD(&vc4->bin_job_list);
1214 	INIT_LIST_HEAD(&vc4->render_job_list);
1215 	INIT_LIST_HEAD(&vc4->job_done_list);
1216 	spin_lock_init(&vc4->job_lock);
1217 
1218 	INIT_WORK(&vc4->hangcheck.reset_work, vc4_reset_work);
1219 	timer_setup(&vc4->hangcheck.timer, vc4_hangcheck_elapsed, 0);
1220 
1221 	INIT_WORK(&vc4->job_done_work, vc4_job_done_work);
1222 
1223 	INIT_LIST_HEAD(&vc4->purgeable.list);
1224 
1225 	ret = drmm_mutex_init(dev, &vc4->purgeable.lock);
1226 	if (ret)
1227 		return ret;
1228 
1229 	return drmm_add_action_or_reset(dev, vc4_gem_destroy, NULL);
1230 }
1231 
1232 static void vc4_gem_destroy(struct drm_device *dev, void *unused)
1233 {
1234 	struct vc4_dev *vc4 = to_vc4_dev(dev);
1235 
1236 	/* Waiting for exec to finish would need to be done before
1237 	 * unregistering V3D.
1238 	 */
1239 	WARN_ON(vc4->emit_seqno != vc4->finished_seqno);
1240 
1241 	/* V3D should already have disabled its interrupt and cleared
1242 	 * the overflow allocation registers.  Now free the object.
1243 	 */
1244 	if (vc4->bin_bo) {
1245 		drm_gem_object_put(&vc4->bin_bo->base.base);
1246 		vc4->bin_bo = NULL;
1247 	}
1248 
1249 	if (vc4->hang_state)
1250 		vc4_free_hang_state(dev, vc4->hang_state);
1251 }
1252 
1253 int vc4_gem_madvise_ioctl(struct drm_device *dev, void *data,
1254 			  struct drm_file *file_priv)
1255 {
1256 	struct vc4_dev *vc4 = to_vc4_dev(dev);
1257 	struct drm_vc4_gem_madvise *args = data;
1258 	struct drm_gem_object *gem_obj;
1259 	struct vc4_bo *bo;
1260 	int ret;
1261 
1262 	if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4))
1263 		return -ENODEV;
1264 
1265 	switch (args->madv) {
1266 	case VC4_MADV_DONTNEED:
1267 	case VC4_MADV_WILLNEED:
1268 		break;
1269 	default:
1270 		return -EINVAL;
1271 	}
1272 
1273 	if (args->pad != 0)
1274 		return -EINVAL;
1275 
1276 	gem_obj = drm_gem_object_lookup(file_priv, args->handle);
1277 	if (!gem_obj) {
1278 		DRM_DEBUG("Failed to look up GEM BO %d\n", args->handle);
1279 		return -ENOENT;
1280 	}
1281 
1282 	bo = to_vc4_bo(gem_obj);
1283 
1284 	/* Only BOs exposed to userspace can be purged. */
1285 	if (bo->madv == __VC4_MADV_NOTSUPP) {
1286 		DRM_DEBUG("madvise not supported on this BO\n");
1287 		ret = -EINVAL;
1288 		goto out_put_gem;
1289 	}
1290 
1291 	/* Not sure it's safe to purge imported BOs. Let's just assume it's
1292 	 * not until proven otherwise.
1293 	 */
1294 	if (drm_gem_is_imported(gem_obj)) {
1295 		DRM_DEBUG("madvise not supported on imported BOs\n");
1296 		ret = -EINVAL;
1297 		goto out_put_gem;
1298 	}
1299 
1300 	mutex_lock(&bo->madv_lock);
1301 
1302 	if (args->madv == VC4_MADV_DONTNEED && bo->madv == VC4_MADV_WILLNEED &&
1303 	    !refcount_read(&bo->usecnt)) {
1304 		/* If the BO is about to be marked as purgeable, is not used
1305 		 * and is not already purgeable or purged, add it to the
1306 		 * purgeable list.
1307 		 */
1308 		vc4_bo_add_to_purgeable_pool(bo);
1309 	} else if (args->madv == VC4_MADV_WILLNEED &&
1310 		   bo->madv == VC4_MADV_DONTNEED &&
1311 		   !refcount_read(&bo->usecnt)) {
1312 		/* The BO has not been purged yet, just remove it from
1313 		 * the purgeable list.
1314 		 */
1315 		vc4_bo_remove_from_purgeable_pool(bo);
1316 	}
1317 
1318 	/* Save the purged state. */
1319 	args->retained = bo->madv != __VC4_MADV_PURGED;
1320 
1321 	/* Update internal madv state only if the bo was not purged. */
1322 	if (bo->madv != __VC4_MADV_PURGED)
1323 		bo->madv = args->madv;
1324 
1325 	mutex_unlock(&bo->madv_lock);
1326 
1327 	ret = 0;
1328 
1329 out_put_gem:
1330 	drm_gem_object_put(gem_obj);
1331 
1332 	return ret;
1333 }
1334