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/firmware/qcom/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_gpu_new(&pdev->dev, gpu, 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 #define ARM_SMMU_FSR_TF                 BIT(1)
250 #define ARM_SMMU_FSR_PF			BIT(3)
251 #define ARM_SMMU_FSR_EF			BIT(4)
252 
253 int adreno_fault_handler(struct msm_gpu *gpu, unsigned long iova, int flags,
254 			 struct adreno_smmu_fault_info *info, const char *block,
255 			 u32 scratch[4])
256 {
257 	const char *type = "UNKNOWN";
258 	bool do_devcoredump = info && !READ_ONCE(gpu->crashstate);
259 
260 	/*
261 	 * If we aren't going to be resuming later from fault_worker, then do
262 	 * it now.
263 	 */
264 	if (!do_devcoredump) {
265 		gpu->aspace->mmu->funcs->resume_translation(gpu->aspace->mmu);
266 	}
267 
268 	/*
269 	 * Print a default message if we couldn't get the data from the
270 	 * adreno-smmu-priv
271 	 */
272 	if (!info) {
273 		pr_warn_ratelimited("*** gpu fault: iova=%.16lx flags=%d (%u,%u,%u,%u)\n",
274 			iova, flags,
275 			scratch[0], scratch[1], scratch[2], scratch[3]);
276 
277 		return 0;
278 	}
279 
280 	if (info->fsr & ARM_SMMU_FSR_TF)
281 		type = "TRANSLATION";
282 	else if (info->fsr & ARM_SMMU_FSR_PF)
283 		type = "PERMISSION";
284 	else if (info->fsr & ARM_SMMU_FSR_EF)
285 		type = "EXTERNAL";
286 
287 	pr_warn_ratelimited("*** gpu fault: ttbr0=%.16llx iova=%.16lx dir=%s type=%s source=%s (%u,%u,%u,%u)\n",
288 			info->ttbr0, iova,
289 			flags & IOMMU_FAULT_WRITE ? "WRITE" : "READ",
290 			type, block,
291 			scratch[0], scratch[1], scratch[2], scratch[3]);
292 
293 	if (do_devcoredump) {
294 		/* Turn off the hangcheck timer to keep it from bothering us */
295 		del_timer(&gpu->hangcheck_timer);
296 
297 		gpu->fault_info.ttbr0 = info->ttbr0;
298 		gpu->fault_info.iova  = iova;
299 		gpu->fault_info.flags = flags;
300 		gpu->fault_info.type  = type;
301 		gpu->fault_info.block = block;
302 
303 		kthread_queue_work(gpu->worker, &gpu->fault_work);
304 	}
305 
306 	return 0;
307 }
308 
309 int adreno_get_param(struct msm_gpu *gpu, struct msm_file_private *ctx,
310 		     uint32_t param, uint64_t *value, uint32_t *len)
311 {
312 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
313 
314 	/* No pointer params yet */
315 	if (*len != 0)
316 		return -EINVAL;
317 
318 	switch (param) {
319 	case MSM_PARAM_GPU_ID:
320 		*value = adreno_gpu->info->revn;
321 		return 0;
322 	case MSM_PARAM_GMEM_SIZE:
323 		*value = adreno_gpu->gmem;
324 		return 0;
325 	case MSM_PARAM_GMEM_BASE:
326 		*value = !adreno_is_a650_family(adreno_gpu) ? 0x100000 : 0;
327 		return 0;
328 	case MSM_PARAM_CHIP_ID:
329 		*value =  (uint64_t)adreno_gpu->rev.patchid |
330 			 ((uint64_t)adreno_gpu->rev.minor << 8) |
331 			 ((uint64_t)adreno_gpu->rev.major << 16) |
332 			 ((uint64_t)adreno_gpu->rev.core  << 24);
333 		if (!adreno_gpu->info->revn)
334 			*value |= ((uint64_t) adreno_gpu->speedbin) << 32;
335 		return 0;
336 	case MSM_PARAM_MAX_FREQ:
337 		*value = adreno_gpu->base.fast_rate;
338 		return 0;
339 	case MSM_PARAM_TIMESTAMP:
340 		if (adreno_gpu->funcs->get_timestamp) {
341 			int ret;
342 
343 			pm_runtime_get_sync(&gpu->pdev->dev);
344 			ret = adreno_gpu->funcs->get_timestamp(gpu, value);
345 			pm_runtime_put_autosuspend(&gpu->pdev->dev);
346 
347 			return ret;
348 		}
349 		return -EINVAL;
350 	case MSM_PARAM_PRIORITIES:
351 		*value = gpu->nr_rings * NR_SCHED_PRIORITIES;
352 		return 0;
353 	case MSM_PARAM_PP_PGTABLE:
354 		*value = 0;
355 		return 0;
356 	case MSM_PARAM_FAULTS:
357 		if (ctx->aspace)
358 			*value = gpu->global_faults + ctx->aspace->faults;
359 		else
360 			*value = gpu->global_faults;
361 		return 0;
362 	case MSM_PARAM_SUSPENDS:
363 		*value = gpu->suspend_count;
364 		return 0;
365 	case MSM_PARAM_VA_START:
366 		if (ctx->aspace == gpu->aspace)
367 			return -EINVAL;
368 		*value = ctx->aspace->va_start;
369 		return 0;
370 	case MSM_PARAM_VA_SIZE:
371 		if (ctx->aspace == gpu->aspace)
372 			return -EINVAL;
373 		*value = ctx->aspace->va_size;
374 		return 0;
375 	default:
376 		DBG("%s: invalid param: %u", gpu->name, param);
377 		return -EINVAL;
378 	}
379 }
380 
381 int adreno_set_param(struct msm_gpu *gpu, struct msm_file_private *ctx,
382 		     uint32_t param, uint64_t value, uint32_t len)
383 {
384 	switch (param) {
385 	case MSM_PARAM_COMM:
386 	case MSM_PARAM_CMDLINE:
387 		/* kstrdup_quotable_cmdline() limits to PAGE_SIZE, so
388 		 * that should be a reasonable upper bound
389 		 */
390 		if (len > PAGE_SIZE)
391 			return -EINVAL;
392 		break;
393 	default:
394 		if (len != 0)
395 			return -EINVAL;
396 	}
397 
398 	switch (param) {
399 	case MSM_PARAM_COMM:
400 	case MSM_PARAM_CMDLINE: {
401 		char *str, **paramp;
402 
403 		str = kmalloc(len + 1, GFP_KERNEL);
404 		if (!str)
405 			return -ENOMEM;
406 
407 		if (copy_from_user(str, u64_to_user_ptr(value), len)) {
408 			kfree(str);
409 			return -EFAULT;
410 		}
411 
412 		/* Ensure string is null terminated: */
413 		str[len] = '\0';
414 
415 		mutex_lock(&gpu->lock);
416 
417 		if (param == MSM_PARAM_COMM) {
418 			paramp = &ctx->comm;
419 		} else {
420 			paramp = &ctx->cmdline;
421 		}
422 
423 		kfree(*paramp);
424 		*paramp = str;
425 
426 		mutex_unlock(&gpu->lock);
427 
428 		return 0;
429 	}
430 	case MSM_PARAM_SYSPROF:
431 		if (!capable(CAP_SYS_ADMIN))
432 			return -EPERM;
433 		return msm_file_private_set_sysprof(ctx, gpu, value);
434 	default:
435 		DBG("%s: invalid param: %u", gpu->name, param);
436 		return -EINVAL;
437 	}
438 }
439 
440 const struct firmware *
441 adreno_request_fw(struct adreno_gpu *adreno_gpu, const char *fwname)
442 {
443 	struct drm_device *drm = adreno_gpu->base.dev;
444 	const struct firmware *fw = NULL;
445 	char *newname;
446 	int ret;
447 
448 	newname = kasprintf(GFP_KERNEL, "qcom/%s", fwname);
449 	if (!newname)
450 		return ERR_PTR(-ENOMEM);
451 
452 	/*
453 	 * Try first to load from qcom/$fwfile using a direct load (to avoid
454 	 * a potential timeout waiting for usermode helper)
455 	 */
456 	if ((adreno_gpu->fwloc == FW_LOCATION_UNKNOWN) ||
457 	    (adreno_gpu->fwloc == FW_LOCATION_NEW)) {
458 
459 		ret = request_firmware_direct(&fw, newname, drm->dev);
460 		if (!ret) {
461 			DRM_DEV_INFO(drm->dev, "loaded %s from new location\n",
462 				newname);
463 			adreno_gpu->fwloc = FW_LOCATION_NEW;
464 			goto out;
465 		} else if (adreno_gpu->fwloc != FW_LOCATION_UNKNOWN) {
466 			DRM_DEV_ERROR(drm->dev, "failed to load %s: %d\n",
467 				newname, ret);
468 			fw = ERR_PTR(ret);
469 			goto out;
470 		}
471 	}
472 
473 	/*
474 	 * Then try the legacy location without qcom/ prefix
475 	 */
476 	if ((adreno_gpu->fwloc == FW_LOCATION_UNKNOWN) ||
477 	    (adreno_gpu->fwloc == FW_LOCATION_LEGACY)) {
478 
479 		ret = request_firmware_direct(&fw, fwname, drm->dev);
480 		if (!ret) {
481 			DRM_DEV_INFO(drm->dev, "loaded %s from legacy location\n",
482 				newname);
483 			adreno_gpu->fwloc = FW_LOCATION_LEGACY;
484 			goto out;
485 		} else if (adreno_gpu->fwloc != FW_LOCATION_UNKNOWN) {
486 			DRM_DEV_ERROR(drm->dev, "failed to load %s: %d\n",
487 				fwname, ret);
488 			fw = ERR_PTR(ret);
489 			goto out;
490 		}
491 	}
492 
493 	/*
494 	 * Finally fall back to request_firmware() for cases where the
495 	 * usermode helper is needed (I think mainly android)
496 	 */
497 	if ((adreno_gpu->fwloc == FW_LOCATION_UNKNOWN) ||
498 	    (adreno_gpu->fwloc == FW_LOCATION_HELPER)) {
499 
500 		ret = request_firmware(&fw, newname, drm->dev);
501 		if (!ret) {
502 			DRM_DEV_INFO(drm->dev, "loaded %s with helper\n",
503 				newname);
504 			adreno_gpu->fwloc = FW_LOCATION_HELPER;
505 			goto out;
506 		} else if (adreno_gpu->fwloc != FW_LOCATION_UNKNOWN) {
507 			DRM_DEV_ERROR(drm->dev, "failed to load %s: %d\n",
508 				newname, ret);
509 			fw = ERR_PTR(ret);
510 			goto out;
511 		}
512 	}
513 
514 	DRM_DEV_ERROR(drm->dev, "failed to load %s\n", fwname);
515 	fw = ERR_PTR(-ENOENT);
516 out:
517 	kfree(newname);
518 	return fw;
519 }
520 
521 int adreno_load_fw(struct adreno_gpu *adreno_gpu)
522 {
523 	int i;
524 
525 	for (i = 0; i < ARRAY_SIZE(adreno_gpu->info->fw); i++) {
526 		const struct firmware *fw;
527 
528 		if (!adreno_gpu->info->fw[i])
529 			continue;
530 
531 		/* Skip if the firmware has already been loaded */
532 		if (adreno_gpu->fw[i])
533 			continue;
534 
535 		fw = adreno_request_fw(adreno_gpu, adreno_gpu->info->fw[i]);
536 		if (IS_ERR(fw))
537 			return PTR_ERR(fw);
538 
539 		adreno_gpu->fw[i] = fw;
540 	}
541 
542 	return 0;
543 }
544 
545 struct drm_gem_object *adreno_fw_create_bo(struct msm_gpu *gpu,
546 		const struct firmware *fw, u64 *iova)
547 {
548 	struct drm_gem_object *bo;
549 	void *ptr;
550 
551 	ptr = msm_gem_kernel_new(gpu->dev, fw->size - 4,
552 		MSM_BO_WC | MSM_BO_GPU_READONLY, gpu->aspace, &bo, iova);
553 
554 	if (IS_ERR(ptr))
555 		return ERR_CAST(ptr);
556 
557 	memcpy(ptr, &fw->data[4], fw->size - 4);
558 
559 	msm_gem_put_vaddr(bo);
560 
561 	return bo;
562 }
563 
564 int adreno_hw_init(struct msm_gpu *gpu)
565 {
566 	VERB("%s", gpu->name);
567 
568 	for (int i = 0; i < gpu->nr_rings; i++) {
569 		struct msm_ringbuffer *ring = gpu->rb[i];
570 
571 		if (!ring)
572 			continue;
573 
574 		ring->cur = ring->start;
575 		ring->next = ring->start;
576 		ring->memptrs->rptr = 0;
577 
578 		/* Detect and clean up an impossible fence, ie. if GPU managed
579 		 * to scribble something invalid, we don't want that to confuse
580 		 * us into mistakingly believing that submits have completed.
581 		 */
582 		if (fence_before(ring->fctx->last_fence, ring->memptrs->fence)) {
583 			ring->memptrs->fence = ring->fctx->last_fence;
584 		}
585 	}
586 
587 	return 0;
588 }
589 
590 /* Use this helper to read rptr, since a430 doesn't update rptr in memory */
591 static uint32_t get_rptr(struct adreno_gpu *adreno_gpu,
592 		struct msm_ringbuffer *ring)
593 {
594 	struct msm_gpu *gpu = &adreno_gpu->base;
595 
596 	return gpu->funcs->get_rptr(gpu, ring);
597 }
598 
599 struct msm_ringbuffer *adreno_active_ring(struct msm_gpu *gpu)
600 {
601 	return gpu->rb[0];
602 }
603 
604 void adreno_recover(struct msm_gpu *gpu)
605 {
606 	struct drm_device *dev = gpu->dev;
607 	int ret;
608 
609 	// XXX pm-runtime??  we *need* the device to be off after this
610 	// so maybe continuing to call ->pm_suspend/resume() is better?
611 
612 	gpu->funcs->pm_suspend(gpu);
613 	gpu->funcs->pm_resume(gpu);
614 
615 	ret = msm_gpu_hw_init(gpu);
616 	if (ret) {
617 		DRM_DEV_ERROR(dev->dev, "gpu hw init failed: %d\n", ret);
618 		/* hmm, oh well? */
619 	}
620 }
621 
622 void adreno_flush(struct msm_gpu *gpu, struct msm_ringbuffer *ring, u32 reg)
623 {
624 	uint32_t wptr;
625 
626 	/* Copy the shadow to the actual register */
627 	ring->cur = ring->next;
628 
629 	/*
630 	 * Mask wptr value that we calculate to fit in the HW range. This is
631 	 * to account for the possibility that the last command fit exactly into
632 	 * the ringbuffer and rb->next hasn't wrapped to zero yet
633 	 */
634 	wptr = get_wptr(ring);
635 
636 	/* ensure writes to ringbuffer have hit system memory: */
637 	mb();
638 
639 	gpu_write(gpu, reg, wptr);
640 }
641 
642 bool adreno_idle(struct msm_gpu *gpu, struct msm_ringbuffer *ring)
643 {
644 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
645 	uint32_t wptr = get_wptr(ring);
646 
647 	/* wait for CP to drain ringbuffer: */
648 	if (!spin_until(get_rptr(adreno_gpu, ring) == wptr))
649 		return true;
650 
651 	/* TODO maybe we need to reset GPU here to recover from hang? */
652 	DRM_ERROR("%s: timeout waiting to drain ringbuffer %d rptr/wptr = %X/%X\n",
653 		gpu->name, ring->id, get_rptr(adreno_gpu, ring), wptr);
654 
655 	return false;
656 }
657 
658 int adreno_gpu_state_get(struct msm_gpu *gpu, struct msm_gpu_state *state)
659 {
660 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
661 	int i, count = 0;
662 
663 	WARN_ON(!mutex_is_locked(&gpu->lock));
664 
665 	kref_init(&state->ref);
666 
667 	ktime_get_real_ts64(&state->time);
668 
669 	for (i = 0; i < gpu->nr_rings; i++) {
670 		int size = 0, j;
671 
672 		state->ring[i].fence = gpu->rb[i]->memptrs->fence;
673 		state->ring[i].iova = gpu->rb[i]->iova;
674 		state->ring[i].seqno = gpu->rb[i]->fctx->last_fence;
675 		state->ring[i].rptr = get_rptr(adreno_gpu, gpu->rb[i]);
676 		state->ring[i].wptr = get_wptr(gpu->rb[i]);
677 
678 		/* Copy at least 'wptr' dwords of the data */
679 		size = state->ring[i].wptr;
680 
681 		/* After wptr find the last non zero dword to save space */
682 		for (j = state->ring[i].wptr; j < MSM_GPU_RINGBUFFER_SZ >> 2; j++)
683 			if (gpu->rb[i]->start[j])
684 				size = j + 1;
685 
686 		if (size) {
687 			state->ring[i].data = kvmalloc(size << 2, GFP_KERNEL);
688 			if (state->ring[i].data) {
689 				memcpy(state->ring[i].data, gpu->rb[i]->start, size << 2);
690 				state->ring[i].data_size = size << 2;
691 			}
692 		}
693 	}
694 
695 	/* Some targets prefer to collect their own registers */
696 	if (!adreno_gpu->registers)
697 		return 0;
698 
699 	/* Count the number of registers */
700 	for (i = 0; adreno_gpu->registers[i] != ~0; i += 2)
701 		count += adreno_gpu->registers[i + 1] -
702 			adreno_gpu->registers[i] + 1;
703 
704 	state->registers = kcalloc(count * 2, sizeof(u32), GFP_KERNEL);
705 	if (state->registers) {
706 		int pos = 0;
707 
708 		for (i = 0; adreno_gpu->registers[i] != ~0; i += 2) {
709 			u32 start = adreno_gpu->registers[i];
710 			u32 end   = adreno_gpu->registers[i + 1];
711 			u32 addr;
712 
713 			for (addr = start; addr <= end; addr++) {
714 				state->registers[pos++] = addr;
715 				state->registers[pos++] = gpu_read(gpu, addr);
716 			}
717 		}
718 
719 		state->nr_registers = count;
720 	}
721 
722 	return 0;
723 }
724 
725 void adreno_gpu_state_destroy(struct msm_gpu_state *state)
726 {
727 	int i;
728 
729 	for (i = 0; i < ARRAY_SIZE(state->ring); i++)
730 		kvfree(state->ring[i].data);
731 
732 	for (i = 0; state->bos && i < state->nr_bos; i++)
733 		kvfree(state->bos[i].data);
734 
735 	kfree(state->bos);
736 	kfree(state->comm);
737 	kfree(state->cmd);
738 	kfree(state->registers);
739 }
740 
741 static void adreno_gpu_state_kref_destroy(struct kref *kref)
742 {
743 	struct msm_gpu_state *state = container_of(kref,
744 		struct msm_gpu_state, ref);
745 
746 	adreno_gpu_state_destroy(state);
747 	kfree(state);
748 }
749 
750 int adreno_gpu_state_put(struct msm_gpu_state *state)
751 {
752 	if (IS_ERR_OR_NULL(state))
753 		return 1;
754 
755 	return kref_put(&state->ref, adreno_gpu_state_kref_destroy);
756 }
757 
758 #if defined(CONFIG_DEBUG_FS) || defined(CONFIG_DEV_COREDUMP)
759 
760 static char *adreno_gpu_ascii85_encode(u32 *src, size_t len)
761 {
762 	void *buf;
763 	size_t buf_itr = 0, buffer_size;
764 	char out[ASCII85_BUFSZ];
765 	long l;
766 	int i;
767 
768 	if (!src || !len)
769 		return NULL;
770 
771 	l = ascii85_encode_len(len);
772 
773 	/*
774 	 * Ascii85 outputs either a 5 byte string or a 1 byte string. So we
775 	 * account for the worst case of 5 bytes per dword plus the 1 for '\0'
776 	 */
777 	buffer_size = (l * 5) + 1;
778 
779 	buf = kvmalloc(buffer_size, GFP_KERNEL);
780 	if (!buf)
781 		return NULL;
782 
783 	for (i = 0; i < l; i++)
784 		buf_itr += scnprintf(buf + buf_itr, buffer_size - buf_itr, "%s",
785 				ascii85_encode(src[i], out));
786 
787 	return buf;
788 }
789 
790 /* len is expected to be in bytes
791  *
792  * WARNING: *ptr should be allocated with kvmalloc or friends.  It can be free'd
793  * with kvfree() and replaced with a newly kvmalloc'd buffer on the first call
794  * when the unencoded raw data is encoded
795  */
796 void adreno_show_object(struct drm_printer *p, void **ptr, int len,
797 		bool *encoded)
798 {
799 	if (!*ptr || !len)
800 		return;
801 
802 	if (!*encoded) {
803 		long datalen, i;
804 		u32 *buf = *ptr;
805 
806 		/*
807 		 * Only dump the non-zero part of the buffer - rarely will
808 		 * any data completely fill the entire allocated size of
809 		 * the buffer.
810 		 */
811 		for (datalen = 0, i = 0; i < len >> 2; i++)
812 			if (buf[i])
813 				datalen = ((i + 1) << 2);
814 
815 		/*
816 		 * If we reach here, then the originally captured binary buffer
817 		 * will be replaced with the ascii85 encoded string
818 		 */
819 		*ptr = adreno_gpu_ascii85_encode(buf, datalen);
820 
821 		kvfree(buf);
822 
823 		*encoded = true;
824 	}
825 
826 	if (!*ptr)
827 		return;
828 
829 	drm_puts(p, "    data: !!ascii85 |\n");
830 	drm_puts(p, "     ");
831 
832 	drm_puts(p, *ptr);
833 
834 	drm_puts(p, "\n");
835 }
836 
837 void adreno_show(struct msm_gpu *gpu, struct msm_gpu_state *state,
838 		struct drm_printer *p)
839 {
840 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
841 	int i;
842 
843 	if (IS_ERR_OR_NULL(state))
844 		return;
845 
846 	drm_printf(p, "revision: %d (%d.%d.%d.%d)\n",
847 			adreno_gpu->info->revn, adreno_gpu->rev.core,
848 			adreno_gpu->rev.major, adreno_gpu->rev.minor,
849 			adreno_gpu->rev.patchid);
850 	/*
851 	 * If this is state collected due to iova fault, so fault related info
852 	 *
853 	 * TTBR0 would not be zero, so this is a good way to distinguish
854 	 */
855 	if (state->fault_info.ttbr0) {
856 		const struct msm_gpu_fault_info *info = &state->fault_info;
857 
858 		drm_puts(p, "fault-info:\n");
859 		drm_printf(p, "  - ttbr0=%.16llx\n", info->ttbr0);
860 		drm_printf(p, "  - iova=%.16lx\n", info->iova);
861 		drm_printf(p, "  - dir=%s\n", info->flags & IOMMU_FAULT_WRITE ? "WRITE" : "READ");
862 		drm_printf(p, "  - type=%s\n", info->type);
863 		drm_printf(p, "  - source=%s\n", info->block);
864 	}
865 
866 	drm_printf(p, "rbbm-status: 0x%08x\n", state->rbbm_status);
867 
868 	drm_puts(p, "ringbuffer:\n");
869 
870 	for (i = 0; i < gpu->nr_rings; i++) {
871 		drm_printf(p, "  - id: %d\n", i);
872 		drm_printf(p, "    iova: 0x%016llx\n", state->ring[i].iova);
873 		drm_printf(p, "    last-fence: %u\n", state->ring[i].seqno);
874 		drm_printf(p, "    retired-fence: %u\n", state->ring[i].fence);
875 		drm_printf(p, "    rptr: %u\n", state->ring[i].rptr);
876 		drm_printf(p, "    wptr: %u\n", state->ring[i].wptr);
877 		drm_printf(p, "    size: %u\n", MSM_GPU_RINGBUFFER_SZ);
878 
879 		adreno_show_object(p, &state->ring[i].data,
880 			state->ring[i].data_size, &state->ring[i].encoded);
881 	}
882 
883 	if (state->bos) {
884 		drm_puts(p, "bos:\n");
885 
886 		for (i = 0; i < state->nr_bos; i++) {
887 			drm_printf(p, "  - iova: 0x%016llx\n",
888 				state->bos[i].iova);
889 			drm_printf(p, "    size: %zd\n", state->bos[i].size);
890 			drm_printf(p, "    name: %-32s\n", state->bos[i].name);
891 
892 			adreno_show_object(p, &state->bos[i].data,
893 				state->bos[i].size, &state->bos[i].encoded);
894 		}
895 	}
896 
897 	if (state->nr_registers) {
898 		drm_puts(p, "registers:\n");
899 
900 		for (i = 0; i < state->nr_registers; i++) {
901 			drm_printf(p, "  - { offset: 0x%04x, value: 0x%08x }\n",
902 				state->registers[i * 2] << 2,
903 				state->registers[(i * 2) + 1]);
904 		}
905 	}
906 }
907 #endif
908 
909 /* Dump common gpu status and scratch registers on any hang, to make
910  * the hangcheck logs more useful.  The scratch registers seem always
911  * safe to read when GPU has hung (unlike some other regs, depending
912  * on how the GPU hung), and they are useful to match up to cmdstream
913  * dumps when debugging hangs:
914  */
915 void adreno_dump_info(struct msm_gpu *gpu)
916 {
917 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
918 	int i;
919 
920 	printk("revision: %d (%d.%d.%d.%d)\n",
921 			adreno_gpu->info->revn, adreno_gpu->rev.core,
922 			adreno_gpu->rev.major, adreno_gpu->rev.minor,
923 			adreno_gpu->rev.patchid);
924 
925 	for (i = 0; i < gpu->nr_rings; i++) {
926 		struct msm_ringbuffer *ring = gpu->rb[i];
927 
928 		printk("rb %d: fence:    %d/%d\n", i,
929 			ring->memptrs->fence,
930 			ring->fctx->last_fence);
931 
932 		printk("rptr:     %d\n", get_rptr(adreno_gpu, ring));
933 		printk("rb wptr:  %d\n", get_wptr(ring));
934 	}
935 }
936 
937 /* would be nice to not have to duplicate the _show() stuff with printk(): */
938 void adreno_dump(struct msm_gpu *gpu)
939 {
940 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
941 	int i;
942 
943 	if (!adreno_gpu->registers)
944 		return;
945 
946 	/* dump these out in a form that can be parsed by demsm: */
947 	printk("IO:region %s 00000000 00020000\n", gpu->name);
948 	for (i = 0; adreno_gpu->registers[i] != ~0; i += 2) {
949 		uint32_t start = adreno_gpu->registers[i];
950 		uint32_t end   = adreno_gpu->registers[i+1];
951 		uint32_t addr;
952 
953 		for (addr = start; addr <= end; addr++) {
954 			uint32_t val = gpu_read(gpu, addr);
955 			printk("IO:R %08x %08x\n", addr<<2, val);
956 		}
957 	}
958 }
959 
960 static uint32_t ring_freewords(struct msm_ringbuffer *ring)
961 {
962 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(ring->gpu);
963 	uint32_t size = MSM_GPU_RINGBUFFER_SZ >> 2;
964 	/* Use ring->next to calculate free size */
965 	uint32_t wptr = ring->next - ring->start;
966 	uint32_t rptr = get_rptr(adreno_gpu, ring);
967 	return (rptr + (size - 1) - wptr) % size;
968 }
969 
970 void adreno_wait_ring(struct msm_ringbuffer *ring, uint32_t ndwords)
971 {
972 	if (spin_until(ring_freewords(ring) >= ndwords))
973 		DRM_DEV_ERROR(ring->gpu->dev->dev,
974 			"timeout waiting for space in ringbuffer %d\n",
975 			ring->id);
976 }
977 
978 static int adreno_get_pwrlevels(struct device *dev,
979 		struct msm_gpu *gpu)
980 {
981 	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
982 	unsigned long freq = ULONG_MAX;
983 	struct dev_pm_opp *opp;
984 	int ret;
985 
986 	gpu->fast_rate = 0;
987 
988 	/* devm_pm_opp_of_add_table may error out but will still create an OPP table */
989 	ret = devm_pm_opp_of_add_table(dev);
990 	if (ret == -ENODEV) {
991 		/* Special cases for ancient hw with ancient DT bindings */
992 		if (adreno_is_a2xx(adreno_gpu)) {
993 			dev_warn(dev, "Unable to find the OPP table. Falling back to 200 MHz.\n");
994 			dev_pm_opp_add(dev, 200000000, 0);
995 		} else if (adreno_is_a320(adreno_gpu)) {
996 			dev_warn(dev, "Unable to find the OPP table. Falling back to 450 MHz.\n");
997 			dev_pm_opp_add(dev, 450000000, 0);
998 		} else {
999 			DRM_DEV_ERROR(dev, "Unable to find the OPP table\n");
1000 			return -ENODEV;
1001 		}
1002 	} else if (ret) {
1003 		DRM_DEV_ERROR(dev, "Unable to set the OPP table\n");
1004 		return ret;
1005 	}
1006 
1007 	/* Find the fastest defined rate */
1008 	opp = dev_pm_opp_find_freq_floor(dev, &freq);
1009 	if (IS_ERR(opp))
1010 		return PTR_ERR(opp);
1011 
1012 	gpu->fast_rate = freq;
1013 	dev_pm_opp_put(opp);
1014 
1015 	DBG("fast_rate=%u, slow_rate=27000000", gpu->fast_rate);
1016 
1017 	return 0;
1018 }
1019 
1020 int adreno_gpu_ocmem_init(struct device *dev, struct adreno_gpu *adreno_gpu,
1021 			  struct adreno_ocmem *adreno_ocmem)
1022 {
1023 	struct ocmem_buf *ocmem_hdl;
1024 	struct ocmem *ocmem;
1025 
1026 	ocmem = of_get_ocmem(dev);
1027 	if (IS_ERR(ocmem)) {
1028 		if (PTR_ERR(ocmem) == -ENODEV) {
1029 			/*
1030 			 * Return success since either the ocmem property was
1031 			 * not specified in device tree, or ocmem support is
1032 			 * not compiled into the kernel.
1033 			 */
1034 			return 0;
1035 		}
1036 
1037 		return PTR_ERR(ocmem);
1038 	}
1039 
1040 	ocmem_hdl = ocmem_allocate(ocmem, OCMEM_GRAPHICS, adreno_gpu->gmem);
1041 	if (IS_ERR(ocmem_hdl))
1042 		return PTR_ERR(ocmem_hdl);
1043 
1044 	adreno_ocmem->ocmem = ocmem;
1045 	adreno_ocmem->base = ocmem_hdl->addr;
1046 	adreno_ocmem->hdl = ocmem_hdl;
1047 	adreno_gpu->gmem = ocmem_hdl->len;
1048 
1049 	return 0;
1050 }
1051 
1052 void adreno_gpu_ocmem_cleanup(struct adreno_ocmem *adreno_ocmem)
1053 {
1054 	if (adreno_ocmem && adreno_ocmem->base)
1055 		ocmem_free(adreno_ocmem->ocmem, OCMEM_GRAPHICS,
1056 			   adreno_ocmem->hdl);
1057 }
1058 
1059 int adreno_read_speedbin(struct device *dev, u32 *speedbin)
1060 {
1061 	return nvmem_cell_read_variable_le_u32(dev, "speed_bin", speedbin);
1062 }
1063 
1064 int adreno_gpu_init(struct drm_device *drm, struct platform_device *pdev,
1065 		struct adreno_gpu *adreno_gpu,
1066 		const struct adreno_gpu_funcs *funcs, int nr_rings)
1067 {
1068 	struct device *dev = &pdev->dev;
1069 	struct adreno_platform_config *config = dev->platform_data;
1070 	struct msm_gpu_config adreno_gpu_config  = { 0 };
1071 	struct msm_gpu *gpu = &adreno_gpu->base;
1072 	struct adreno_rev *rev = &config->rev;
1073 	const char *gpu_name;
1074 	u32 speedbin;
1075 	int ret;
1076 
1077 	/* Only handle the core clock when GMU is not in use */
1078 	if (config->rev.core < 6) {
1079 		/*
1080 		 * This can only be done before devm_pm_opp_of_add_table(), or
1081 		 * dev_pm_opp_set_config() will WARN_ON()
1082 		 */
1083 		if (IS_ERR(devm_clk_get(dev, "core"))) {
1084 			/*
1085 			 * If "core" is absent, go for the legacy clock name.
1086 			 * If we got this far in probing, it's a given one of
1087 			 * them exists.
1088 			 */
1089 			devm_pm_opp_set_clkname(dev, "core_clk");
1090 		} else
1091 			devm_pm_opp_set_clkname(dev, "core");
1092 	}
1093 
1094 	adreno_gpu->funcs = funcs;
1095 	adreno_gpu->info = adreno_info(config->rev);
1096 	adreno_gpu->gmem = adreno_gpu->info->gmem;
1097 	adreno_gpu->revn = adreno_gpu->info->revn;
1098 	adreno_gpu->rev = *rev;
1099 
1100 	if (adreno_read_speedbin(dev, &speedbin) || !speedbin)
1101 		speedbin = 0xffff;
1102 	adreno_gpu->speedbin = (uint16_t) (0xffff & speedbin);
1103 
1104 	gpu_name = adreno_gpu->info->name;
1105 	if (!gpu_name) {
1106 		gpu_name = devm_kasprintf(dev, GFP_KERNEL, "%d.%d.%d.%d",
1107 				rev->core, rev->major, rev->minor,
1108 				rev->patchid);
1109 		if (!gpu_name)
1110 			return -ENOMEM;
1111 	}
1112 
1113 	adreno_gpu_config.ioname = "kgsl_3d0_reg_memory";
1114 
1115 	adreno_gpu_config.nr_rings = nr_rings;
1116 
1117 	ret = adreno_get_pwrlevels(dev, gpu);
1118 	if (ret)
1119 		return ret;
1120 
1121 	pm_runtime_set_autosuspend_delay(dev,
1122 		adreno_gpu->info->inactive_period);
1123 	pm_runtime_use_autosuspend(dev);
1124 
1125 	return msm_gpu_init(drm, pdev, &adreno_gpu->base, &funcs->base,
1126 			gpu_name, &adreno_gpu_config);
1127 }
1128 
1129 void adreno_gpu_cleanup(struct adreno_gpu *adreno_gpu)
1130 {
1131 	struct msm_gpu *gpu = &adreno_gpu->base;
1132 	struct msm_drm_private *priv = gpu->dev ? gpu->dev->dev_private : NULL;
1133 	unsigned int i;
1134 
1135 	for (i = 0; i < ARRAY_SIZE(adreno_gpu->info->fw); i++)
1136 		release_firmware(adreno_gpu->fw[i]);
1137 
1138 	if (priv && pm_runtime_enabled(&priv->gpu_pdev->dev))
1139 		pm_runtime_disable(&priv->gpu_pdev->dev);
1140 
1141 	msm_gpu_cleanup(&adreno_gpu->base);
1142 }
1143