1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2013 Red Hat
4  * Author: Rob Clark <robdclark@gmail.com>
5  *
6  * Copyright (c) 2014 The Linux Foundation. All rights reserved.
7  */
8 
9 #include <linux/ascii85.h>
10 #include <linux/interconnect.h>
11 #include <linux/qcom_scm.h>
12 #include <linux/kernel.h>
13 #include <linux/of_address.h>
14 #include <linux/pm_opp.h>
15 #include <linux/slab.h>
16 #include <linux/soc/qcom/mdt_loader.h>
17 #include <linux/nvmem-consumer.h>
18 #include <soc/qcom/ocmem.h>
19 #include "adreno_gpu.h"
20 #include "a6xx_gpu.h"
21 #include "msm_gem.h"
22 #include "msm_mmu.h"
23 
24 static u64 address_space_size = 0;
25 MODULE_PARM_DESC(address_space_size, "Override for size of processes private GPU address space");
26 module_param(address_space_size, ullong, 0600);
27 
28 static bool zap_available = true;
29 
30 static int zap_shader_load_mdt(struct msm_gpu *gpu, const char *fwname,
31 		u32 pasid)
32 {
33 	struct device *dev = &gpu->pdev->dev;
34 	const struct firmware *fw;
35 	const char *signed_fwname = NULL;
36 	struct device_node *np, *mem_np;
37 	struct resource r;
38 	phys_addr_t mem_phys;
39 	ssize_t mem_size;
40 	void *mem_region = NULL;
41 	int ret;
42 
43 	if (!IS_ENABLED(CONFIG_ARCH_QCOM)) {
44 		zap_available = false;
45 		return -EINVAL;
46 	}
47 
48 	np = of_get_child_by_name(dev->of_node, "zap-shader");
49 	if (!np) {
50 		zap_available = false;
51 		return -ENODEV;
52 	}
53 
54 	mem_np = of_parse_phandle(np, "memory-region", 0);
55 	of_node_put(np);
56 	if (!mem_np) {
57 		zap_available = false;
58 		return -EINVAL;
59 	}
60 
61 	ret = of_address_to_resource(mem_np, 0, &r);
62 	of_node_put(mem_np);
63 	if (ret)
64 		return ret;
65 
66 	mem_phys = r.start;
67 
68 	/*
69 	 * Check for a firmware-name property.  This is the new scheme
70 	 * to handle firmware that may be signed with device specific
71 	 * keys, allowing us to have a different zap fw path for different
72 	 * devices.
73 	 *
74 	 * If the firmware-name property is found, we bypass the
75 	 * adreno_request_fw() mechanism, because we don't need to handle
76 	 * the /lib/firmware/qcom/... vs /lib/firmware/... case.
77 	 *
78 	 * If the firmware-name property is not found, for backwards
79 	 * compatibility we fall back to the fwname from the gpulist
80 	 * table.
81 	 */
82 	of_property_read_string_index(np, "firmware-name", 0, &signed_fwname);
83 	if (signed_fwname) {
84 		fwname = signed_fwname;
85 		ret = request_firmware_direct(&fw, fwname, gpu->dev->dev);
86 		if (ret)
87 			fw = ERR_PTR(ret);
88 	} else if (fwname) {
89 		/* Request the MDT file from the default location: */
90 		fw = adreno_request_fw(to_adreno_gpu(gpu), fwname);
91 	} else {
92 		/*
93 		 * For new targets, we require the firmware-name property,
94 		 * if a zap-shader is required, rather than falling back
95 		 * to a firmware name specified in gpulist.
96 		 *
97 		 * Because the firmware is signed with a (potentially)
98 		 * device specific key, having the name come from gpulist
99 		 * was a bad idea, and is only provided for backwards
100 		 * compatibility for older targets.
101 		 */
102 		return -ENODEV;
103 	}
104 
105 	if (IS_ERR(fw)) {
106 		DRM_DEV_ERROR(dev, "Unable to load %s\n", fwname);
107 		return PTR_ERR(fw);
108 	}
109 
110 	/* Figure out how much memory we need */
111 	mem_size = qcom_mdt_get_size(fw);
112 	if (mem_size < 0) {
113 		ret = mem_size;
114 		goto out;
115 	}
116 
117 	if (mem_size > resource_size(&r)) {
118 		DRM_DEV_ERROR(dev,
119 			"memory region is too small to load the MDT\n");
120 		ret = -E2BIG;
121 		goto out;
122 	}
123 
124 	/* Allocate memory for the firmware image */
125 	mem_region = memremap(mem_phys, mem_size,  MEMREMAP_WC);
126 	if (!mem_region) {
127 		ret = -ENOMEM;
128 		goto out;
129 	}
130 
131 	/*
132 	 * Load the rest of the MDT
133 	 *
134 	 * Note that we could be dealing with two different paths, since
135 	 * with upstream linux-firmware it would be in a qcom/ subdir..
136 	 * adreno_request_fw() handles this, but qcom_mdt_load() does
137 	 * not.  But since we've already gotten through adreno_request_fw()
138 	 * we know which of the two cases it is:
139 	 */
140 	if (signed_fwname || (to_adreno_gpu(gpu)->fwloc == FW_LOCATION_LEGACY)) {
141 		ret = qcom_mdt_load(dev, fw, fwname, pasid,
142 				mem_region, mem_phys, mem_size, NULL);
143 	} else {
144 		char *newname;
145 
146 		newname = kasprintf(GFP_KERNEL, "qcom/%s", fwname);
147 
148 		ret = qcom_mdt_load(dev, fw, newname, pasid,
149 				mem_region, mem_phys, mem_size, NULL);
150 		kfree(newname);
151 	}
152 	if (ret)
153 		goto out;
154 
155 	/* Send the image to the secure world */
156 	ret = qcom_scm_pas_auth_and_reset(pasid);
157 
158 	/*
159 	 * If the scm call returns -EOPNOTSUPP we assume that this target
160 	 * doesn't need/support the zap shader so quietly fail
161 	 */
162 	if (ret == -EOPNOTSUPP)
163 		zap_available = false;
164 	else if (ret)
165 		DRM_DEV_ERROR(dev, "Unable to authorize the image\n");
166 
167 out:
168 	if (mem_region)
169 		memunmap(mem_region);
170 
171 	release_firmware(fw);
172 
173 	return ret;
174 }
175 
176 int adreno_zap_shader_load(struct msm_gpu *gpu, u32 pasid)
177 {
178 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
179 	struct platform_device *pdev = gpu->pdev;
180 
181 	/* Short cut if we determine the zap shader isn't available/needed */
182 	if (!zap_available)
183 		return -ENODEV;
184 
185 	/* We need SCM to be able to load the firmware */
186 	if (!qcom_scm_is_available()) {
187 		DRM_DEV_ERROR(&pdev->dev, "SCM is not available\n");
188 		return -EPROBE_DEFER;
189 	}
190 
191 	return zap_shader_load_mdt(gpu, adreno_gpu->info->zapfw, pasid);
192 }
193 
194 struct msm_gem_address_space *
195 adreno_create_address_space(struct msm_gpu *gpu,
196 			    struct platform_device *pdev)
197 {
198 	return adreno_iommu_create_address_space(gpu, pdev, 0);
199 }
200 
201 struct msm_gem_address_space *
202 adreno_iommu_create_address_space(struct msm_gpu *gpu,
203 				  struct platform_device *pdev,
204 				  unsigned long quirks)
205 {
206 	struct iommu_domain_geometry *geometry;
207 	struct msm_mmu *mmu;
208 	struct msm_gem_address_space *aspace;
209 	u64 start, size;
210 
211 	mmu = msm_iommu_new(&pdev->dev, quirks);
212 	if (IS_ERR_OR_NULL(mmu))
213 		return ERR_CAST(mmu);
214 
215 	geometry = msm_iommu_get_geometry(mmu);
216 	if (IS_ERR(geometry))
217 		return ERR_CAST(geometry);
218 
219 	/*
220 	 * Use the aperture start or SZ_16M, whichever is greater. This will
221 	 * ensure that we align with the allocated pagetable range while still
222 	 * allowing room in the lower 32 bits for GMEM and whatnot
223 	 */
224 	start = max_t(u64, SZ_16M, geometry->aperture_start);
225 	size = geometry->aperture_end - start + 1;
226 
227 	aspace = msm_gem_address_space_create(mmu, "gpu",
228 		start & GENMASK_ULL(48, 0), size);
229 
230 	if (IS_ERR(aspace) && !IS_ERR(mmu))
231 		mmu->funcs->destroy(mmu);
232 
233 	return aspace;
234 }
235 
236 u64 adreno_private_address_space_size(struct msm_gpu *gpu)
237 {
238 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
239 
240 	if (address_space_size)
241 		return address_space_size;
242 
243 	if (adreno_gpu->info->address_space_size)
244 		return adreno_gpu->info->address_space_size;
245 
246 	return SZ_4G;
247 }
248 
249 int adreno_get_param(struct msm_gpu *gpu, struct msm_file_private *ctx,
250 		     uint32_t param, uint64_t *value, uint32_t *len)
251 {
252 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
253 
254 	/* No pointer params yet */
255 	if (*len != 0)
256 		return -EINVAL;
257 
258 	switch (param) {
259 	case MSM_PARAM_GPU_ID:
260 		*value = adreno_gpu->info->revn;
261 		return 0;
262 	case MSM_PARAM_GMEM_SIZE:
263 		*value = adreno_gpu->gmem;
264 		return 0;
265 	case MSM_PARAM_GMEM_BASE:
266 		*value = !adreno_is_a650_family(adreno_gpu) ? 0x100000 : 0;
267 		return 0;
268 	case MSM_PARAM_CHIP_ID:
269 		*value =  (uint64_t)adreno_gpu->rev.patchid |
270 			 ((uint64_t)adreno_gpu->rev.minor << 8) |
271 			 ((uint64_t)adreno_gpu->rev.major << 16) |
272 			 ((uint64_t)adreno_gpu->rev.core  << 24);
273 		if (!adreno_gpu->info->revn)
274 			*value |= ((uint64_t) adreno_gpu->speedbin) << 32;
275 		return 0;
276 	case MSM_PARAM_MAX_FREQ:
277 		*value = adreno_gpu->base.fast_rate;
278 		return 0;
279 	case MSM_PARAM_TIMESTAMP:
280 		if (adreno_gpu->funcs->get_timestamp) {
281 			int ret;
282 
283 			pm_runtime_get_sync(&gpu->pdev->dev);
284 			ret = adreno_gpu->funcs->get_timestamp(gpu, value);
285 			pm_runtime_put_autosuspend(&gpu->pdev->dev);
286 
287 			return ret;
288 		}
289 		return -EINVAL;
290 	case MSM_PARAM_PRIORITIES:
291 		*value = gpu->nr_rings * NR_SCHED_PRIORITIES;
292 		return 0;
293 	case MSM_PARAM_PP_PGTABLE:
294 		*value = 0;
295 		return 0;
296 	case MSM_PARAM_FAULTS:
297 		if (ctx->aspace)
298 			*value = gpu->global_faults + ctx->aspace->faults;
299 		else
300 			*value = gpu->global_faults;
301 		return 0;
302 	case MSM_PARAM_SUSPENDS:
303 		*value = gpu->suspend_count;
304 		return 0;
305 	case MSM_PARAM_VA_START:
306 		if (ctx->aspace == gpu->aspace)
307 			return -EINVAL;
308 		*value = ctx->aspace->va_start;
309 		return 0;
310 	case MSM_PARAM_VA_SIZE:
311 		if (ctx->aspace == gpu->aspace)
312 			return -EINVAL;
313 		*value = ctx->aspace->va_size;
314 		return 0;
315 	default:
316 		DBG("%s: invalid param: %u", gpu->name, param);
317 		return -EINVAL;
318 	}
319 }
320 
321 int adreno_set_param(struct msm_gpu *gpu, struct msm_file_private *ctx,
322 		     uint32_t param, uint64_t value, uint32_t len)
323 {
324 	switch (param) {
325 	case MSM_PARAM_COMM:
326 	case MSM_PARAM_CMDLINE:
327 		/* kstrdup_quotable_cmdline() limits to PAGE_SIZE, so
328 		 * that should be a reasonable upper bound
329 		 */
330 		if (len > PAGE_SIZE)
331 			return -EINVAL;
332 		break;
333 	default:
334 		if (len != 0)
335 			return -EINVAL;
336 	}
337 
338 	switch (param) {
339 	case MSM_PARAM_COMM:
340 	case MSM_PARAM_CMDLINE: {
341 		char *str, **paramp;
342 
343 		str = kmalloc(len + 1, GFP_KERNEL);
344 		if (!str)
345 			return -ENOMEM;
346 
347 		if (copy_from_user(str, u64_to_user_ptr(value), len)) {
348 			kfree(str);
349 			return -EFAULT;
350 		}
351 
352 		/* Ensure string is null terminated: */
353 		str[len] = '\0';
354 
355 		if (param == MSM_PARAM_COMM) {
356 			paramp = &ctx->comm;
357 		} else {
358 			paramp = &ctx->cmdline;
359 		}
360 
361 		kfree(*paramp);
362 		*paramp = str;
363 
364 		return 0;
365 	}
366 	case MSM_PARAM_SYSPROF:
367 		if (!capable(CAP_SYS_ADMIN))
368 			return -EPERM;
369 		return msm_file_private_set_sysprof(ctx, gpu, value);
370 	default:
371 		DBG("%s: invalid param: %u", gpu->name, param);
372 		return -EINVAL;
373 	}
374 }
375 
376 const struct firmware *
377 adreno_request_fw(struct adreno_gpu *adreno_gpu, const char *fwname)
378 {
379 	struct drm_device *drm = adreno_gpu->base.dev;
380 	const struct firmware *fw = NULL;
381 	char *newname;
382 	int ret;
383 
384 	newname = kasprintf(GFP_KERNEL, "qcom/%s", fwname);
385 	if (!newname)
386 		return ERR_PTR(-ENOMEM);
387 
388 	/*
389 	 * Try first to load from qcom/$fwfile using a direct load (to avoid
390 	 * a potential timeout waiting for usermode helper)
391 	 */
392 	if ((adreno_gpu->fwloc == FW_LOCATION_UNKNOWN) ||
393 	    (adreno_gpu->fwloc == FW_LOCATION_NEW)) {
394 
395 		ret = request_firmware_direct(&fw, newname, drm->dev);
396 		if (!ret) {
397 			DRM_DEV_INFO(drm->dev, "loaded %s from new location\n",
398 				newname);
399 			adreno_gpu->fwloc = FW_LOCATION_NEW;
400 			goto out;
401 		} else if (adreno_gpu->fwloc != FW_LOCATION_UNKNOWN) {
402 			DRM_DEV_ERROR(drm->dev, "failed to load %s: %d\n",
403 				newname, ret);
404 			fw = ERR_PTR(ret);
405 			goto out;
406 		}
407 	}
408 
409 	/*
410 	 * Then try the legacy location without qcom/ prefix
411 	 */
412 	if ((adreno_gpu->fwloc == FW_LOCATION_UNKNOWN) ||
413 	    (adreno_gpu->fwloc == FW_LOCATION_LEGACY)) {
414 
415 		ret = request_firmware_direct(&fw, fwname, drm->dev);
416 		if (!ret) {
417 			DRM_DEV_INFO(drm->dev, "loaded %s from legacy location\n",
418 				newname);
419 			adreno_gpu->fwloc = FW_LOCATION_LEGACY;
420 			goto out;
421 		} else if (adreno_gpu->fwloc != FW_LOCATION_UNKNOWN) {
422 			DRM_DEV_ERROR(drm->dev, "failed to load %s: %d\n",
423 				fwname, ret);
424 			fw = ERR_PTR(ret);
425 			goto out;
426 		}
427 	}
428 
429 	/*
430 	 * Finally fall back to request_firmware() for cases where the
431 	 * usermode helper is needed (I think mainly android)
432 	 */
433 	if ((adreno_gpu->fwloc == FW_LOCATION_UNKNOWN) ||
434 	    (adreno_gpu->fwloc == FW_LOCATION_HELPER)) {
435 
436 		ret = request_firmware(&fw, newname, drm->dev);
437 		if (!ret) {
438 			DRM_DEV_INFO(drm->dev, "loaded %s with helper\n",
439 				newname);
440 			adreno_gpu->fwloc = FW_LOCATION_HELPER;
441 			goto out;
442 		} else if (adreno_gpu->fwloc != FW_LOCATION_UNKNOWN) {
443 			DRM_DEV_ERROR(drm->dev, "failed to load %s: %d\n",
444 				newname, ret);
445 			fw = ERR_PTR(ret);
446 			goto out;
447 		}
448 	}
449 
450 	DRM_DEV_ERROR(drm->dev, "failed to load %s\n", fwname);
451 	fw = ERR_PTR(-ENOENT);
452 out:
453 	kfree(newname);
454 	return fw;
455 }
456 
457 int adreno_load_fw(struct adreno_gpu *adreno_gpu)
458 {
459 	int i;
460 
461 	for (i = 0; i < ARRAY_SIZE(adreno_gpu->info->fw); i++) {
462 		const struct firmware *fw;
463 
464 		if (!adreno_gpu->info->fw[i])
465 			continue;
466 
467 		/* Skip if the firmware has already been loaded */
468 		if (adreno_gpu->fw[i])
469 			continue;
470 
471 		fw = adreno_request_fw(adreno_gpu, adreno_gpu->info->fw[i]);
472 		if (IS_ERR(fw))
473 			return PTR_ERR(fw);
474 
475 		adreno_gpu->fw[i] = fw;
476 	}
477 
478 	return 0;
479 }
480 
481 struct drm_gem_object *adreno_fw_create_bo(struct msm_gpu *gpu,
482 		const struct firmware *fw, u64 *iova)
483 {
484 	struct drm_gem_object *bo;
485 	void *ptr;
486 
487 	ptr = msm_gem_kernel_new(gpu->dev, fw->size - 4,
488 		MSM_BO_WC | MSM_BO_GPU_READONLY, gpu->aspace, &bo, iova);
489 
490 	if (IS_ERR(ptr))
491 		return ERR_CAST(ptr);
492 
493 	memcpy(ptr, &fw->data[4], fw->size - 4);
494 
495 	msm_gem_put_vaddr(bo);
496 
497 	return bo;
498 }
499 
500 int adreno_hw_init(struct msm_gpu *gpu)
501 {
502 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
503 	int ret, i;
504 
505 	VERB("%s", gpu->name);
506 
507 	ret = adreno_load_fw(adreno_gpu);
508 	if (ret)
509 		return ret;
510 
511 	for (i = 0; i < gpu->nr_rings; i++) {
512 		struct msm_ringbuffer *ring = gpu->rb[i];
513 
514 		if (!ring)
515 			continue;
516 
517 		ring->cur = ring->start;
518 		ring->next = ring->start;
519 		ring->memptrs->rptr = 0;
520 
521 		/* Detect and clean up an impossible fence, ie. if GPU managed
522 		 * to scribble something invalid, we don't want that to confuse
523 		 * us into mistakingly believing that submits have completed.
524 		 */
525 		if (fence_before(ring->fctx->last_fence, ring->memptrs->fence)) {
526 			ring->memptrs->fence = ring->fctx->last_fence;
527 		}
528 	}
529 
530 	return 0;
531 }
532 
533 /* Use this helper to read rptr, since a430 doesn't update rptr in memory */
534 static uint32_t get_rptr(struct adreno_gpu *adreno_gpu,
535 		struct msm_ringbuffer *ring)
536 {
537 	struct msm_gpu *gpu = &adreno_gpu->base;
538 
539 	return gpu->funcs->get_rptr(gpu, ring);
540 }
541 
542 struct msm_ringbuffer *adreno_active_ring(struct msm_gpu *gpu)
543 {
544 	return gpu->rb[0];
545 }
546 
547 void adreno_recover(struct msm_gpu *gpu)
548 {
549 	struct drm_device *dev = gpu->dev;
550 	int ret;
551 
552 	// XXX pm-runtime??  we *need* the device to be off after this
553 	// so maybe continuing to call ->pm_suspend/resume() is better?
554 
555 	gpu->funcs->pm_suspend(gpu);
556 	gpu->funcs->pm_resume(gpu);
557 
558 	ret = msm_gpu_hw_init(gpu);
559 	if (ret) {
560 		DRM_DEV_ERROR(dev->dev, "gpu hw init failed: %d\n", ret);
561 		/* hmm, oh well? */
562 	}
563 }
564 
565 void adreno_flush(struct msm_gpu *gpu, struct msm_ringbuffer *ring, u32 reg)
566 {
567 	uint32_t wptr;
568 
569 	/* Copy the shadow to the actual register */
570 	ring->cur = ring->next;
571 
572 	/*
573 	 * Mask wptr value that we calculate to fit in the HW range. This is
574 	 * to account for the possibility that the last command fit exactly into
575 	 * the ringbuffer and rb->next hasn't wrapped to zero yet
576 	 */
577 	wptr = get_wptr(ring);
578 
579 	/* ensure writes to ringbuffer have hit system memory: */
580 	mb();
581 
582 	gpu_write(gpu, reg, wptr);
583 }
584 
585 bool adreno_idle(struct msm_gpu *gpu, struct msm_ringbuffer *ring)
586 {
587 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
588 	uint32_t wptr = get_wptr(ring);
589 
590 	/* wait for CP to drain ringbuffer: */
591 	if (!spin_until(get_rptr(adreno_gpu, ring) == wptr))
592 		return true;
593 
594 	/* TODO maybe we need to reset GPU here to recover from hang? */
595 	DRM_ERROR("%s: timeout waiting to drain ringbuffer %d rptr/wptr = %X/%X\n",
596 		gpu->name, ring->id, get_rptr(adreno_gpu, ring), wptr);
597 
598 	return false;
599 }
600 
601 int adreno_gpu_state_get(struct msm_gpu *gpu, struct msm_gpu_state *state)
602 {
603 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
604 	int i, count = 0;
605 
606 	WARN_ON(!mutex_is_locked(&gpu->lock));
607 
608 	kref_init(&state->ref);
609 
610 	ktime_get_real_ts64(&state->time);
611 
612 	for (i = 0; i < gpu->nr_rings; i++) {
613 		int size = 0, j;
614 
615 		state->ring[i].fence = gpu->rb[i]->memptrs->fence;
616 		state->ring[i].iova = gpu->rb[i]->iova;
617 		state->ring[i].seqno = gpu->rb[i]->fctx->last_fence;
618 		state->ring[i].rptr = get_rptr(adreno_gpu, gpu->rb[i]);
619 		state->ring[i].wptr = get_wptr(gpu->rb[i]);
620 
621 		/* Copy at least 'wptr' dwords of the data */
622 		size = state->ring[i].wptr;
623 
624 		/* After wptr find the last non zero dword to save space */
625 		for (j = state->ring[i].wptr; j < MSM_GPU_RINGBUFFER_SZ >> 2; j++)
626 			if (gpu->rb[i]->start[j])
627 				size = j + 1;
628 
629 		if (size) {
630 			state->ring[i].data = kvmalloc(size << 2, GFP_KERNEL);
631 			if (state->ring[i].data) {
632 				memcpy(state->ring[i].data, gpu->rb[i]->start, size << 2);
633 				state->ring[i].data_size = size << 2;
634 			}
635 		}
636 	}
637 
638 	/* Some targets prefer to collect their own registers */
639 	if (!adreno_gpu->registers)
640 		return 0;
641 
642 	/* Count the number of registers */
643 	for (i = 0; adreno_gpu->registers[i] != ~0; i += 2)
644 		count += adreno_gpu->registers[i + 1] -
645 			adreno_gpu->registers[i] + 1;
646 
647 	state->registers = kcalloc(count * 2, sizeof(u32), GFP_KERNEL);
648 	if (state->registers) {
649 		int pos = 0;
650 
651 		for (i = 0; adreno_gpu->registers[i] != ~0; i += 2) {
652 			u32 start = adreno_gpu->registers[i];
653 			u32 end   = adreno_gpu->registers[i + 1];
654 			u32 addr;
655 
656 			for (addr = start; addr <= end; addr++) {
657 				state->registers[pos++] = addr;
658 				state->registers[pos++] = gpu_read(gpu, addr);
659 			}
660 		}
661 
662 		state->nr_registers = count;
663 	}
664 
665 	return 0;
666 }
667 
668 void adreno_gpu_state_destroy(struct msm_gpu_state *state)
669 {
670 	int i;
671 
672 	for (i = 0; i < ARRAY_SIZE(state->ring); i++)
673 		kvfree(state->ring[i].data);
674 
675 	for (i = 0; state->bos && i < state->nr_bos; i++)
676 		kvfree(state->bos[i].data);
677 
678 	kfree(state->bos);
679 	kfree(state->comm);
680 	kfree(state->cmd);
681 	kfree(state->registers);
682 }
683 
684 static void adreno_gpu_state_kref_destroy(struct kref *kref)
685 {
686 	struct msm_gpu_state *state = container_of(kref,
687 		struct msm_gpu_state, ref);
688 
689 	adreno_gpu_state_destroy(state);
690 	kfree(state);
691 }
692 
693 int adreno_gpu_state_put(struct msm_gpu_state *state)
694 {
695 	if (IS_ERR_OR_NULL(state))
696 		return 1;
697 
698 	return kref_put(&state->ref, adreno_gpu_state_kref_destroy);
699 }
700 
701 #if defined(CONFIG_DEBUG_FS) || defined(CONFIG_DEV_COREDUMP)
702 
703 static char *adreno_gpu_ascii85_encode(u32 *src, size_t len)
704 {
705 	void *buf;
706 	size_t buf_itr = 0, buffer_size;
707 	char out[ASCII85_BUFSZ];
708 	long l;
709 	int i;
710 
711 	if (!src || !len)
712 		return NULL;
713 
714 	l = ascii85_encode_len(len);
715 
716 	/*
717 	 * Ascii85 outputs either a 5 byte string or a 1 byte string. So we
718 	 * account for the worst case of 5 bytes per dword plus the 1 for '\0'
719 	 */
720 	buffer_size = (l * 5) + 1;
721 
722 	buf = kvmalloc(buffer_size, GFP_KERNEL);
723 	if (!buf)
724 		return NULL;
725 
726 	for (i = 0; i < l; i++)
727 		buf_itr += scnprintf(buf + buf_itr, buffer_size - buf_itr, "%s",
728 				ascii85_encode(src[i], out));
729 
730 	return buf;
731 }
732 
733 /* len is expected to be in bytes
734  *
735  * WARNING: *ptr should be allocated with kvmalloc or friends.  It can be free'd
736  * with kvfree() and replaced with a newly kvmalloc'd buffer on the first call
737  * when the unencoded raw data is encoded
738  */
739 void adreno_show_object(struct drm_printer *p, void **ptr, int len,
740 		bool *encoded)
741 {
742 	if (!*ptr || !len)
743 		return;
744 
745 	if (!*encoded) {
746 		long datalen, i;
747 		u32 *buf = *ptr;
748 
749 		/*
750 		 * Only dump the non-zero part of the buffer - rarely will
751 		 * any data completely fill the entire allocated size of
752 		 * the buffer.
753 		 */
754 		for (datalen = 0, i = 0; i < len >> 2; i++)
755 			if (buf[i])
756 				datalen = ((i + 1) << 2);
757 
758 		/*
759 		 * If we reach here, then the originally captured binary buffer
760 		 * will be replaced with the ascii85 encoded string
761 		 */
762 		*ptr = adreno_gpu_ascii85_encode(buf, datalen);
763 
764 		kvfree(buf);
765 
766 		*encoded = true;
767 	}
768 
769 	if (!*ptr)
770 		return;
771 
772 	drm_puts(p, "    data: !!ascii85 |\n");
773 	drm_puts(p, "     ");
774 
775 	drm_puts(p, *ptr);
776 
777 	drm_puts(p, "\n");
778 }
779 
780 void adreno_show(struct msm_gpu *gpu, struct msm_gpu_state *state,
781 		struct drm_printer *p)
782 {
783 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
784 	int i;
785 
786 	if (IS_ERR_OR_NULL(state))
787 		return;
788 
789 	drm_printf(p, "revision: %d (%d.%d.%d.%d)\n",
790 			adreno_gpu->info->revn, adreno_gpu->rev.core,
791 			adreno_gpu->rev.major, adreno_gpu->rev.minor,
792 			adreno_gpu->rev.patchid);
793 	/*
794 	 * If this is state collected due to iova fault, so fault related info
795 	 *
796 	 * TTBR0 would not be zero, so this is a good way to distinguish
797 	 */
798 	if (state->fault_info.ttbr0) {
799 		const struct msm_gpu_fault_info *info = &state->fault_info;
800 
801 		drm_puts(p, "fault-info:\n");
802 		drm_printf(p, "  - ttbr0=%.16llx\n", info->ttbr0);
803 		drm_printf(p, "  - iova=%.16lx\n", info->iova);
804 		drm_printf(p, "  - dir=%s\n", info->flags & IOMMU_FAULT_WRITE ? "WRITE" : "READ");
805 		drm_printf(p, "  - type=%s\n", info->type);
806 		drm_printf(p, "  - source=%s\n", info->block);
807 	}
808 
809 	drm_printf(p, "rbbm-status: 0x%08x\n", state->rbbm_status);
810 
811 	drm_puts(p, "ringbuffer:\n");
812 
813 	for (i = 0; i < gpu->nr_rings; i++) {
814 		drm_printf(p, "  - id: %d\n", i);
815 		drm_printf(p, "    iova: 0x%016llx\n", state->ring[i].iova);
816 		drm_printf(p, "    last-fence: %u\n", state->ring[i].seqno);
817 		drm_printf(p, "    retired-fence: %u\n", state->ring[i].fence);
818 		drm_printf(p, "    rptr: %u\n", state->ring[i].rptr);
819 		drm_printf(p, "    wptr: %u\n", state->ring[i].wptr);
820 		drm_printf(p, "    size: %u\n", MSM_GPU_RINGBUFFER_SZ);
821 
822 		adreno_show_object(p, &state->ring[i].data,
823 			state->ring[i].data_size, &state->ring[i].encoded);
824 	}
825 
826 	if (state->bos) {
827 		drm_puts(p, "bos:\n");
828 
829 		for (i = 0; i < state->nr_bos; i++) {
830 			drm_printf(p, "  - iova: 0x%016llx\n",
831 				state->bos[i].iova);
832 			drm_printf(p, "    size: %zd\n", state->bos[i].size);
833 			drm_printf(p, "    name: %-32s\n", state->bos[i].name);
834 
835 			adreno_show_object(p, &state->bos[i].data,
836 				state->bos[i].size, &state->bos[i].encoded);
837 		}
838 	}
839 
840 	if (state->nr_registers) {
841 		drm_puts(p, "registers:\n");
842 
843 		for (i = 0; i < state->nr_registers; i++) {
844 			drm_printf(p, "  - { offset: 0x%04x, value: 0x%08x }\n",
845 				state->registers[i * 2] << 2,
846 				state->registers[(i * 2) + 1]);
847 		}
848 	}
849 }
850 #endif
851 
852 /* Dump common gpu status and scratch registers on any hang, to make
853  * the hangcheck logs more useful.  The scratch registers seem always
854  * safe to read when GPU has hung (unlike some other regs, depending
855  * on how the GPU hung), and they are useful to match up to cmdstream
856  * dumps when debugging hangs:
857  */
858 void adreno_dump_info(struct msm_gpu *gpu)
859 {
860 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
861 	int i;
862 
863 	printk("revision: %d (%d.%d.%d.%d)\n",
864 			adreno_gpu->info->revn, adreno_gpu->rev.core,
865 			adreno_gpu->rev.major, adreno_gpu->rev.minor,
866 			adreno_gpu->rev.patchid);
867 
868 	for (i = 0; i < gpu->nr_rings; i++) {
869 		struct msm_ringbuffer *ring = gpu->rb[i];
870 
871 		printk("rb %d: fence:    %d/%d\n", i,
872 			ring->memptrs->fence,
873 			ring->fctx->last_fence);
874 
875 		printk("rptr:     %d\n", get_rptr(adreno_gpu, ring));
876 		printk("rb wptr:  %d\n", get_wptr(ring));
877 	}
878 }
879 
880 /* would be nice to not have to duplicate the _show() stuff with printk(): */
881 void adreno_dump(struct msm_gpu *gpu)
882 {
883 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
884 	int i;
885 
886 	if (!adreno_gpu->registers)
887 		return;
888 
889 	/* dump these out in a form that can be parsed by demsm: */
890 	printk("IO:region %s 00000000 00020000\n", gpu->name);
891 	for (i = 0; adreno_gpu->registers[i] != ~0; i += 2) {
892 		uint32_t start = adreno_gpu->registers[i];
893 		uint32_t end   = adreno_gpu->registers[i+1];
894 		uint32_t addr;
895 
896 		for (addr = start; addr <= end; addr++) {
897 			uint32_t val = gpu_read(gpu, addr);
898 			printk("IO:R %08x %08x\n", addr<<2, val);
899 		}
900 	}
901 }
902 
903 static uint32_t ring_freewords(struct msm_ringbuffer *ring)
904 {
905 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(ring->gpu);
906 	uint32_t size = MSM_GPU_RINGBUFFER_SZ >> 2;
907 	/* Use ring->next to calculate free size */
908 	uint32_t wptr = ring->next - ring->start;
909 	uint32_t rptr = get_rptr(adreno_gpu, ring);
910 	return (rptr + (size - 1) - wptr) % size;
911 }
912 
913 void adreno_wait_ring(struct msm_ringbuffer *ring, uint32_t ndwords)
914 {
915 	if (spin_until(ring_freewords(ring) >= ndwords))
916 		DRM_DEV_ERROR(ring->gpu->dev->dev,
917 			"timeout waiting for space in ringbuffer %d\n",
918 			ring->id);
919 }
920 
921 /* Get legacy powerlevels from qcom,gpu-pwrlevels and populate the opp table */
922 static int adreno_get_legacy_pwrlevels(struct device *dev)
923 {
924 	struct device_node *child, *node;
925 	int ret;
926 
927 	node = of_get_compatible_child(dev->of_node, "qcom,gpu-pwrlevels");
928 	if (!node) {
929 		DRM_DEV_DEBUG(dev, "Could not find the GPU powerlevels\n");
930 		return -ENXIO;
931 	}
932 
933 	for_each_child_of_node(node, child) {
934 		unsigned int val;
935 
936 		ret = of_property_read_u32(child, "qcom,gpu-freq", &val);
937 		if (ret)
938 			continue;
939 
940 		/*
941 		 * Skip the intentionally bogus clock value found at the bottom
942 		 * of most legacy frequency tables
943 		 */
944 		if (val != 27000000)
945 			dev_pm_opp_add(dev, val, 0);
946 	}
947 
948 	of_node_put(node);
949 
950 	return 0;
951 }
952 
953 static void adreno_get_pwrlevels(struct device *dev,
954 		struct msm_gpu *gpu)
955 {
956 	unsigned long freq = ULONG_MAX;
957 	struct dev_pm_opp *opp;
958 	int ret;
959 
960 	gpu->fast_rate = 0;
961 
962 	/* You down with OPP? */
963 	if (!of_find_property(dev->of_node, "operating-points-v2", NULL))
964 		ret = adreno_get_legacy_pwrlevels(dev);
965 	else {
966 		ret = devm_pm_opp_of_add_table(dev);
967 		if (ret)
968 			DRM_DEV_ERROR(dev, "Unable to set the OPP table\n");
969 	}
970 
971 	if (!ret) {
972 		/* Find the fastest defined rate */
973 		opp = dev_pm_opp_find_freq_floor(dev, &freq);
974 		if (!IS_ERR(opp)) {
975 			gpu->fast_rate = freq;
976 			dev_pm_opp_put(opp);
977 		}
978 	}
979 
980 	if (!gpu->fast_rate) {
981 		dev_warn(dev,
982 			"Could not find a clock rate. Using a reasonable default\n");
983 		/* Pick a suitably safe clock speed for any target */
984 		gpu->fast_rate = 200000000;
985 	}
986 
987 	DBG("fast_rate=%u, slow_rate=27000000", gpu->fast_rate);
988 }
989 
990 int adreno_gpu_ocmem_init(struct device *dev, struct adreno_gpu *adreno_gpu,
991 			  struct adreno_ocmem *adreno_ocmem)
992 {
993 	struct ocmem_buf *ocmem_hdl;
994 	struct ocmem *ocmem;
995 
996 	ocmem = of_get_ocmem(dev);
997 	if (IS_ERR(ocmem)) {
998 		if (PTR_ERR(ocmem) == -ENODEV) {
999 			/*
1000 			 * Return success since either the ocmem property was
1001 			 * not specified in device tree, or ocmem support is
1002 			 * not compiled into the kernel.
1003 			 */
1004 			return 0;
1005 		}
1006 
1007 		return PTR_ERR(ocmem);
1008 	}
1009 
1010 	ocmem_hdl = ocmem_allocate(ocmem, OCMEM_GRAPHICS, adreno_gpu->gmem);
1011 	if (IS_ERR(ocmem_hdl))
1012 		return PTR_ERR(ocmem_hdl);
1013 
1014 	adreno_ocmem->ocmem = ocmem;
1015 	adreno_ocmem->base = ocmem_hdl->addr;
1016 	adreno_ocmem->hdl = ocmem_hdl;
1017 	adreno_gpu->gmem = ocmem_hdl->len;
1018 
1019 	return 0;
1020 }
1021 
1022 void adreno_gpu_ocmem_cleanup(struct adreno_ocmem *adreno_ocmem)
1023 {
1024 	if (adreno_ocmem && adreno_ocmem->base)
1025 		ocmem_free(adreno_ocmem->ocmem, OCMEM_GRAPHICS,
1026 			   adreno_ocmem->hdl);
1027 }
1028 
1029 int adreno_read_speedbin(struct device *dev, u32 *speedbin)
1030 {
1031 	return nvmem_cell_read_variable_le_u32(dev, "speed_bin", speedbin);
1032 }
1033 
1034 int adreno_gpu_init(struct drm_device *drm, struct platform_device *pdev,
1035 		struct adreno_gpu *adreno_gpu,
1036 		const struct adreno_gpu_funcs *funcs, int nr_rings)
1037 {
1038 	struct device *dev = &pdev->dev;
1039 	struct adreno_platform_config *config = dev->platform_data;
1040 	struct msm_gpu_config adreno_gpu_config  = { 0 };
1041 	struct msm_gpu *gpu = &adreno_gpu->base;
1042 	struct adreno_rev *rev = &config->rev;
1043 	const char *gpu_name;
1044 	u32 speedbin;
1045 
1046 	adreno_gpu->funcs = funcs;
1047 	adreno_gpu->info = adreno_info(config->rev);
1048 	adreno_gpu->gmem = adreno_gpu->info->gmem;
1049 	adreno_gpu->revn = adreno_gpu->info->revn;
1050 	adreno_gpu->rev = *rev;
1051 
1052 	if (adreno_read_speedbin(dev, &speedbin) || !speedbin)
1053 		speedbin = 0xffff;
1054 	adreno_gpu->speedbin = (uint16_t) (0xffff & speedbin);
1055 
1056 	gpu_name = adreno_gpu->info->name;
1057 	if (!gpu_name) {
1058 		gpu_name = devm_kasprintf(dev, GFP_KERNEL, "%d.%d.%d.%d",
1059 				rev->core, rev->major, rev->minor,
1060 				rev->patchid);
1061 		if (!gpu_name)
1062 			return -ENOMEM;
1063 	}
1064 
1065 	adreno_gpu_config.ioname = "kgsl_3d0_reg_memory";
1066 
1067 	adreno_gpu_config.nr_rings = nr_rings;
1068 
1069 	adreno_get_pwrlevels(dev, gpu);
1070 
1071 	pm_runtime_set_autosuspend_delay(dev,
1072 		adreno_gpu->info->inactive_period);
1073 	pm_runtime_use_autosuspend(dev);
1074 
1075 	return msm_gpu_init(drm, pdev, &adreno_gpu->base, &funcs->base,
1076 			gpu_name, &adreno_gpu_config);
1077 }
1078 
1079 void adreno_gpu_cleanup(struct adreno_gpu *adreno_gpu)
1080 {
1081 	struct msm_gpu *gpu = &adreno_gpu->base;
1082 	struct msm_drm_private *priv = gpu->dev->dev_private;
1083 	unsigned int i;
1084 
1085 	for (i = 0; i < ARRAY_SIZE(adreno_gpu->info->fw); i++)
1086 		release_firmware(adreno_gpu->fw[i]);
1087 
1088 	if (pm_runtime_enabled(&priv->gpu_pdev->dev))
1089 		pm_runtime_disable(&priv->gpu_pdev->dev);
1090 
1091 	msm_gpu_cleanup(&adreno_gpu->base);
1092 }
1093