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