1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Remote Processor Framework
4  *
5  * Copyright (C) 2011 Texas Instruments, Inc.
6  * Copyright (C) 2011 Google, Inc.
7  *
8  * Ohad Ben-Cohen <ohad@wizery.com>
9  * Brian Swetland <swetland@google.com>
10  * Mark Grosen <mgrosen@ti.com>
11  * Fernando Guzman Lugo <fernando.lugo@ti.com>
12  * Suman Anna <s-anna@ti.com>
13  * Robert Tivy <rtivy@ti.com>
14  * Armando Uribe De Leon <x0095078@ti.com>
15  */
16 
17 #define pr_fmt(fmt)    "%s: " fmt, __func__
18 
19 #include <linux/delay.h>
20 #include <linux/kernel.h>
21 #include <linux/module.h>
22 #include <linux/device.h>
23 #include <linux/slab.h>
24 #include <linux/mutex.h>
25 #include <linux/dma-mapping.h>
26 #include <linux/dma-direct.h> /* XXX: pokes into bus_dma_range */
27 #include <linux/firmware.h>
28 #include <linux/string.h>
29 #include <linux/debugfs.h>
30 #include <linux/rculist.h>
31 #include <linux/remoteproc.h>
32 #include <linux/iommu.h>
33 #include <linux/idr.h>
34 #include <linux/elf.h>
35 #include <linux/crc32.h>
36 #include <linux/of_reserved_mem.h>
37 #include <linux/virtio_ids.h>
38 #include <linux/virtio_ring.h>
39 #include <asm/byteorder.h>
40 #include <linux/platform_device.h>
41 
42 #include "remoteproc_internal.h"
43 
44 #define HIGH_BITS_MASK 0xFFFFFFFF00000000ULL
45 
46 static DEFINE_MUTEX(rproc_list_mutex);
47 static LIST_HEAD(rproc_list);
48 static struct notifier_block rproc_panic_nb;
49 
50 typedef int (*rproc_handle_resource_t)(struct rproc *rproc,
51 				 void *, int offset, int avail);
52 
53 static int rproc_alloc_carveout(struct rproc *rproc,
54 				struct rproc_mem_entry *mem);
55 static int rproc_release_carveout(struct rproc *rproc,
56 				  struct rproc_mem_entry *mem);
57 
58 /* Unique indices for remoteproc devices */
59 static DEFINE_IDA(rproc_dev_index);
60 
61 static const char * const rproc_crash_names[] = {
62 	[RPROC_MMUFAULT]	= "mmufault",
63 	[RPROC_WATCHDOG]	= "watchdog",
64 	[RPROC_FATAL_ERROR]	= "fatal error",
65 };
66 
67 /* translate rproc_crash_type to string */
68 static const char *rproc_crash_to_string(enum rproc_crash_type type)
69 {
70 	if (type < ARRAY_SIZE(rproc_crash_names))
71 		return rproc_crash_names[type];
72 	return "unknown";
73 }
74 
75 /*
76  * This is the IOMMU fault handler we register with the IOMMU API
77  * (when relevant; not all remote processors access memory through
78  * an IOMMU).
79  *
80  * IOMMU core will invoke this handler whenever the remote processor
81  * will try to access an unmapped device address.
82  */
83 static int rproc_iommu_fault(struct iommu_domain *domain, struct device *dev,
84 			     unsigned long iova, int flags, void *token)
85 {
86 	struct rproc *rproc = token;
87 
88 	dev_err(dev, "iommu fault: da 0x%lx flags 0x%x\n", iova, flags);
89 
90 	rproc_report_crash(rproc, RPROC_MMUFAULT);
91 
92 	/*
93 	 * Let the iommu core know we're not really handling this fault;
94 	 * we just used it as a recovery trigger.
95 	 */
96 	return -ENOSYS;
97 }
98 
99 static int rproc_enable_iommu(struct rproc *rproc)
100 {
101 	struct iommu_domain *domain;
102 	struct device *dev = rproc->dev.parent;
103 	int ret;
104 
105 	if (!rproc->has_iommu) {
106 		dev_dbg(dev, "iommu not present\n");
107 		return 0;
108 	}
109 
110 	domain = iommu_domain_alloc(dev->bus);
111 	if (!domain) {
112 		dev_err(dev, "can't alloc iommu domain\n");
113 		return -ENOMEM;
114 	}
115 
116 	iommu_set_fault_handler(domain, rproc_iommu_fault, rproc);
117 
118 	ret = iommu_attach_device(domain, dev);
119 	if (ret) {
120 		dev_err(dev, "can't attach iommu device: %d\n", ret);
121 		goto free_domain;
122 	}
123 
124 	rproc->domain = domain;
125 
126 	return 0;
127 
128 free_domain:
129 	iommu_domain_free(domain);
130 	return ret;
131 }
132 
133 static void rproc_disable_iommu(struct rproc *rproc)
134 {
135 	struct iommu_domain *domain = rproc->domain;
136 	struct device *dev = rproc->dev.parent;
137 
138 	if (!domain)
139 		return;
140 
141 	iommu_detach_device(domain, dev);
142 	iommu_domain_free(domain);
143 }
144 
145 phys_addr_t rproc_va_to_pa(void *cpu_addr)
146 {
147 	/*
148 	 * Return physical address according to virtual address location
149 	 * - in vmalloc: if region ioremapped or defined as dma_alloc_coherent
150 	 * - in kernel: if region allocated in generic dma memory pool
151 	 */
152 	if (is_vmalloc_addr(cpu_addr)) {
153 		return page_to_phys(vmalloc_to_page(cpu_addr)) +
154 				    offset_in_page(cpu_addr);
155 	}
156 
157 	WARN_ON(!virt_addr_valid(cpu_addr));
158 	return virt_to_phys(cpu_addr);
159 }
160 EXPORT_SYMBOL(rproc_va_to_pa);
161 
162 /**
163  * rproc_da_to_va() - lookup the kernel virtual address for a remoteproc address
164  * @rproc: handle of a remote processor
165  * @da: remoteproc device address to translate
166  * @len: length of the memory region @da is pointing to
167  *
168  * Some remote processors will ask us to allocate them physically contiguous
169  * memory regions (which we call "carveouts"), and map them to specific
170  * device addresses (which are hardcoded in the firmware). They may also have
171  * dedicated memory regions internal to the processors, and use them either
172  * exclusively or alongside carveouts.
173  *
174  * They may then ask us to copy objects into specific device addresses (e.g.
175  * code/data sections) or expose us certain symbols in other device address
176  * (e.g. their trace buffer).
177  *
178  * This function is a helper function with which we can go over the allocated
179  * carveouts and translate specific device addresses to kernel virtual addresses
180  * so we can access the referenced memory. This function also allows to perform
181  * translations on the internal remoteproc memory regions through a platform
182  * implementation specific da_to_va ops, if present.
183  *
184  * The function returns a valid kernel address on success or NULL on failure.
185  *
186  * Note: phys_to_virt(iommu_iova_to_phys(rproc->domain, da)) will work too,
187  * but only on kernel direct mapped RAM memory. Instead, we're just using
188  * here the output of the DMA API for the carveouts, which should be more
189  * correct.
190  */
191 void *rproc_da_to_va(struct rproc *rproc, u64 da, size_t len)
192 {
193 	struct rproc_mem_entry *carveout;
194 	void *ptr = NULL;
195 
196 	if (rproc->ops->da_to_va) {
197 		ptr = rproc->ops->da_to_va(rproc, da, len);
198 		if (ptr)
199 			goto out;
200 	}
201 
202 	list_for_each_entry(carveout, &rproc->carveouts, node) {
203 		int offset = da - carveout->da;
204 
205 		/*  Verify that carveout is allocated */
206 		if (!carveout->va)
207 			continue;
208 
209 		/* try next carveout if da is too small */
210 		if (offset < 0)
211 			continue;
212 
213 		/* try next carveout if da is too large */
214 		if (offset + len > carveout->len)
215 			continue;
216 
217 		ptr = carveout->va + offset;
218 
219 		break;
220 	}
221 
222 out:
223 	return ptr;
224 }
225 EXPORT_SYMBOL(rproc_da_to_va);
226 
227 /**
228  * rproc_find_carveout_by_name() - lookup the carveout region by a name
229  * @rproc: handle of a remote processor
230  * @name: carveout name to find (format string)
231  * @...: optional parameters matching @name string
232  *
233  * Platform driver has the capability to register some pre-allacoted carveout
234  * (physically contiguous memory regions) before rproc firmware loading and
235  * associated resource table analysis. These regions may be dedicated memory
236  * regions internal to the coprocessor or specified DDR region with specific
237  * attributes
238  *
239  * This function is a helper function with which we can go over the
240  * allocated carveouts and return associated region characteristics like
241  * coprocessor address, length or processor virtual address.
242  *
243  * Return: a valid pointer on carveout entry on success or NULL on failure.
244  */
245 __printf(2, 3)
246 struct rproc_mem_entry *
247 rproc_find_carveout_by_name(struct rproc *rproc, const char *name, ...)
248 {
249 	va_list args;
250 	char _name[32];
251 	struct rproc_mem_entry *carveout, *mem = NULL;
252 
253 	if (!name)
254 		return NULL;
255 
256 	va_start(args, name);
257 	vsnprintf(_name, sizeof(_name), name, args);
258 	va_end(args);
259 
260 	list_for_each_entry(carveout, &rproc->carveouts, node) {
261 		/* Compare carveout and requested names */
262 		if (!strcmp(carveout->name, _name)) {
263 			mem = carveout;
264 			break;
265 		}
266 	}
267 
268 	return mem;
269 }
270 
271 /**
272  * rproc_check_carveout_da() - Check specified carveout da configuration
273  * @rproc: handle of a remote processor
274  * @mem: pointer on carveout to check
275  * @da: area device address
276  * @len: associated area size
277  *
278  * This function is a helper function to verify requested device area (couple
279  * da, len) is part of specified carveout.
280  * If da is not set (defined as FW_RSC_ADDR_ANY), only requested length is
281  * checked.
282  *
283  * Return: 0 if carveout matches request else error
284  */
285 static int rproc_check_carveout_da(struct rproc *rproc,
286 				   struct rproc_mem_entry *mem, u32 da, u32 len)
287 {
288 	struct device *dev = &rproc->dev;
289 	int delta;
290 
291 	/* Check requested resource length */
292 	if (len > mem->len) {
293 		dev_err(dev, "Registered carveout doesn't fit len request\n");
294 		return -EINVAL;
295 	}
296 
297 	if (da != FW_RSC_ADDR_ANY && mem->da == FW_RSC_ADDR_ANY) {
298 		/* Address doesn't match registered carveout configuration */
299 		return -EINVAL;
300 	} else if (da != FW_RSC_ADDR_ANY && mem->da != FW_RSC_ADDR_ANY) {
301 		delta = da - mem->da;
302 
303 		/* Check requested resource belongs to registered carveout */
304 		if (delta < 0) {
305 			dev_err(dev,
306 				"Registered carveout doesn't fit da request\n");
307 			return -EINVAL;
308 		}
309 
310 		if (delta + len > mem->len) {
311 			dev_err(dev,
312 				"Registered carveout doesn't fit len request\n");
313 			return -EINVAL;
314 		}
315 	}
316 
317 	return 0;
318 }
319 
320 int rproc_alloc_vring(struct rproc_vdev *rvdev, int i)
321 {
322 	struct rproc *rproc = rvdev->rproc;
323 	struct device *dev = &rproc->dev;
324 	struct rproc_vring *rvring = &rvdev->vring[i];
325 	struct fw_rsc_vdev *rsc;
326 	int ret, notifyid;
327 	struct rproc_mem_entry *mem;
328 	size_t size;
329 
330 	/* actual size of vring (in bytes) */
331 	size = PAGE_ALIGN(vring_size(rvring->len, rvring->align));
332 
333 	rsc = (void *)rproc->table_ptr + rvdev->rsc_offset;
334 
335 	/* Search for pre-registered carveout */
336 	mem = rproc_find_carveout_by_name(rproc, "vdev%dvring%d", rvdev->index,
337 					  i);
338 	if (mem) {
339 		if (rproc_check_carveout_da(rproc, mem, rsc->vring[i].da, size))
340 			return -ENOMEM;
341 	} else {
342 		/* Register carveout in in list */
343 		mem = rproc_mem_entry_init(dev, NULL, 0,
344 					   size, rsc->vring[i].da,
345 					   rproc_alloc_carveout,
346 					   rproc_release_carveout,
347 					   "vdev%dvring%d",
348 					   rvdev->index, i);
349 		if (!mem) {
350 			dev_err(dev, "Can't allocate memory entry structure\n");
351 			return -ENOMEM;
352 		}
353 
354 		rproc_add_carveout(rproc, mem);
355 	}
356 
357 	/*
358 	 * Assign an rproc-wide unique index for this vring
359 	 * TODO: assign a notifyid for rvdev updates as well
360 	 * TODO: support predefined notifyids (via resource table)
361 	 */
362 	ret = idr_alloc(&rproc->notifyids, rvring, 0, 0, GFP_KERNEL);
363 	if (ret < 0) {
364 		dev_err(dev, "idr_alloc failed: %d\n", ret);
365 		return ret;
366 	}
367 	notifyid = ret;
368 
369 	/* Potentially bump max_notifyid */
370 	if (notifyid > rproc->max_notifyid)
371 		rproc->max_notifyid = notifyid;
372 
373 	rvring->notifyid = notifyid;
374 
375 	/* Let the rproc know the notifyid of this vring.*/
376 	rsc->vring[i].notifyid = notifyid;
377 	return 0;
378 }
379 
380 static int
381 rproc_parse_vring(struct rproc_vdev *rvdev, struct fw_rsc_vdev *rsc, int i)
382 {
383 	struct rproc *rproc = rvdev->rproc;
384 	struct device *dev = &rproc->dev;
385 	struct fw_rsc_vdev_vring *vring = &rsc->vring[i];
386 	struct rproc_vring *rvring = &rvdev->vring[i];
387 
388 	dev_dbg(dev, "vdev rsc: vring%d: da 0x%x, qsz %d, align %d\n",
389 		i, vring->da, vring->num, vring->align);
390 
391 	/* verify queue size and vring alignment are sane */
392 	if (!vring->num || !vring->align) {
393 		dev_err(dev, "invalid qsz (%d) or alignment (%d)\n",
394 			vring->num, vring->align);
395 		return -EINVAL;
396 	}
397 
398 	rvring->len = vring->num;
399 	rvring->align = vring->align;
400 	rvring->rvdev = rvdev;
401 
402 	return 0;
403 }
404 
405 void rproc_free_vring(struct rproc_vring *rvring)
406 {
407 	struct rproc *rproc = rvring->rvdev->rproc;
408 	int idx = rvring - rvring->rvdev->vring;
409 	struct fw_rsc_vdev *rsc;
410 
411 	idr_remove(&rproc->notifyids, rvring->notifyid);
412 
413 	/*
414 	 * At this point rproc_stop() has been called and the installed resource
415 	 * table in the remote processor memory may no longer be accessible. As
416 	 * such and as per rproc_stop(), rproc->table_ptr points to the cached
417 	 * resource table (rproc->cached_table).  The cached resource table is
418 	 * only available when a remote processor has been booted by the
419 	 * remoteproc core, otherwise it is NULL.
420 	 *
421 	 * Based on the above, reset the virtio device section in the cached
422 	 * resource table only if there is one to work with.
423 	 */
424 	if (rproc->table_ptr) {
425 		rsc = (void *)rproc->table_ptr + rvring->rvdev->rsc_offset;
426 		rsc->vring[idx].da = 0;
427 		rsc->vring[idx].notifyid = -1;
428 	}
429 }
430 
431 static int rproc_vdev_do_start(struct rproc_subdev *subdev)
432 {
433 	struct rproc_vdev *rvdev = container_of(subdev, struct rproc_vdev, subdev);
434 
435 	return rproc_add_virtio_dev(rvdev, rvdev->id);
436 }
437 
438 static void rproc_vdev_do_stop(struct rproc_subdev *subdev, bool crashed)
439 {
440 	struct rproc_vdev *rvdev = container_of(subdev, struct rproc_vdev, subdev);
441 	int ret;
442 
443 	ret = device_for_each_child(&rvdev->dev, NULL, rproc_remove_virtio_dev);
444 	if (ret)
445 		dev_warn(&rvdev->dev, "can't remove vdev child device: %d\n", ret);
446 }
447 
448 /**
449  * rproc_rvdev_release() - release the existence of a rvdev
450  *
451  * @dev: the subdevice's dev
452  */
453 static void rproc_rvdev_release(struct device *dev)
454 {
455 	struct rproc_vdev *rvdev = container_of(dev, struct rproc_vdev, dev);
456 
457 	of_reserved_mem_device_release(dev);
458 
459 	kfree(rvdev);
460 }
461 
462 static int copy_dma_range_map(struct device *to, struct device *from)
463 {
464 	const struct bus_dma_region *map = from->dma_range_map, *new_map, *r;
465 	int num_ranges = 0;
466 
467 	if (!map)
468 		return 0;
469 
470 	for (r = map; r->size; r++)
471 		num_ranges++;
472 
473 	new_map = kmemdup(map, array_size(num_ranges + 1, sizeof(*map)),
474 			  GFP_KERNEL);
475 	if (!new_map)
476 		return -ENOMEM;
477 	to->dma_range_map = new_map;
478 	return 0;
479 }
480 
481 /**
482  * rproc_handle_vdev() - handle a vdev fw resource
483  * @rproc: the remote processor
484  * @rsc: the vring resource descriptor
485  * @offset: offset of the resource entry
486  * @avail: size of available data (for sanity checking the image)
487  *
488  * This resource entry requests the host to statically register a virtio
489  * device (vdev), and setup everything needed to support it. It contains
490  * everything needed to make it possible: the virtio device id, virtio
491  * device features, vrings information, virtio config space, etc...
492  *
493  * Before registering the vdev, the vrings are allocated from non-cacheable
494  * physically contiguous memory. Currently we only support two vrings per
495  * remote processor (temporary limitation). We might also want to consider
496  * doing the vring allocation only later when ->find_vqs() is invoked, and
497  * then release them upon ->del_vqs().
498  *
499  * Note: @da is currently not really handled correctly: we dynamically
500  * allocate it using the DMA API, ignoring requested hard coded addresses,
501  * and we don't take care of any required IOMMU programming. This is all
502  * going to be taken care of when the generic iommu-based DMA API will be
503  * merged. Meanwhile, statically-addressed iommu-based firmware images should
504  * use RSC_DEVMEM resource entries to map their required @da to the physical
505  * address of their base CMA region (ouch, hacky!).
506  *
507  * Returns 0 on success, or an appropriate error code otherwise
508  */
509 static int rproc_handle_vdev(struct rproc *rproc, struct fw_rsc_vdev *rsc,
510 			     int offset, int avail)
511 {
512 	struct device *dev = &rproc->dev;
513 	struct rproc_vdev *rvdev;
514 	int i, ret;
515 	char name[16];
516 
517 	/* make sure resource isn't truncated */
518 	if (struct_size(rsc, vring, rsc->num_of_vrings) + rsc->config_len >
519 			avail) {
520 		dev_err(dev, "vdev rsc is truncated\n");
521 		return -EINVAL;
522 	}
523 
524 	/* make sure reserved bytes are zeroes */
525 	if (rsc->reserved[0] || rsc->reserved[1]) {
526 		dev_err(dev, "vdev rsc has non zero reserved bytes\n");
527 		return -EINVAL;
528 	}
529 
530 	dev_dbg(dev, "vdev rsc: id %d, dfeatures 0x%x, cfg len %d, %d vrings\n",
531 		rsc->id, rsc->dfeatures, rsc->config_len, rsc->num_of_vrings);
532 
533 	/* we currently support only two vrings per rvdev */
534 	if (rsc->num_of_vrings > ARRAY_SIZE(rvdev->vring)) {
535 		dev_err(dev, "too many vrings: %d\n", rsc->num_of_vrings);
536 		return -EINVAL;
537 	}
538 
539 	rvdev = kzalloc(sizeof(*rvdev), GFP_KERNEL);
540 	if (!rvdev)
541 		return -ENOMEM;
542 
543 	kref_init(&rvdev->refcount);
544 
545 	rvdev->id = rsc->id;
546 	rvdev->rproc = rproc;
547 	rvdev->index = rproc->nb_vdev++;
548 
549 	/* Initialise vdev subdevice */
550 	snprintf(name, sizeof(name), "vdev%dbuffer", rvdev->index);
551 	rvdev->dev.parent = &rproc->dev;
552 	ret = copy_dma_range_map(&rvdev->dev, rproc->dev.parent);
553 	if (ret)
554 		return ret;
555 	rvdev->dev.release = rproc_rvdev_release;
556 	dev_set_name(&rvdev->dev, "%s#%s", dev_name(rvdev->dev.parent), name);
557 	dev_set_drvdata(&rvdev->dev, rvdev);
558 
559 	ret = device_register(&rvdev->dev);
560 	if (ret) {
561 		put_device(&rvdev->dev);
562 		return ret;
563 	}
564 	/* Make device dma capable by inheriting from parent's capabilities */
565 	set_dma_ops(&rvdev->dev, get_dma_ops(rproc->dev.parent));
566 
567 	ret = dma_coerce_mask_and_coherent(&rvdev->dev,
568 					   dma_get_mask(rproc->dev.parent));
569 	if (ret) {
570 		dev_warn(dev,
571 			 "Failed to set DMA mask %llx. Trying to continue... %x\n",
572 			 dma_get_mask(rproc->dev.parent), ret);
573 	}
574 
575 	/* parse the vrings */
576 	for (i = 0; i < rsc->num_of_vrings; i++) {
577 		ret = rproc_parse_vring(rvdev, rsc, i);
578 		if (ret)
579 			goto free_rvdev;
580 	}
581 
582 	/* remember the resource offset*/
583 	rvdev->rsc_offset = offset;
584 
585 	/* allocate the vring resources */
586 	for (i = 0; i < rsc->num_of_vrings; i++) {
587 		ret = rproc_alloc_vring(rvdev, i);
588 		if (ret)
589 			goto unwind_vring_allocations;
590 	}
591 
592 	list_add_tail(&rvdev->node, &rproc->rvdevs);
593 
594 	rvdev->subdev.start = rproc_vdev_do_start;
595 	rvdev->subdev.stop = rproc_vdev_do_stop;
596 
597 	rproc_add_subdev(rproc, &rvdev->subdev);
598 
599 	return 0;
600 
601 unwind_vring_allocations:
602 	for (i--; i >= 0; i--)
603 		rproc_free_vring(&rvdev->vring[i]);
604 free_rvdev:
605 	device_unregister(&rvdev->dev);
606 	return ret;
607 }
608 
609 void rproc_vdev_release(struct kref *ref)
610 {
611 	struct rproc_vdev *rvdev = container_of(ref, struct rproc_vdev, refcount);
612 	struct rproc_vring *rvring;
613 	struct rproc *rproc = rvdev->rproc;
614 	int id;
615 
616 	for (id = 0; id < ARRAY_SIZE(rvdev->vring); id++) {
617 		rvring = &rvdev->vring[id];
618 		rproc_free_vring(rvring);
619 	}
620 
621 	rproc_remove_subdev(rproc, &rvdev->subdev);
622 	list_del(&rvdev->node);
623 	device_unregister(&rvdev->dev);
624 }
625 
626 /**
627  * rproc_handle_trace() - handle a shared trace buffer resource
628  * @rproc: the remote processor
629  * @rsc: the trace resource descriptor
630  * @offset: offset of the resource entry
631  * @avail: size of available data (for sanity checking the image)
632  *
633  * In case the remote processor dumps trace logs into memory,
634  * export it via debugfs.
635  *
636  * Currently, the 'da' member of @rsc should contain the device address
637  * where the remote processor is dumping the traces. Later we could also
638  * support dynamically allocating this address using the generic
639  * DMA API (but currently there isn't a use case for that).
640  *
641  * Returns 0 on success, or an appropriate error code otherwise
642  */
643 static int rproc_handle_trace(struct rproc *rproc, struct fw_rsc_trace *rsc,
644 			      int offset, int avail)
645 {
646 	struct rproc_debug_trace *trace;
647 	struct device *dev = &rproc->dev;
648 	char name[15];
649 
650 	if (sizeof(*rsc) > avail) {
651 		dev_err(dev, "trace rsc is truncated\n");
652 		return -EINVAL;
653 	}
654 
655 	/* make sure reserved bytes are zeroes */
656 	if (rsc->reserved) {
657 		dev_err(dev, "trace rsc has non zero reserved bytes\n");
658 		return -EINVAL;
659 	}
660 
661 	trace = kzalloc(sizeof(*trace), GFP_KERNEL);
662 	if (!trace)
663 		return -ENOMEM;
664 
665 	/* set the trace buffer dma properties */
666 	trace->trace_mem.len = rsc->len;
667 	trace->trace_mem.da = rsc->da;
668 
669 	/* set pointer on rproc device */
670 	trace->rproc = rproc;
671 
672 	/* make sure snprintf always null terminates, even if truncating */
673 	snprintf(name, sizeof(name), "trace%d", rproc->num_traces);
674 
675 	/* create the debugfs entry */
676 	trace->tfile = rproc_create_trace_file(name, rproc, trace);
677 	if (!trace->tfile) {
678 		kfree(trace);
679 		return -EINVAL;
680 	}
681 
682 	list_add_tail(&trace->node, &rproc->traces);
683 
684 	rproc->num_traces++;
685 
686 	dev_dbg(dev, "%s added: da 0x%x, len 0x%x\n",
687 		name, rsc->da, rsc->len);
688 
689 	return 0;
690 }
691 
692 /**
693  * rproc_handle_devmem() - handle devmem resource entry
694  * @rproc: remote processor handle
695  * @rsc: the devmem resource entry
696  * @offset: offset of the resource entry
697  * @avail: size of available data (for sanity checking the image)
698  *
699  * Remote processors commonly need to access certain on-chip peripherals.
700  *
701  * Some of these remote processors access memory via an iommu device,
702  * and might require us to configure their iommu before they can access
703  * the on-chip peripherals they need.
704  *
705  * This resource entry is a request to map such a peripheral device.
706  *
707  * These devmem entries will contain the physical address of the device in
708  * the 'pa' member. If a specific device address is expected, then 'da' will
709  * contain it (currently this is the only use case supported). 'len' will
710  * contain the size of the physical region we need to map.
711  *
712  * Currently we just "trust" those devmem entries to contain valid physical
713  * addresses, but this is going to change: we want the implementations to
714  * tell us ranges of physical addresses the firmware is allowed to request,
715  * and not allow firmwares to request access to physical addresses that
716  * are outside those ranges.
717  */
718 static int rproc_handle_devmem(struct rproc *rproc, struct fw_rsc_devmem *rsc,
719 			       int offset, int avail)
720 {
721 	struct rproc_mem_entry *mapping;
722 	struct device *dev = &rproc->dev;
723 	int ret;
724 
725 	/* no point in handling this resource without a valid iommu domain */
726 	if (!rproc->domain)
727 		return -EINVAL;
728 
729 	if (sizeof(*rsc) > avail) {
730 		dev_err(dev, "devmem rsc is truncated\n");
731 		return -EINVAL;
732 	}
733 
734 	/* make sure reserved bytes are zeroes */
735 	if (rsc->reserved) {
736 		dev_err(dev, "devmem rsc has non zero reserved bytes\n");
737 		return -EINVAL;
738 	}
739 
740 	mapping = kzalloc(sizeof(*mapping), GFP_KERNEL);
741 	if (!mapping)
742 		return -ENOMEM;
743 
744 	ret = iommu_map(rproc->domain, rsc->da, rsc->pa, rsc->len, rsc->flags);
745 	if (ret) {
746 		dev_err(dev, "failed to map devmem: %d\n", ret);
747 		goto out;
748 	}
749 
750 	/*
751 	 * We'll need this info later when we'll want to unmap everything
752 	 * (e.g. on shutdown).
753 	 *
754 	 * We can't trust the remote processor not to change the resource
755 	 * table, so we must maintain this info independently.
756 	 */
757 	mapping->da = rsc->da;
758 	mapping->len = rsc->len;
759 	list_add_tail(&mapping->node, &rproc->mappings);
760 
761 	dev_dbg(dev, "mapped devmem pa 0x%x, da 0x%x, len 0x%x\n",
762 		rsc->pa, rsc->da, rsc->len);
763 
764 	return 0;
765 
766 out:
767 	kfree(mapping);
768 	return ret;
769 }
770 
771 /**
772  * rproc_alloc_carveout() - allocated specified carveout
773  * @rproc: rproc handle
774  * @mem: the memory entry to allocate
775  *
776  * This function allocate specified memory entry @mem using
777  * dma_alloc_coherent() as default allocator
778  */
779 static int rproc_alloc_carveout(struct rproc *rproc,
780 				struct rproc_mem_entry *mem)
781 {
782 	struct rproc_mem_entry *mapping = NULL;
783 	struct device *dev = &rproc->dev;
784 	dma_addr_t dma;
785 	void *va;
786 	int ret;
787 
788 	va = dma_alloc_coherent(dev->parent, mem->len, &dma, GFP_KERNEL);
789 	if (!va) {
790 		dev_err(dev->parent,
791 			"failed to allocate dma memory: len 0x%zx\n",
792 			mem->len);
793 		return -ENOMEM;
794 	}
795 
796 	dev_dbg(dev, "carveout va %pK, dma %pad, len 0x%zx\n",
797 		va, &dma, mem->len);
798 
799 	if (mem->da != FW_RSC_ADDR_ANY && !rproc->domain) {
800 		/*
801 		 * Check requested da is equal to dma address
802 		 * and print a warn message in case of missalignment.
803 		 * Don't stop rproc_start sequence as coprocessor may
804 		 * build pa to da translation on its side.
805 		 */
806 		if (mem->da != (u32)dma)
807 			dev_warn(dev->parent,
808 				 "Allocated carveout doesn't fit device address request\n");
809 	}
810 
811 	/*
812 	 * Ok, this is non-standard.
813 	 *
814 	 * Sometimes we can't rely on the generic iommu-based DMA API
815 	 * to dynamically allocate the device address and then set the IOMMU
816 	 * tables accordingly, because some remote processors might
817 	 * _require_ us to use hard coded device addresses that their
818 	 * firmware was compiled with.
819 	 *
820 	 * In this case, we must use the IOMMU API directly and map
821 	 * the memory to the device address as expected by the remote
822 	 * processor.
823 	 *
824 	 * Obviously such remote processor devices should not be configured
825 	 * to use the iommu-based DMA API: we expect 'dma' to contain the
826 	 * physical address in this case.
827 	 */
828 	if (mem->da != FW_RSC_ADDR_ANY && rproc->domain) {
829 		mapping = kzalloc(sizeof(*mapping), GFP_KERNEL);
830 		if (!mapping) {
831 			ret = -ENOMEM;
832 			goto dma_free;
833 		}
834 
835 		ret = iommu_map(rproc->domain, mem->da, dma, mem->len,
836 				mem->flags);
837 		if (ret) {
838 			dev_err(dev, "iommu_map failed: %d\n", ret);
839 			goto free_mapping;
840 		}
841 
842 		/*
843 		 * We'll need this info later when we'll want to unmap
844 		 * everything (e.g. on shutdown).
845 		 *
846 		 * We can't trust the remote processor not to change the
847 		 * resource table, so we must maintain this info independently.
848 		 */
849 		mapping->da = mem->da;
850 		mapping->len = mem->len;
851 		list_add_tail(&mapping->node, &rproc->mappings);
852 
853 		dev_dbg(dev, "carveout mapped 0x%x to %pad\n",
854 			mem->da, &dma);
855 	}
856 
857 	if (mem->da == FW_RSC_ADDR_ANY) {
858 		/* Update device address as undefined by requester */
859 		if ((u64)dma & HIGH_BITS_MASK)
860 			dev_warn(dev, "DMA address cast in 32bit to fit resource table format\n");
861 
862 		mem->da = (u32)dma;
863 	}
864 
865 	mem->dma = dma;
866 	mem->va = va;
867 
868 	return 0;
869 
870 free_mapping:
871 	kfree(mapping);
872 dma_free:
873 	dma_free_coherent(dev->parent, mem->len, va, dma);
874 	return ret;
875 }
876 
877 /**
878  * rproc_release_carveout() - release acquired carveout
879  * @rproc: rproc handle
880  * @mem: the memory entry to release
881  *
882  * This function releases specified memory entry @mem allocated via
883  * rproc_alloc_carveout() function by @rproc.
884  */
885 static int rproc_release_carveout(struct rproc *rproc,
886 				  struct rproc_mem_entry *mem)
887 {
888 	struct device *dev = &rproc->dev;
889 
890 	/* clean up carveout allocations */
891 	dma_free_coherent(dev->parent, mem->len, mem->va, mem->dma);
892 	return 0;
893 }
894 
895 /**
896  * rproc_handle_carveout() - handle phys contig memory allocation requests
897  * @rproc: rproc handle
898  * @rsc: the resource entry
899  * @offset: offset of the resource entry
900  * @avail: size of available data (for image validation)
901  *
902  * This function will handle firmware requests for allocation of physically
903  * contiguous memory regions.
904  *
905  * These request entries should come first in the firmware's resource table,
906  * as other firmware entries might request placing other data objects inside
907  * these memory regions (e.g. data/code segments, trace resource entries, ...).
908  *
909  * Allocating memory this way helps utilizing the reserved physical memory
910  * (e.g. CMA) more efficiently, and also minimizes the number of TLB entries
911  * needed to map it (in case @rproc is using an IOMMU). Reducing the TLB
912  * pressure is important; it may have a substantial impact on performance.
913  */
914 static int rproc_handle_carveout(struct rproc *rproc,
915 				 struct fw_rsc_carveout *rsc,
916 				 int offset, int avail)
917 {
918 	struct rproc_mem_entry *carveout;
919 	struct device *dev = &rproc->dev;
920 
921 	if (sizeof(*rsc) > avail) {
922 		dev_err(dev, "carveout rsc is truncated\n");
923 		return -EINVAL;
924 	}
925 
926 	/* make sure reserved bytes are zeroes */
927 	if (rsc->reserved) {
928 		dev_err(dev, "carveout rsc has non zero reserved bytes\n");
929 		return -EINVAL;
930 	}
931 
932 	dev_dbg(dev, "carveout rsc: name: %s, da 0x%x, pa 0x%x, len 0x%x, flags 0x%x\n",
933 		rsc->name, rsc->da, rsc->pa, rsc->len, rsc->flags);
934 
935 	/*
936 	 * Check carveout rsc already part of a registered carveout,
937 	 * Search by name, then check the da and length
938 	 */
939 	carveout = rproc_find_carveout_by_name(rproc, rsc->name);
940 
941 	if (carveout) {
942 		if (carveout->rsc_offset != FW_RSC_ADDR_ANY) {
943 			dev_err(dev,
944 				"Carveout already associated to resource table\n");
945 			return -ENOMEM;
946 		}
947 
948 		if (rproc_check_carveout_da(rproc, carveout, rsc->da, rsc->len))
949 			return -ENOMEM;
950 
951 		/* Update memory carveout with resource table info */
952 		carveout->rsc_offset = offset;
953 		carveout->flags = rsc->flags;
954 
955 		return 0;
956 	}
957 
958 	/* Register carveout in in list */
959 	carveout = rproc_mem_entry_init(dev, NULL, 0, rsc->len, rsc->da,
960 					rproc_alloc_carveout,
961 					rproc_release_carveout, rsc->name);
962 	if (!carveout) {
963 		dev_err(dev, "Can't allocate memory entry structure\n");
964 		return -ENOMEM;
965 	}
966 
967 	carveout->flags = rsc->flags;
968 	carveout->rsc_offset = offset;
969 	rproc_add_carveout(rproc, carveout);
970 
971 	return 0;
972 }
973 
974 /**
975  * rproc_add_carveout() - register an allocated carveout region
976  * @rproc: rproc handle
977  * @mem: memory entry to register
978  *
979  * This function registers specified memory entry in @rproc carveouts list.
980  * Specified carveout should have been allocated before registering.
981  */
982 void rproc_add_carveout(struct rproc *rproc, struct rproc_mem_entry *mem)
983 {
984 	list_add_tail(&mem->node, &rproc->carveouts);
985 }
986 EXPORT_SYMBOL(rproc_add_carveout);
987 
988 /**
989  * rproc_mem_entry_init() - allocate and initialize rproc_mem_entry struct
990  * @dev: pointer on device struct
991  * @va: virtual address
992  * @dma: dma address
993  * @len: memory carveout length
994  * @da: device address
995  * @alloc: memory carveout allocation function
996  * @release: memory carveout release function
997  * @name: carveout name
998  *
999  * This function allocates a rproc_mem_entry struct and fill it with parameters
1000  * provided by client.
1001  */
1002 __printf(8, 9)
1003 struct rproc_mem_entry *
1004 rproc_mem_entry_init(struct device *dev,
1005 		     void *va, dma_addr_t dma, size_t len, u32 da,
1006 		     int (*alloc)(struct rproc *, struct rproc_mem_entry *),
1007 		     int (*release)(struct rproc *, struct rproc_mem_entry *),
1008 		     const char *name, ...)
1009 {
1010 	struct rproc_mem_entry *mem;
1011 	va_list args;
1012 
1013 	mem = kzalloc(sizeof(*mem), GFP_KERNEL);
1014 	if (!mem)
1015 		return mem;
1016 
1017 	mem->va = va;
1018 	mem->dma = dma;
1019 	mem->da = da;
1020 	mem->len = len;
1021 	mem->alloc = alloc;
1022 	mem->release = release;
1023 	mem->rsc_offset = FW_RSC_ADDR_ANY;
1024 	mem->of_resm_idx = -1;
1025 
1026 	va_start(args, name);
1027 	vsnprintf(mem->name, sizeof(mem->name), name, args);
1028 	va_end(args);
1029 
1030 	return mem;
1031 }
1032 EXPORT_SYMBOL(rproc_mem_entry_init);
1033 
1034 /**
1035  * rproc_of_resm_mem_entry_init() - allocate and initialize rproc_mem_entry struct
1036  * from a reserved memory phandle
1037  * @dev: pointer on device struct
1038  * @of_resm_idx: reserved memory phandle index in "memory-region"
1039  * @len: memory carveout length
1040  * @da: device address
1041  * @name: carveout name
1042  *
1043  * This function allocates a rproc_mem_entry struct and fill it with parameters
1044  * provided by client.
1045  */
1046 __printf(5, 6)
1047 struct rproc_mem_entry *
1048 rproc_of_resm_mem_entry_init(struct device *dev, u32 of_resm_idx, size_t len,
1049 			     u32 da, const char *name, ...)
1050 {
1051 	struct rproc_mem_entry *mem;
1052 	va_list args;
1053 
1054 	mem = kzalloc(sizeof(*mem), GFP_KERNEL);
1055 	if (!mem)
1056 		return mem;
1057 
1058 	mem->da = da;
1059 	mem->len = len;
1060 	mem->rsc_offset = FW_RSC_ADDR_ANY;
1061 	mem->of_resm_idx = of_resm_idx;
1062 
1063 	va_start(args, name);
1064 	vsnprintf(mem->name, sizeof(mem->name), name, args);
1065 	va_end(args);
1066 
1067 	return mem;
1068 }
1069 EXPORT_SYMBOL(rproc_of_resm_mem_entry_init);
1070 
1071 /**
1072  * rproc_of_parse_firmware() - parse and return the firmware-name
1073  * @dev: pointer on device struct representing a rproc
1074  * @index: index to use for the firmware-name retrieval
1075  * @fw_name: pointer to a character string, in which the firmware
1076  *           name is returned on success and unmodified otherwise.
1077  *
1078  * This is an OF helper function that parses a device's DT node for
1079  * the "firmware-name" property and returns the firmware name pointer
1080  * in @fw_name on success.
1081  *
1082  * Return: 0 on success, or an appropriate failure.
1083  */
1084 int rproc_of_parse_firmware(struct device *dev, int index, const char **fw_name)
1085 {
1086 	int ret;
1087 
1088 	ret = of_property_read_string_index(dev->of_node, "firmware-name",
1089 					    index, fw_name);
1090 	return ret ? ret : 0;
1091 }
1092 EXPORT_SYMBOL(rproc_of_parse_firmware);
1093 
1094 /*
1095  * A lookup table for resource handlers. The indices are defined in
1096  * enum fw_resource_type.
1097  */
1098 static rproc_handle_resource_t rproc_loading_handlers[RSC_LAST] = {
1099 	[RSC_CARVEOUT] = (rproc_handle_resource_t)rproc_handle_carveout,
1100 	[RSC_DEVMEM] = (rproc_handle_resource_t)rproc_handle_devmem,
1101 	[RSC_TRACE] = (rproc_handle_resource_t)rproc_handle_trace,
1102 	[RSC_VDEV] = (rproc_handle_resource_t)rproc_handle_vdev,
1103 };
1104 
1105 /* handle firmware resource entries before booting the remote processor */
1106 static int rproc_handle_resources(struct rproc *rproc,
1107 				  rproc_handle_resource_t handlers[RSC_LAST])
1108 {
1109 	struct device *dev = &rproc->dev;
1110 	rproc_handle_resource_t handler;
1111 	int ret = 0, i;
1112 
1113 	if (!rproc->table_ptr)
1114 		return 0;
1115 
1116 	for (i = 0; i < rproc->table_ptr->num; i++) {
1117 		int offset = rproc->table_ptr->offset[i];
1118 		struct fw_rsc_hdr *hdr = (void *)rproc->table_ptr + offset;
1119 		int avail = rproc->table_sz - offset - sizeof(*hdr);
1120 		void *rsc = (void *)hdr + sizeof(*hdr);
1121 
1122 		/* make sure table isn't truncated */
1123 		if (avail < 0) {
1124 			dev_err(dev, "rsc table is truncated\n");
1125 			return -EINVAL;
1126 		}
1127 
1128 		dev_dbg(dev, "rsc: type %d\n", hdr->type);
1129 
1130 		if (hdr->type >= RSC_VENDOR_START &&
1131 		    hdr->type <= RSC_VENDOR_END) {
1132 			ret = rproc_handle_rsc(rproc, hdr->type, rsc,
1133 					       offset + sizeof(*hdr), avail);
1134 			if (ret == RSC_HANDLED)
1135 				continue;
1136 			else if (ret < 0)
1137 				break;
1138 
1139 			dev_warn(dev, "unsupported vendor resource %d\n",
1140 				 hdr->type);
1141 			continue;
1142 		}
1143 
1144 		if (hdr->type >= RSC_LAST) {
1145 			dev_warn(dev, "unsupported resource %d\n", hdr->type);
1146 			continue;
1147 		}
1148 
1149 		handler = handlers[hdr->type];
1150 		if (!handler)
1151 			continue;
1152 
1153 		ret = handler(rproc, rsc, offset + sizeof(*hdr), avail);
1154 		if (ret)
1155 			break;
1156 	}
1157 
1158 	return ret;
1159 }
1160 
1161 static int rproc_prepare_subdevices(struct rproc *rproc)
1162 {
1163 	struct rproc_subdev *subdev;
1164 	int ret;
1165 
1166 	list_for_each_entry(subdev, &rproc->subdevs, node) {
1167 		if (subdev->prepare) {
1168 			ret = subdev->prepare(subdev);
1169 			if (ret)
1170 				goto unroll_preparation;
1171 		}
1172 	}
1173 
1174 	return 0;
1175 
1176 unroll_preparation:
1177 	list_for_each_entry_continue_reverse(subdev, &rproc->subdevs, node) {
1178 		if (subdev->unprepare)
1179 			subdev->unprepare(subdev);
1180 	}
1181 
1182 	return ret;
1183 }
1184 
1185 static int rproc_start_subdevices(struct rproc *rproc)
1186 {
1187 	struct rproc_subdev *subdev;
1188 	int ret;
1189 
1190 	list_for_each_entry(subdev, &rproc->subdevs, node) {
1191 		if (subdev->start) {
1192 			ret = subdev->start(subdev);
1193 			if (ret)
1194 				goto unroll_registration;
1195 		}
1196 	}
1197 
1198 	return 0;
1199 
1200 unroll_registration:
1201 	list_for_each_entry_continue_reverse(subdev, &rproc->subdevs, node) {
1202 		if (subdev->stop)
1203 			subdev->stop(subdev, true);
1204 	}
1205 
1206 	return ret;
1207 }
1208 
1209 static void rproc_stop_subdevices(struct rproc *rproc, bool crashed)
1210 {
1211 	struct rproc_subdev *subdev;
1212 
1213 	list_for_each_entry_reverse(subdev, &rproc->subdevs, node) {
1214 		if (subdev->stop)
1215 			subdev->stop(subdev, crashed);
1216 	}
1217 }
1218 
1219 static void rproc_unprepare_subdevices(struct rproc *rproc)
1220 {
1221 	struct rproc_subdev *subdev;
1222 
1223 	list_for_each_entry_reverse(subdev, &rproc->subdevs, node) {
1224 		if (subdev->unprepare)
1225 			subdev->unprepare(subdev);
1226 	}
1227 }
1228 
1229 /**
1230  * rproc_alloc_registered_carveouts() - allocate all carveouts registered
1231  * in the list
1232  * @rproc: the remote processor handle
1233  *
1234  * This function parses registered carveout list, performs allocation
1235  * if alloc() ops registered and updates resource table information
1236  * if rsc_offset set.
1237  *
1238  * Return: 0 on success
1239  */
1240 static int rproc_alloc_registered_carveouts(struct rproc *rproc)
1241 {
1242 	struct rproc_mem_entry *entry, *tmp;
1243 	struct fw_rsc_carveout *rsc;
1244 	struct device *dev = &rproc->dev;
1245 	u64 pa;
1246 	int ret;
1247 
1248 	list_for_each_entry_safe(entry, tmp, &rproc->carveouts, node) {
1249 		if (entry->alloc) {
1250 			ret = entry->alloc(rproc, entry);
1251 			if (ret) {
1252 				dev_err(dev, "Unable to allocate carveout %s: %d\n",
1253 					entry->name, ret);
1254 				return -ENOMEM;
1255 			}
1256 		}
1257 
1258 		if (entry->rsc_offset != FW_RSC_ADDR_ANY) {
1259 			/* update resource table */
1260 			rsc = (void *)rproc->table_ptr + entry->rsc_offset;
1261 
1262 			/*
1263 			 * Some remote processors might need to know the pa
1264 			 * even though they are behind an IOMMU. E.g., OMAP4's
1265 			 * remote M3 processor needs this so it can control
1266 			 * on-chip hardware accelerators that are not behind
1267 			 * the IOMMU, and therefor must know the pa.
1268 			 *
1269 			 * Generally we don't want to expose physical addresses
1270 			 * if we don't have to (remote processors are generally
1271 			 * _not_ trusted), so we might want to do this only for
1272 			 * remote processor that _must_ have this (e.g. OMAP4's
1273 			 * dual M3 subsystem).
1274 			 *
1275 			 * Non-IOMMU processors might also want to have this info.
1276 			 * In this case, the device address and the physical address
1277 			 * are the same.
1278 			 */
1279 
1280 			/* Use va if defined else dma to generate pa */
1281 			if (entry->va)
1282 				pa = (u64)rproc_va_to_pa(entry->va);
1283 			else
1284 				pa = (u64)entry->dma;
1285 
1286 			if (((u64)pa) & HIGH_BITS_MASK)
1287 				dev_warn(dev,
1288 					 "Physical address cast in 32bit to fit resource table format\n");
1289 
1290 			rsc->pa = (u32)pa;
1291 			rsc->da = entry->da;
1292 			rsc->len = entry->len;
1293 		}
1294 	}
1295 
1296 	return 0;
1297 }
1298 
1299 
1300 /**
1301  * rproc_resource_cleanup() - clean up and free all acquired resources
1302  * @rproc: rproc handle
1303  *
1304  * This function will free all resources acquired for @rproc, and it
1305  * is called whenever @rproc either shuts down or fails to boot.
1306  */
1307 void rproc_resource_cleanup(struct rproc *rproc)
1308 {
1309 	struct rproc_mem_entry *entry, *tmp;
1310 	struct rproc_debug_trace *trace, *ttmp;
1311 	struct rproc_vdev *rvdev, *rvtmp;
1312 	struct device *dev = &rproc->dev;
1313 
1314 	/* clean up debugfs trace entries */
1315 	list_for_each_entry_safe(trace, ttmp, &rproc->traces, node) {
1316 		rproc_remove_trace_file(trace->tfile);
1317 		rproc->num_traces--;
1318 		list_del(&trace->node);
1319 		kfree(trace);
1320 	}
1321 
1322 	/* clean up iommu mapping entries */
1323 	list_for_each_entry_safe(entry, tmp, &rproc->mappings, node) {
1324 		size_t unmapped;
1325 
1326 		unmapped = iommu_unmap(rproc->domain, entry->da, entry->len);
1327 		if (unmapped != entry->len) {
1328 			/* nothing much to do besides complaining */
1329 			dev_err(dev, "failed to unmap %zx/%zu\n", entry->len,
1330 				unmapped);
1331 		}
1332 
1333 		list_del(&entry->node);
1334 		kfree(entry);
1335 	}
1336 
1337 	/* clean up carveout allocations */
1338 	list_for_each_entry_safe(entry, tmp, &rproc->carveouts, node) {
1339 		if (entry->release)
1340 			entry->release(rproc, entry);
1341 		list_del(&entry->node);
1342 		kfree(entry);
1343 	}
1344 
1345 	/* clean up remote vdev entries */
1346 	list_for_each_entry_safe(rvdev, rvtmp, &rproc->rvdevs, node)
1347 		kref_put(&rvdev->refcount, rproc_vdev_release);
1348 
1349 	rproc_coredump_cleanup(rproc);
1350 }
1351 EXPORT_SYMBOL(rproc_resource_cleanup);
1352 
1353 static int rproc_start(struct rproc *rproc, const struct firmware *fw)
1354 {
1355 	struct resource_table *loaded_table;
1356 	struct device *dev = &rproc->dev;
1357 	int ret;
1358 
1359 	/* load the ELF segments to memory */
1360 	ret = rproc_load_segments(rproc, fw);
1361 	if (ret) {
1362 		dev_err(dev, "Failed to load program segments: %d\n", ret);
1363 		return ret;
1364 	}
1365 
1366 	/*
1367 	 * The starting device has been given the rproc->cached_table as the
1368 	 * resource table. The address of the vring along with the other
1369 	 * allocated resources (carveouts etc) is stored in cached_table.
1370 	 * In order to pass this information to the remote device we must copy
1371 	 * this information to device memory. We also update the table_ptr so
1372 	 * that any subsequent changes will be applied to the loaded version.
1373 	 */
1374 	loaded_table = rproc_find_loaded_rsc_table(rproc, fw);
1375 	if (loaded_table) {
1376 		memcpy(loaded_table, rproc->cached_table, rproc->table_sz);
1377 		rproc->table_ptr = loaded_table;
1378 	}
1379 
1380 	ret = rproc_prepare_subdevices(rproc);
1381 	if (ret) {
1382 		dev_err(dev, "failed to prepare subdevices for %s: %d\n",
1383 			rproc->name, ret);
1384 		goto reset_table_ptr;
1385 	}
1386 
1387 	/* power up the remote processor */
1388 	ret = rproc->ops->start(rproc);
1389 	if (ret) {
1390 		dev_err(dev, "can't start rproc %s: %d\n", rproc->name, ret);
1391 		goto unprepare_subdevices;
1392 	}
1393 
1394 	/* Start any subdevices for the remote processor */
1395 	ret = rproc_start_subdevices(rproc);
1396 	if (ret) {
1397 		dev_err(dev, "failed to probe subdevices for %s: %d\n",
1398 			rproc->name, ret);
1399 		goto stop_rproc;
1400 	}
1401 
1402 	rproc->state = RPROC_RUNNING;
1403 
1404 	dev_info(dev, "remote processor %s is now up\n", rproc->name);
1405 
1406 	return 0;
1407 
1408 stop_rproc:
1409 	rproc->ops->stop(rproc);
1410 unprepare_subdevices:
1411 	rproc_unprepare_subdevices(rproc);
1412 reset_table_ptr:
1413 	rproc->table_ptr = rproc->cached_table;
1414 
1415 	return ret;
1416 }
1417 
1418 static int rproc_attach(struct rproc *rproc)
1419 {
1420 	struct device *dev = &rproc->dev;
1421 	int ret;
1422 
1423 	ret = rproc_prepare_subdevices(rproc);
1424 	if (ret) {
1425 		dev_err(dev, "failed to prepare subdevices for %s: %d\n",
1426 			rproc->name, ret);
1427 		goto out;
1428 	}
1429 
1430 	/* Attach to the remote processor */
1431 	ret = rproc_attach_device(rproc);
1432 	if (ret) {
1433 		dev_err(dev, "can't attach to rproc %s: %d\n",
1434 			rproc->name, ret);
1435 		goto unprepare_subdevices;
1436 	}
1437 
1438 	/* Start any subdevices for the remote processor */
1439 	ret = rproc_start_subdevices(rproc);
1440 	if (ret) {
1441 		dev_err(dev, "failed to probe subdevices for %s: %d\n",
1442 			rproc->name, ret);
1443 		goto stop_rproc;
1444 	}
1445 
1446 	rproc->state = RPROC_RUNNING;
1447 
1448 	dev_info(dev, "remote processor %s is now attached\n", rproc->name);
1449 
1450 	return 0;
1451 
1452 stop_rproc:
1453 	rproc->ops->stop(rproc);
1454 unprepare_subdevices:
1455 	rproc_unprepare_subdevices(rproc);
1456 out:
1457 	return ret;
1458 }
1459 
1460 /*
1461  * take a firmware and boot a remote processor with it.
1462  */
1463 static int rproc_fw_boot(struct rproc *rproc, const struct firmware *fw)
1464 {
1465 	struct device *dev = &rproc->dev;
1466 	const char *name = rproc->firmware;
1467 	int ret;
1468 
1469 	ret = rproc_fw_sanity_check(rproc, fw);
1470 	if (ret)
1471 		return ret;
1472 
1473 	dev_info(dev, "Booting fw image %s, size %zd\n", name, fw->size);
1474 
1475 	/*
1476 	 * if enabling an IOMMU isn't relevant for this rproc, this is
1477 	 * just a nop
1478 	 */
1479 	ret = rproc_enable_iommu(rproc);
1480 	if (ret) {
1481 		dev_err(dev, "can't enable iommu: %d\n", ret);
1482 		return ret;
1483 	}
1484 
1485 	/* Prepare rproc for firmware loading if needed */
1486 	ret = rproc_prepare_device(rproc);
1487 	if (ret) {
1488 		dev_err(dev, "can't prepare rproc %s: %d\n", rproc->name, ret);
1489 		goto disable_iommu;
1490 	}
1491 
1492 	rproc->bootaddr = rproc_get_boot_addr(rproc, fw);
1493 
1494 	/* Load resource table, core dump segment list etc from the firmware */
1495 	ret = rproc_parse_fw(rproc, fw);
1496 	if (ret)
1497 		goto unprepare_rproc;
1498 
1499 	/* reset max_notifyid */
1500 	rproc->max_notifyid = -1;
1501 
1502 	/* reset handled vdev */
1503 	rproc->nb_vdev = 0;
1504 
1505 	/* handle fw resources which are required to boot rproc */
1506 	ret = rproc_handle_resources(rproc, rproc_loading_handlers);
1507 	if (ret) {
1508 		dev_err(dev, "Failed to process resources: %d\n", ret);
1509 		goto clean_up_resources;
1510 	}
1511 
1512 	/* Allocate carveout resources associated to rproc */
1513 	ret = rproc_alloc_registered_carveouts(rproc);
1514 	if (ret) {
1515 		dev_err(dev, "Failed to allocate associated carveouts: %d\n",
1516 			ret);
1517 		goto clean_up_resources;
1518 	}
1519 
1520 	ret = rproc_start(rproc, fw);
1521 	if (ret)
1522 		goto clean_up_resources;
1523 
1524 	return 0;
1525 
1526 clean_up_resources:
1527 	rproc_resource_cleanup(rproc);
1528 	kfree(rproc->cached_table);
1529 	rproc->cached_table = NULL;
1530 	rproc->table_ptr = NULL;
1531 unprepare_rproc:
1532 	/* release HW resources if needed */
1533 	rproc_unprepare_device(rproc);
1534 disable_iommu:
1535 	rproc_disable_iommu(rproc);
1536 	return ret;
1537 }
1538 
1539 /*
1540  * Attach to remote processor - similar to rproc_fw_boot() but without
1541  * the steps that deal with the firmware image.
1542  */
1543 static int rproc_actuate(struct rproc *rproc)
1544 {
1545 	struct device *dev = &rproc->dev;
1546 	int ret;
1547 
1548 	/*
1549 	 * if enabling an IOMMU isn't relevant for this rproc, this is
1550 	 * just a nop
1551 	 */
1552 	ret = rproc_enable_iommu(rproc);
1553 	if (ret) {
1554 		dev_err(dev, "can't enable iommu: %d\n", ret);
1555 		return ret;
1556 	}
1557 
1558 	/* reset max_notifyid */
1559 	rproc->max_notifyid = -1;
1560 
1561 	/* reset handled vdev */
1562 	rproc->nb_vdev = 0;
1563 
1564 	/*
1565 	 * Handle firmware resources required to attach to a remote processor.
1566 	 * Because we are attaching rather than booting the remote processor,
1567 	 * we expect the platform driver to properly set rproc->table_ptr.
1568 	 */
1569 	ret = rproc_handle_resources(rproc, rproc_loading_handlers);
1570 	if (ret) {
1571 		dev_err(dev, "Failed to process resources: %d\n", ret);
1572 		goto disable_iommu;
1573 	}
1574 
1575 	/* Allocate carveout resources associated to rproc */
1576 	ret = rproc_alloc_registered_carveouts(rproc);
1577 	if (ret) {
1578 		dev_err(dev, "Failed to allocate associated carveouts: %d\n",
1579 			ret);
1580 		goto clean_up_resources;
1581 	}
1582 
1583 	ret = rproc_attach(rproc);
1584 	if (ret)
1585 		goto clean_up_resources;
1586 
1587 	return 0;
1588 
1589 clean_up_resources:
1590 	rproc_resource_cleanup(rproc);
1591 disable_iommu:
1592 	rproc_disable_iommu(rproc);
1593 	return ret;
1594 }
1595 
1596 /*
1597  * take a firmware and boot it up.
1598  *
1599  * Note: this function is called asynchronously upon registration of the
1600  * remote processor (so we must wait until it completes before we try
1601  * to unregister the device. one other option is just to use kref here,
1602  * that might be cleaner).
1603  */
1604 static void rproc_auto_boot_callback(const struct firmware *fw, void *context)
1605 {
1606 	struct rproc *rproc = context;
1607 
1608 	rproc_boot(rproc);
1609 
1610 	release_firmware(fw);
1611 }
1612 
1613 static int rproc_trigger_auto_boot(struct rproc *rproc)
1614 {
1615 	int ret;
1616 
1617 	/*
1618 	 * Since the remote processor is in a detached state, it has already
1619 	 * been booted by another entity.  As such there is no point in waiting
1620 	 * for a firmware image to be loaded, we can simply initiate the process
1621 	 * of attaching to it immediately.
1622 	 */
1623 	if (rproc->state == RPROC_DETACHED)
1624 		return rproc_boot(rproc);
1625 
1626 	/*
1627 	 * We're initiating an asynchronous firmware loading, so we can
1628 	 * be built-in kernel code, without hanging the boot process.
1629 	 */
1630 	ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_HOTPLUG,
1631 				      rproc->firmware, &rproc->dev, GFP_KERNEL,
1632 				      rproc, rproc_auto_boot_callback);
1633 	if (ret < 0)
1634 		dev_err(&rproc->dev, "request_firmware_nowait err: %d\n", ret);
1635 
1636 	return ret;
1637 }
1638 
1639 static int rproc_stop(struct rproc *rproc, bool crashed)
1640 {
1641 	struct device *dev = &rproc->dev;
1642 	int ret;
1643 
1644 	/* Stop any subdevices for the remote processor */
1645 	rproc_stop_subdevices(rproc, crashed);
1646 
1647 	/* the installed resource table is no longer accessible */
1648 	rproc->table_ptr = rproc->cached_table;
1649 
1650 	/* power off the remote processor */
1651 	ret = rproc->ops->stop(rproc);
1652 	if (ret) {
1653 		dev_err(dev, "can't stop rproc: %d\n", ret);
1654 		return ret;
1655 	}
1656 
1657 	rproc_unprepare_subdevices(rproc);
1658 
1659 	rproc->state = RPROC_OFFLINE;
1660 
1661 	/*
1662 	 * The remote processor has been stopped and is now offline, which means
1663 	 * that the next time it is brought back online the remoteproc core will
1664 	 * be responsible to load its firmware.  As such it is no longer
1665 	 * autonomous.
1666 	 */
1667 	rproc->autonomous = false;
1668 
1669 	dev_info(dev, "stopped remote processor %s\n", rproc->name);
1670 
1671 	return 0;
1672 }
1673 
1674 
1675 /**
1676  * rproc_trigger_recovery() - recover a remoteproc
1677  * @rproc: the remote processor
1678  *
1679  * The recovery is done by resetting all the virtio devices, that way all the
1680  * rpmsg drivers will be reseted along with the remote processor making the
1681  * remoteproc functional again.
1682  *
1683  * This function can sleep, so it cannot be called from atomic context.
1684  */
1685 int rproc_trigger_recovery(struct rproc *rproc)
1686 {
1687 	const struct firmware *firmware_p;
1688 	struct device *dev = &rproc->dev;
1689 	int ret;
1690 
1691 	ret = mutex_lock_interruptible(&rproc->lock);
1692 	if (ret)
1693 		return ret;
1694 
1695 	/* State could have changed before we got the mutex */
1696 	if (rproc->state != RPROC_CRASHED)
1697 		goto unlock_mutex;
1698 
1699 	dev_err(dev, "recovering %s\n", rproc->name);
1700 
1701 	ret = rproc_stop(rproc, true);
1702 	if (ret)
1703 		goto unlock_mutex;
1704 
1705 	/* generate coredump */
1706 	rproc_coredump(rproc);
1707 
1708 	/* load firmware */
1709 	ret = request_firmware(&firmware_p, rproc->firmware, dev);
1710 	if (ret < 0) {
1711 		dev_err(dev, "request_firmware failed: %d\n", ret);
1712 		goto unlock_mutex;
1713 	}
1714 
1715 	/* boot the remote processor up again */
1716 	ret = rproc_start(rproc, firmware_p);
1717 
1718 	release_firmware(firmware_p);
1719 
1720 unlock_mutex:
1721 	mutex_unlock(&rproc->lock);
1722 	return ret;
1723 }
1724 
1725 /**
1726  * rproc_crash_handler_work() - handle a crash
1727  * @work: work treating the crash
1728  *
1729  * This function needs to handle everything related to a crash, like cpu
1730  * registers and stack dump, information to help to debug the fatal error, etc.
1731  */
1732 static void rproc_crash_handler_work(struct work_struct *work)
1733 {
1734 	struct rproc *rproc = container_of(work, struct rproc, crash_handler);
1735 	struct device *dev = &rproc->dev;
1736 
1737 	dev_dbg(dev, "enter %s\n", __func__);
1738 
1739 	mutex_lock(&rproc->lock);
1740 
1741 	if (rproc->state == RPROC_CRASHED || rproc->state == RPROC_OFFLINE) {
1742 		/* handle only the first crash detected */
1743 		mutex_unlock(&rproc->lock);
1744 		return;
1745 	}
1746 
1747 	rproc->state = RPROC_CRASHED;
1748 	dev_err(dev, "handling crash #%u in %s\n", ++rproc->crash_cnt,
1749 		rproc->name);
1750 
1751 	mutex_unlock(&rproc->lock);
1752 
1753 	if (!rproc->recovery_disabled)
1754 		rproc_trigger_recovery(rproc);
1755 
1756 	pm_relax(rproc->dev.parent);
1757 }
1758 
1759 /**
1760  * rproc_boot() - boot a remote processor
1761  * @rproc: handle of a remote processor
1762  *
1763  * Boot a remote processor (i.e. load its firmware, power it on, ...).
1764  *
1765  * If the remote processor is already powered on, this function immediately
1766  * returns (successfully).
1767  *
1768  * Returns 0 on success, and an appropriate error value otherwise.
1769  */
1770 int rproc_boot(struct rproc *rproc)
1771 {
1772 	const struct firmware *firmware_p;
1773 	struct device *dev;
1774 	int ret;
1775 
1776 	if (!rproc) {
1777 		pr_err("invalid rproc handle\n");
1778 		return -EINVAL;
1779 	}
1780 
1781 	dev = &rproc->dev;
1782 
1783 	ret = mutex_lock_interruptible(&rproc->lock);
1784 	if (ret) {
1785 		dev_err(dev, "can't lock rproc %s: %d\n", rproc->name, ret);
1786 		return ret;
1787 	}
1788 
1789 	if (rproc->state == RPROC_DELETED) {
1790 		ret = -ENODEV;
1791 		dev_err(dev, "can't boot deleted rproc %s\n", rproc->name);
1792 		goto unlock_mutex;
1793 	}
1794 
1795 	/* skip the boot or attach process if rproc is already powered up */
1796 	if (atomic_inc_return(&rproc->power) > 1) {
1797 		ret = 0;
1798 		goto unlock_mutex;
1799 	}
1800 
1801 	if (rproc->state == RPROC_DETACHED) {
1802 		dev_info(dev, "attaching to %s\n", rproc->name);
1803 
1804 		ret = rproc_actuate(rproc);
1805 	} else {
1806 		dev_info(dev, "powering up %s\n", rproc->name);
1807 
1808 		/* load firmware */
1809 		ret = request_firmware(&firmware_p, rproc->firmware, dev);
1810 		if (ret < 0) {
1811 			dev_err(dev, "request_firmware failed: %d\n", ret);
1812 			goto downref_rproc;
1813 		}
1814 
1815 		ret = rproc_fw_boot(rproc, firmware_p);
1816 
1817 		release_firmware(firmware_p);
1818 	}
1819 
1820 downref_rproc:
1821 	if (ret)
1822 		atomic_dec(&rproc->power);
1823 unlock_mutex:
1824 	mutex_unlock(&rproc->lock);
1825 	return ret;
1826 }
1827 EXPORT_SYMBOL(rproc_boot);
1828 
1829 /**
1830  * rproc_shutdown() - power off the remote processor
1831  * @rproc: the remote processor
1832  *
1833  * Power off a remote processor (previously booted with rproc_boot()).
1834  *
1835  * In case @rproc is still being used by an additional user(s), then
1836  * this function will just decrement the power refcount and exit,
1837  * without really powering off the device.
1838  *
1839  * Every call to rproc_boot() must (eventually) be accompanied by a call
1840  * to rproc_shutdown(). Calling rproc_shutdown() redundantly is a bug.
1841  *
1842  * Notes:
1843  * - we're not decrementing the rproc's refcount, only the power refcount.
1844  *   which means that the @rproc handle stays valid even after rproc_shutdown()
1845  *   returns, and users can still use it with a subsequent rproc_boot(), if
1846  *   needed.
1847  */
1848 void rproc_shutdown(struct rproc *rproc)
1849 {
1850 	struct device *dev = &rproc->dev;
1851 	int ret;
1852 
1853 	ret = mutex_lock_interruptible(&rproc->lock);
1854 	if (ret) {
1855 		dev_err(dev, "can't lock rproc %s: %d\n", rproc->name, ret);
1856 		return;
1857 	}
1858 
1859 	/* if the remote proc is still needed, bail out */
1860 	if (!atomic_dec_and_test(&rproc->power))
1861 		goto out;
1862 
1863 	ret = rproc_stop(rproc, false);
1864 	if (ret) {
1865 		atomic_inc(&rproc->power);
1866 		goto out;
1867 	}
1868 
1869 	/* clean up all acquired resources */
1870 	rproc_resource_cleanup(rproc);
1871 
1872 	/* release HW resources if needed */
1873 	rproc_unprepare_device(rproc);
1874 
1875 	rproc_disable_iommu(rproc);
1876 
1877 	/* Free the copy of the resource table */
1878 	kfree(rproc->cached_table);
1879 	rproc->cached_table = NULL;
1880 	rproc->table_ptr = NULL;
1881 out:
1882 	mutex_unlock(&rproc->lock);
1883 }
1884 EXPORT_SYMBOL(rproc_shutdown);
1885 
1886 /**
1887  * rproc_get_by_phandle() - find a remote processor by phandle
1888  * @phandle: phandle to the rproc
1889  *
1890  * Finds an rproc handle using the remote processor's phandle, and then
1891  * return a handle to the rproc.
1892  *
1893  * This function increments the remote processor's refcount, so always
1894  * use rproc_put() to decrement it back once rproc isn't needed anymore.
1895  *
1896  * Returns the rproc handle on success, and NULL on failure.
1897  */
1898 #ifdef CONFIG_OF
1899 struct rproc *rproc_get_by_phandle(phandle phandle)
1900 {
1901 	struct rproc *rproc = NULL, *r;
1902 	struct device_node *np;
1903 
1904 	np = of_find_node_by_phandle(phandle);
1905 	if (!np)
1906 		return NULL;
1907 
1908 	rcu_read_lock();
1909 	list_for_each_entry_rcu(r, &rproc_list, node) {
1910 		if (r->dev.parent && r->dev.parent->of_node == np) {
1911 			/* prevent underlying implementation from being removed */
1912 			if (!try_module_get(r->dev.parent->driver->owner)) {
1913 				dev_err(&r->dev, "can't get owner\n");
1914 				break;
1915 			}
1916 
1917 			rproc = r;
1918 			get_device(&rproc->dev);
1919 			break;
1920 		}
1921 	}
1922 	rcu_read_unlock();
1923 
1924 	of_node_put(np);
1925 
1926 	return rproc;
1927 }
1928 #else
1929 struct rproc *rproc_get_by_phandle(phandle phandle)
1930 {
1931 	return NULL;
1932 }
1933 #endif
1934 EXPORT_SYMBOL(rproc_get_by_phandle);
1935 
1936 static int rproc_validate(struct rproc *rproc)
1937 {
1938 	switch (rproc->state) {
1939 	case RPROC_OFFLINE:
1940 		/*
1941 		 * An offline processor without a start()
1942 		 * function makes no sense.
1943 		 */
1944 		if (!rproc->ops->start)
1945 			return -EINVAL;
1946 		break;
1947 	case RPROC_DETACHED:
1948 		/*
1949 		 * A remote processor in a detached state without an
1950 		 * attach() function makes not sense.
1951 		 */
1952 		if (!rproc->ops->attach)
1953 			return -EINVAL;
1954 		/*
1955 		 * When attaching to a remote processor the device memory
1956 		 * is already available and as such there is no need to have a
1957 		 * cached table.
1958 		 */
1959 		if (rproc->cached_table)
1960 			return -EINVAL;
1961 		break;
1962 	default:
1963 		/*
1964 		 * When adding a remote processor, the state of the device
1965 		 * can be offline or detached, nothing else.
1966 		 */
1967 		return -EINVAL;
1968 	}
1969 
1970 	return 0;
1971 }
1972 
1973 /**
1974  * rproc_add() - register a remote processor
1975  * @rproc: the remote processor handle to register
1976  *
1977  * Registers @rproc with the remoteproc framework, after it has been
1978  * allocated with rproc_alloc().
1979  *
1980  * This is called by the platform-specific rproc implementation, whenever
1981  * a new remote processor device is probed.
1982  *
1983  * Returns 0 on success and an appropriate error code otherwise.
1984  *
1985  * Note: this function initiates an asynchronous firmware loading
1986  * context, which will look for virtio devices supported by the rproc's
1987  * firmware.
1988  *
1989  * If found, those virtio devices will be created and added, so as a result
1990  * of registering this remote processor, additional virtio drivers might be
1991  * probed.
1992  */
1993 int rproc_add(struct rproc *rproc)
1994 {
1995 	struct device *dev = &rproc->dev;
1996 	int ret;
1997 
1998 	ret = device_add(dev);
1999 	if (ret < 0)
2000 		return ret;
2001 
2002 	ret = rproc_validate(rproc);
2003 	if (ret < 0)
2004 		return ret;
2005 
2006 	dev_info(dev, "%s is available\n", rproc->name);
2007 
2008 	/* create debugfs entries */
2009 	rproc_create_debug_dir(rproc);
2010 
2011 	/* add char device for this remoteproc */
2012 	ret = rproc_char_device_add(rproc);
2013 	if (ret < 0)
2014 		return ret;
2015 
2016 	/*
2017 	 * Remind ourselves the remote processor has been attached to rather
2018 	 * than booted by the remoteproc core.  This is important because the
2019 	 * RPROC_DETACHED state will be lost as soon as the remote processor
2020 	 * has been attached to.  Used in firmware_show() and reset in
2021 	 * rproc_stop().
2022 	 */
2023 	if (rproc->state == RPROC_DETACHED)
2024 		rproc->autonomous = true;
2025 
2026 	/* if rproc is marked always-on, request it to boot */
2027 	if (rproc->auto_boot) {
2028 		ret = rproc_trigger_auto_boot(rproc);
2029 		if (ret < 0)
2030 			return ret;
2031 	}
2032 
2033 	/* expose to rproc_get_by_phandle users */
2034 	mutex_lock(&rproc_list_mutex);
2035 	list_add_rcu(&rproc->node, &rproc_list);
2036 	mutex_unlock(&rproc_list_mutex);
2037 
2038 	return 0;
2039 }
2040 EXPORT_SYMBOL(rproc_add);
2041 
2042 static void devm_rproc_remove(void *rproc)
2043 {
2044 	rproc_del(rproc);
2045 }
2046 
2047 /**
2048  * devm_rproc_add() - resource managed rproc_add()
2049  * @dev: the underlying device
2050  * @rproc: the remote processor handle to register
2051  *
2052  * This function performs like rproc_add() but the registered rproc device will
2053  * automatically be removed on driver detach.
2054  *
2055  * Returns: 0 on success, negative errno on failure
2056  */
2057 int devm_rproc_add(struct device *dev, struct rproc *rproc)
2058 {
2059 	int err;
2060 
2061 	err = rproc_add(rproc);
2062 	if (err)
2063 		return err;
2064 
2065 	return devm_add_action_or_reset(dev, devm_rproc_remove, rproc);
2066 }
2067 EXPORT_SYMBOL(devm_rproc_add);
2068 
2069 /**
2070  * rproc_type_release() - release a remote processor instance
2071  * @dev: the rproc's device
2072  *
2073  * This function should _never_ be called directly.
2074  *
2075  * It will be called by the driver core when no one holds a valid pointer
2076  * to @dev anymore.
2077  */
2078 static void rproc_type_release(struct device *dev)
2079 {
2080 	struct rproc *rproc = container_of(dev, struct rproc, dev);
2081 
2082 	dev_info(&rproc->dev, "releasing %s\n", rproc->name);
2083 
2084 	idr_destroy(&rproc->notifyids);
2085 
2086 	if (rproc->index >= 0)
2087 		ida_simple_remove(&rproc_dev_index, rproc->index);
2088 
2089 	kfree_const(rproc->firmware);
2090 	kfree_const(rproc->name);
2091 	kfree(rproc->ops);
2092 	kfree(rproc);
2093 }
2094 
2095 static const struct device_type rproc_type = {
2096 	.name		= "remoteproc",
2097 	.release	= rproc_type_release,
2098 };
2099 
2100 static int rproc_alloc_firmware(struct rproc *rproc,
2101 				const char *name, const char *firmware)
2102 {
2103 	const char *p;
2104 
2105 	/*
2106 	 * Allocate a firmware name if the caller gave us one to work
2107 	 * with.  Otherwise construct a new one using a default pattern.
2108 	 */
2109 	if (firmware)
2110 		p = kstrdup_const(firmware, GFP_KERNEL);
2111 	else
2112 		p = kasprintf(GFP_KERNEL, "rproc-%s-fw", name);
2113 
2114 	if (!p)
2115 		return -ENOMEM;
2116 
2117 	rproc->firmware = p;
2118 
2119 	return 0;
2120 }
2121 
2122 static int rproc_alloc_ops(struct rproc *rproc, const struct rproc_ops *ops)
2123 {
2124 	rproc->ops = kmemdup(ops, sizeof(*ops), GFP_KERNEL);
2125 	if (!rproc->ops)
2126 		return -ENOMEM;
2127 
2128 	if (rproc->ops->load)
2129 		return 0;
2130 
2131 	/* Default to ELF loader if no load function is specified */
2132 	rproc->ops->load = rproc_elf_load_segments;
2133 	rproc->ops->parse_fw = rproc_elf_load_rsc_table;
2134 	rproc->ops->find_loaded_rsc_table = rproc_elf_find_loaded_rsc_table;
2135 	rproc->ops->sanity_check = rproc_elf_sanity_check;
2136 	rproc->ops->get_boot_addr = rproc_elf_get_boot_addr;
2137 
2138 	return 0;
2139 }
2140 
2141 /**
2142  * rproc_alloc() - allocate a remote processor handle
2143  * @dev: the underlying device
2144  * @name: name of this remote processor
2145  * @ops: platform-specific handlers (mainly start/stop)
2146  * @firmware: name of firmware file to load, can be NULL
2147  * @len: length of private data needed by the rproc driver (in bytes)
2148  *
2149  * Allocates a new remote processor handle, but does not register
2150  * it yet. if @firmware is NULL, a default name is used.
2151  *
2152  * This function should be used by rproc implementations during initialization
2153  * of the remote processor.
2154  *
2155  * After creating an rproc handle using this function, and when ready,
2156  * implementations should then call rproc_add() to complete
2157  * the registration of the remote processor.
2158  *
2159  * On success the new rproc is returned, and on failure, NULL.
2160  *
2161  * Note: _never_ directly deallocate @rproc, even if it was not registered
2162  * yet. Instead, when you need to unroll rproc_alloc(), use rproc_free().
2163  */
2164 struct rproc *rproc_alloc(struct device *dev, const char *name,
2165 			  const struct rproc_ops *ops,
2166 			  const char *firmware, int len)
2167 {
2168 	struct rproc *rproc;
2169 
2170 	if (!dev || !name || !ops)
2171 		return NULL;
2172 
2173 	rproc = kzalloc(sizeof(struct rproc) + len, GFP_KERNEL);
2174 	if (!rproc)
2175 		return NULL;
2176 
2177 	rproc->priv = &rproc[1];
2178 	rproc->auto_boot = true;
2179 	rproc->elf_class = ELFCLASSNONE;
2180 	rproc->elf_machine = EM_NONE;
2181 
2182 	device_initialize(&rproc->dev);
2183 	rproc->dev.parent = dev;
2184 	rproc->dev.type = &rproc_type;
2185 	rproc->dev.class = &rproc_class;
2186 	rproc->dev.driver_data = rproc;
2187 	idr_init(&rproc->notifyids);
2188 
2189 	rproc->name = kstrdup_const(name, GFP_KERNEL);
2190 	if (!rproc->name)
2191 		goto put_device;
2192 
2193 	if (rproc_alloc_firmware(rproc, name, firmware))
2194 		goto put_device;
2195 
2196 	if (rproc_alloc_ops(rproc, ops))
2197 		goto put_device;
2198 
2199 	/* Assign a unique device index and name */
2200 	rproc->index = ida_simple_get(&rproc_dev_index, 0, 0, GFP_KERNEL);
2201 	if (rproc->index < 0) {
2202 		dev_err(dev, "ida_simple_get failed: %d\n", rproc->index);
2203 		goto put_device;
2204 	}
2205 
2206 	dev_set_name(&rproc->dev, "remoteproc%d", rproc->index);
2207 
2208 	atomic_set(&rproc->power, 0);
2209 
2210 	mutex_init(&rproc->lock);
2211 
2212 	INIT_LIST_HEAD(&rproc->carveouts);
2213 	INIT_LIST_HEAD(&rproc->mappings);
2214 	INIT_LIST_HEAD(&rproc->traces);
2215 	INIT_LIST_HEAD(&rproc->rvdevs);
2216 	INIT_LIST_HEAD(&rproc->subdevs);
2217 	INIT_LIST_HEAD(&rproc->dump_segments);
2218 
2219 	INIT_WORK(&rproc->crash_handler, rproc_crash_handler_work);
2220 
2221 	rproc->state = RPROC_OFFLINE;
2222 
2223 	return rproc;
2224 
2225 put_device:
2226 	put_device(&rproc->dev);
2227 	return NULL;
2228 }
2229 EXPORT_SYMBOL(rproc_alloc);
2230 
2231 /**
2232  * rproc_free() - unroll rproc_alloc()
2233  * @rproc: the remote processor handle
2234  *
2235  * This function decrements the rproc dev refcount.
2236  *
2237  * If no one holds any reference to rproc anymore, then its refcount would
2238  * now drop to zero, and it would be freed.
2239  */
2240 void rproc_free(struct rproc *rproc)
2241 {
2242 	put_device(&rproc->dev);
2243 }
2244 EXPORT_SYMBOL(rproc_free);
2245 
2246 /**
2247  * rproc_put() - release rproc reference
2248  * @rproc: the remote processor handle
2249  *
2250  * This function decrements the rproc dev refcount.
2251  *
2252  * If no one holds any reference to rproc anymore, then its refcount would
2253  * now drop to zero, and it would be freed.
2254  */
2255 void rproc_put(struct rproc *rproc)
2256 {
2257 	module_put(rproc->dev.parent->driver->owner);
2258 	put_device(&rproc->dev);
2259 }
2260 EXPORT_SYMBOL(rproc_put);
2261 
2262 /**
2263  * rproc_del() - unregister a remote processor
2264  * @rproc: rproc handle to unregister
2265  *
2266  * This function should be called when the platform specific rproc
2267  * implementation decides to remove the rproc device. it should
2268  * _only_ be called if a previous invocation of rproc_add()
2269  * has completed successfully.
2270  *
2271  * After rproc_del() returns, @rproc isn't freed yet, because
2272  * of the outstanding reference created by rproc_alloc. To decrement that
2273  * one last refcount, one still needs to call rproc_free().
2274  *
2275  * Returns 0 on success and -EINVAL if @rproc isn't valid.
2276  */
2277 int rproc_del(struct rproc *rproc)
2278 {
2279 	if (!rproc)
2280 		return -EINVAL;
2281 
2282 	/* if rproc is marked always-on, rproc_add() booted it */
2283 	/* TODO: make sure this works with rproc->power > 1 */
2284 	if (rproc->auto_boot)
2285 		rproc_shutdown(rproc);
2286 
2287 	mutex_lock(&rproc->lock);
2288 	rproc->state = RPROC_DELETED;
2289 	mutex_unlock(&rproc->lock);
2290 
2291 	rproc_delete_debug_dir(rproc);
2292 	rproc_char_device_remove(rproc);
2293 
2294 	/* the rproc is downref'ed as soon as it's removed from the klist */
2295 	mutex_lock(&rproc_list_mutex);
2296 	list_del_rcu(&rproc->node);
2297 	mutex_unlock(&rproc_list_mutex);
2298 
2299 	/* Ensure that no readers of rproc_list are still active */
2300 	synchronize_rcu();
2301 
2302 	device_del(&rproc->dev);
2303 
2304 	return 0;
2305 }
2306 EXPORT_SYMBOL(rproc_del);
2307 
2308 static void devm_rproc_free(struct device *dev, void *res)
2309 {
2310 	rproc_free(*(struct rproc **)res);
2311 }
2312 
2313 /**
2314  * devm_rproc_alloc() - resource managed rproc_alloc()
2315  * @dev: the underlying device
2316  * @name: name of this remote processor
2317  * @ops: platform-specific handlers (mainly start/stop)
2318  * @firmware: name of firmware file to load, can be NULL
2319  * @len: length of private data needed by the rproc driver (in bytes)
2320  *
2321  * This function performs like rproc_alloc() but the acquired rproc device will
2322  * automatically be released on driver detach.
2323  *
2324  * Returns: new rproc instance, or NULL on failure
2325  */
2326 struct rproc *devm_rproc_alloc(struct device *dev, const char *name,
2327 			       const struct rproc_ops *ops,
2328 			       const char *firmware, int len)
2329 {
2330 	struct rproc **ptr, *rproc;
2331 
2332 	ptr = devres_alloc(devm_rproc_free, sizeof(*ptr), GFP_KERNEL);
2333 	if (!ptr)
2334 		return NULL;
2335 
2336 	rproc = rproc_alloc(dev, name, ops, firmware, len);
2337 	if (rproc) {
2338 		*ptr = rproc;
2339 		devres_add(dev, ptr);
2340 	} else {
2341 		devres_free(ptr);
2342 	}
2343 
2344 	return rproc;
2345 }
2346 EXPORT_SYMBOL(devm_rproc_alloc);
2347 
2348 /**
2349  * rproc_add_subdev() - add a subdevice to a remoteproc
2350  * @rproc: rproc handle to add the subdevice to
2351  * @subdev: subdev handle to register
2352  *
2353  * Caller is responsible for populating optional subdevice function pointers.
2354  */
2355 void rproc_add_subdev(struct rproc *rproc, struct rproc_subdev *subdev)
2356 {
2357 	list_add_tail(&subdev->node, &rproc->subdevs);
2358 }
2359 EXPORT_SYMBOL(rproc_add_subdev);
2360 
2361 /**
2362  * rproc_remove_subdev() - remove a subdevice from a remoteproc
2363  * @rproc: rproc handle to remove the subdevice from
2364  * @subdev: subdev handle, previously registered with rproc_add_subdev()
2365  */
2366 void rproc_remove_subdev(struct rproc *rproc, struct rproc_subdev *subdev)
2367 {
2368 	list_del(&subdev->node);
2369 }
2370 EXPORT_SYMBOL(rproc_remove_subdev);
2371 
2372 /**
2373  * rproc_get_by_child() - acquire rproc handle of @dev's ancestor
2374  * @dev:	child device to find ancestor of
2375  *
2376  * Returns the ancestor rproc instance, or NULL if not found.
2377  */
2378 struct rproc *rproc_get_by_child(struct device *dev)
2379 {
2380 	for (dev = dev->parent; dev; dev = dev->parent) {
2381 		if (dev->type == &rproc_type)
2382 			return dev->driver_data;
2383 	}
2384 
2385 	return NULL;
2386 }
2387 EXPORT_SYMBOL(rproc_get_by_child);
2388 
2389 /**
2390  * rproc_report_crash() - rproc crash reporter function
2391  * @rproc: remote processor
2392  * @type: crash type
2393  *
2394  * This function must be called every time a crash is detected by the low-level
2395  * drivers implementing a specific remoteproc. This should not be called from a
2396  * non-remoteproc driver.
2397  *
2398  * This function can be called from atomic/interrupt context.
2399  */
2400 void rproc_report_crash(struct rproc *rproc, enum rproc_crash_type type)
2401 {
2402 	if (!rproc) {
2403 		pr_err("NULL rproc pointer\n");
2404 		return;
2405 	}
2406 
2407 	/* Prevent suspend while the remoteproc is being recovered */
2408 	pm_stay_awake(rproc->dev.parent);
2409 
2410 	dev_err(&rproc->dev, "crash detected in %s: type %s\n",
2411 		rproc->name, rproc_crash_to_string(type));
2412 
2413 	/* create a new task to handle the error */
2414 	schedule_work(&rproc->crash_handler);
2415 }
2416 EXPORT_SYMBOL(rproc_report_crash);
2417 
2418 static int rproc_panic_handler(struct notifier_block *nb, unsigned long event,
2419 			       void *ptr)
2420 {
2421 	unsigned int longest = 0;
2422 	struct rproc *rproc;
2423 	unsigned int d;
2424 
2425 	rcu_read_lock();
2426 	list_for_each_entry_rcu(rproc, &rproc_list, node) {
2427 		if (!rproc->ops->panic || rproc->state != RPROC_RUNNING)
2428 			continue;
2429 
2430 		d = rproc->ops->panic(rproc);
2431 		longest = max(longest, d);
2432 	}
2433 	rcu_read_unlock();
2434 
2435 	/*
2436 	 * Delay for the longest requested duration before returning. This can
2437 	 * be used by the remoteproc drivers to give the remote processor time
2438 	 * to perform any requested operations (such as flush caches), when
2439 	 * it's not possible to signal the Linux side due to the panic.
2440 	 */
2441 	mdelay(longest);
2442 
2443 	return NOTIFY_DONE;
2444 }
2445 
2446 static void __init rproc_init_panic(void)
2447 {
2448 	rproc_panic_nb.notifier_call = rproc_panic_handler;
2449 	atomic_notifier_chain_register(&panic_notifier_list, &rproc_panic_nb);
2450 }
2451 
2452 static void __exit rproc_exit_panic(void)
2453 {
2454 	atomic_notifier_chain_unregister(&panic_notifier_list, &rproc_panic_nb);
2455 }
2456 
2457 static int __init remoteproc_init(void)
2458 {
2459 	rproc_init_sysfs();
2460 	rproc_init_debugfs();
2461 	rproc_init_cdev();
2462 	rproc_init_panic();
2463 
2464 	return 0;
2465 }
2466 subsys_initcall(remoteproc_init);
2467 
2468 static void __exit remoteproc_exit(void)
2469 {
2470 	ida_destroy(&rproc_dev_index);
2471 
2472 	rproc_exit_panic();
2473 	rproc_exit_debugfs();
2474 	rproc_exit_sysfs();
2475 }
2476 module_exit(remoteproc_exit);
2477 
2478 MODULE_LICENSE("GPL v2");
2479 MODULE_DESCRIPTION("Generic Remote Processor Framework");
2480