Merge tag 'leds_for_4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/j...
[linux-block.git] / drivers / remoteproc / remoteproc_core.c
1 /*
2  * Remote Processor Framework
3  *
4  * Copyright (C) 2011 Texas Instruments, Inc.
5  * Copyright (C) 2011 Google, Inc.
6  *
7  * Ohad Ben-Cohen <ohad@wizery.com>
8  * Brian Swetland <swetland@google.com>
9  * Mark Grosen <mgrosen@ti.com>
10  * Fernando Guzman Lugo <fernando.lugo@ti.com>
11  * Suman Anna <s-anna@ti.com>
12  * Robert Tivy <rtivy@ti.com>
13  * Armando Uribe De Leon <x0095078@ti.com>
14  *
15  * This program is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU General Public License
17  * version 2 as published by the Free Software Foundation.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  */
24
25 #define pr_fmt(fmt)    "%s: " fmt, __func__
26
27 #include <linux/kernel.h>
28 #include <linux/module.h>
29 #include <linux/device.h>
30 #include <linux/slab.h>
31 #include <linux/mutex.h>
32 #include <linux/dma-mapping.h>
33 #include <linux/firmware.h>
34 #include <linux/string.h>
35 #include <linux/debugfs.h>
36 #include <linux/devcoredump.h>
37 #include <linux/remoteproc.h>
38 #include <linux/iommu.h>
39 #include <linux/idr.h>
40 #include <linux/elf.h>
41 #include <linux/crc32.h>
42 #include <linux/virtio_ids.h>
43 #include <linux/virtio_ring.h>
44 #include <asm/byteorder.h>
45
46 #include "remoteproc_internal.h"
47
48 static DEFINE_MUTEX(rproc_list_mutex);
49 static LIST_HEAD(rproc_list);
50
51 typedef int (*rproc_handle_resources_t)(struct rproc *rproc,
52                                 struct resource_table *table, int len);
53 typedef int (*rproc_handle_resource_t)(struct rproc *rproc,
54                                  void *, int offset, int avail);
55
56 /* Unique indices for remoteproc devices */
57 static DEFINE_IDA(rproc_dev_index);
58
59 static const char * const rproc_crash_names[] = {
60         [RPROC_MMUFAULT]        = "mmufault",
61         [RPROC_WATCHDOG]        = "watchdog",
62         [RPROC_FATAL_ERROR]     = "fatal error",
63 };
64
65 /* translate rproc_crash_type to string */
66 static const char *rproc_crash_to_string(enum rproc_crash_type type)
67 {
68         if (type < ARRAY_SIZE(rproc_crash_names))
69                 return rproc_crash_names[type];
70         return "unknown";
71 }
72
73 /*
74  * This is the IOMMU fault handler we register with the IOMMU API
75  * (when relevant; not all remote processors access memory through
76  * an IOMMU).
77  *
78  * IOMMU core will invoke this handler whenever the remote processor
79  * will try to access an unmapped device address.
80  */
81 static int rproc_iommu_fault(struct iommu_domain *domain, struct device *dev,
82                              unsigned long iova, int flags, void *token)
83 {
84         struct rproc *rproc = token;
85
86         dev_err(dev, "iommu fault: da 0x%lx flags 0x%x\n", iova, flags);
87
88         rproc_report_crash(rproc, RPROC_MMUFAULT);
89
90         /*
91          * Let the iommu core know we're not really handling this fault;
92          * we just used it as a recovery trigger.
93          */
94         return -ENOSYS;
95 }
96
97 static int rproc_enable_iommu(struct rproc *rproc)
98 {
99         struct iommu_domain *domain;
100         struct device *dev = rproc->dev.parent;
101         int ret;
102
103         if (!rproc->has_iommu) {
104                 dev_dbg(dev, "iommu not present\n");
105                 return 0;
106         }
107
108         domain = iommu_domain_alloc(dev->bus);
109         if (!domain) {
110                 dev_err(dev, "can't alloc iommu domain\n");
111                 return -ENOMEM;
112         }
113
114         iommu_set_fault_handler(domain, rproc_iommu_fault, rproc);
115
116         ret = iommu_attach_device(domain, dev);
117         if (ret) {
118                 dev_err(dev, "can't attach iommu device: %d\n", ret);
119                 goto free_domain;
120         }
121
122         rproc->domain = domain;
123
124         return 0;
125
126 free_domain:
127         iommu_domain_free(domain);
128         return ret;
129 }
130
131 static void rproc_disable_iommu(struct rproc *rproc)
132 {
133         struct iommu_domain *domain = rproc->domain;
134         struct device *dev = rproc->dev.parent;
135
136         if (!domain)
137                 return;
138
139         iommu_detach_device(domain, dev);
140         iommu_domain_free(domain);
141 }
142
143 /**
144  * rproc_da_to_va() - lookup the kernel virtual address for a remoteproc address
145  * @rproc: handle of a remote processor
146  * @da: remoteproc device address to translate
147  * @len: length of the memory region @da is pointing to
148  *
149  * Some remote processors will ask us to allocate them physically contiguous
150  * memory regions (which we call "carveouts"), and map them to specific
151  * device addresses (which are hardcoded in the firmware). They may also have
152  * dedicated memory regions internal to the processors, and use them either
153  * exclusively or alongside carveouts.
154  *
155  * They may then ask us to copy objects into specific device addresses (e.g.
156  * code/data sections) or expose us certain symbols in other device address
157  * (e.g. their trace buffer).
158  *
159  * This function is a helper function with which we can go over the allocated
160  * carveouts and translate specific device addresses to kernel virtual addresses
161  * so we can access the referenced memory. This function also allows to perform
162  * translations on the internal remoteproc memory regions through a platform
163  * implementation specific da_to_va ops, if present.
164  *
165  * The function returns a valid kernel address on success or NULL on failure.
166  *
167  * Note: phys_to_virt(iommu_iova_to_phys(rproc->domain, da)) will work too,
168  * but only on kernel direct mapped RAM memory. Instead, we're just using
169  * here the output of the DMA API for the carveouts, which should be more
170  * correct.
171  */
172 void *rproc_da_to_va(struct rproc *rproc, u64 da, int len)
173 {
174         struct rproc_mem_entry *carveout;
175         void *ptr = NULL;
176
177         if (rproc->ops->da_to_va) {
178                 ptr = rproc->ops->da_to_va(rproc, da, len);
179                 if (ptr)
180                         goto out;
181         }
182
183         list_for_each_entry(carveout, &rproc->carveouts, node) {
184                 int offset = da - carveout->da;
185
186                 /* try next carveout if da is too small */
187                 if (offset < 0)
188                         continue;
189
190                 /* try next carveout if da is too large */
191                 if (offset + len > carveout->len)
192                         continue;
193
194                 ptr = carveout->va + offset;
195
196                 break;
197         }
198
199 out:
200         return ptr;
201 }
202 EXPORT_SYMBOL(rproc_da_to_va);
203
204 int rproc_alloc_vring(struct rproc_vdev *rvdev, int i)
205 {
206         struct rproc *rproc = rvdev->rproc;
207         struct device *dev = &rproc->dev;
208         struct rproc_vring *rvring = &rvdev->vring[i];
209         struct fw_rsc_vdev *rsc;
210         dma_addr_t dma;
211         void *va;
212         int ret, size, notifyid;
213
214         /* actual size of vring (in bytes) */
215         size = PAGE_ALIGN(vring_size(rvring->len, rvring->align));
216
217         /*
218          * Allocate non-cacheable memory for the vring. In the future
219          * this call will also configure the IOMMU for us
220          */
221         va = dma_alloc_coherent(dev->parent, size, &dma, GFP_KERNEL);
222         if (!va) {
223                 dev_err(dev->parent, "dma_alloc_coherent failed\n");
224                 return -EINVAL;
225         }
226
227         /*
228          * Assign an rproc-wide unique index for this vring
229          * TODO: assign a notifyid for rvdev updates as well
230          * TODO: support predefined notifyids (via resource table)
231          */
232         ret = idr_alloc(&rproc->notifyids, rvring, 0, 0, GFP_KERNEL);
233         if (ret < 0) {
234                 dev_err(dev, "idr_alloc failed: %d\n", ret);
235                 dma_free_coherent(dev->parent, size, va, dma);
236                 return ret;
237         }
238         notifyid = ret;
239
240         /* Potentially bump max_notifyid */
241         if (notifyid > rproc->max_notifyid)
242                 rproc->max_notifyid = notifyid;
243
244         dev_dbg(dev, "vring%d: va %p dma %pad size 0x%x idr %d\n",
245                 i, va, &dma, size, notifyid);
246
247         rvring->va = va;
248         rvring->dma = dma;
249         rvring->notifyid = notifyid;
250
251         /*
252          * Let the rproc know the notifyid and da of this vring.
253          * Not all platforms use dma_alloc_coherent to automatically
254          * set up the iommu. In this case the device address (da) will
255          * hold the physical address and not the device address.
256          */
257         rsc = (void *)rproc->table_ptr + rvdev->rsc_offset;
258         rsc->vring[i].da = dma;
259         rsc->vring[i].notifyid = notifyid;
260         return 0;
261 }
262
263 static int
264 rproc_parse_vring(struct rproc_vdev *rvdev, struct fw_rsc_vdev *rsc, int i)
265 {
266         struct rproc *rproc = rvdev->rproc;
267         struct device *dev = &rproc->dev;
268         struct fw_rsc_vdev_vring *vring = &rsc->vring[i];
269         struct rproc_vring *rvring = &rvdev->vring[i];
270
271         dev_dbg(dev, "vdev rsc: vring%d: da 0x%x, qsz %d, align %d\n",
272                 i, vring->da, vring->num, vring->align);
273
274         /* verify queue size and vring alignment are sane */
275         if (!vring->num || !vring->align) {
276                 dev_err(dev, "invalid qsz (%d) or alignment (%d)\n",
277                         vring->num, vring->align);
278                 return -EINVAL;
279         }
280
281         rvring->len = vring->num;
282         rvring->align = vring->align;
283         rvring->rvdev = rvdev;
284
285         return 0;
286 }
287
288 void rproc_free_vring(struct rproc_vring *rvring)
289 {
290         int size = PAGE_ALIGN(vring_size(rvring->len, rvring->align));
291         struct rproc *rproc = rvring->rvdev->rproc;
292         int idx = rvring->rvdev->vring - rvring;
293         struct fw_rsc_vdev *rsc;
294
295         dma_free_coherent(rproc->dev.parent, size, rvring->va, rvring->dma);
296         idr_remove(&rproc->notifyids, rvring->notifyid);
297
298         /* reset resource entry info */
299         rsc = (void *)rproc->table_ptr + rvring->rvdev->rsc_offset;
300         rsc->vring[idx].da = 0;
301         rsc->vring[idx].notifyid = -1;
302 }
303
304 static int rproc_vdev_do_probe(struct rproc_subdev *subdev)
305 {
306         struct rproc_vdev *rvdev = container_of(subdev, struct rproc_vdev, subdev);
307
308         return rproc_add_virtio_dev(rvdev, rvdev->id);
309 }
310
311 static void rproc_vdev_do_remove(struct rproc_subdev *subdev, bool crashed)
312 {
313         struct rproc_vdev *rvdev = container_of(subdev, struct rproc_vdev, subdev);
314
315         rproc_remove_virtio_dev(rvdev);
316 }
317
318 /**
319  * rproc_handle_vdev() - handle a vdev fw resource
320  * @rproc: the remote processor
321  * @rsc: the vring resource descriptor
322  * @avail: size of available data (for sanity checking the image)
323  *
324  * This resource entry requests the host to statically register a virtio
325  * device (vdev), and setup everything needed to support it. It contains
326  * everything needed to make it possible: the virtio device id, virtio
327  * device features, vrings information, virtio config space, etc...
328  *
329  * Before registering the vdev, the vrings are allocated from non-cacheable
330  * physically contiguous memory. Currently we only support two vrings per
331  * remote processor (temporary limitation). We might also want to consider
332  * doing the vring allocation only later when ->find_vqs() is invoked, and
333  * then release them upon ->del_vqs().
334  *
335  * Note: @da is currently not really handled correctly: we dynamically
336  * allocate it using the DMA API, ignoring requested hard coded addresses,
337  * and we don't take care of any required IOMMU programming. This is all
338  * going to be taken care of when the generic iommu-based DMA API will be
339  * merged. Meanwhile, statically-addressed iommu-based firmware images should
340  * use RSC_DEVMEM resource entries to map their required @da to the physical
341  * address of their base CMA region (ouch, hacky!).
342  *
343  * Returns 0 on success, or an appropriate error code otherwise
344  */
345 static int rproc_handle_vdev(struct rproc *rproc, struct fw_rsc_vdev *rsc,
346                              int offset, int avail)
347 {
348         struct device *dev = &rproc->dev;
349         struct rproc_vdev *rvdev;
350         int i, ret;
351
352         /* make sure resource isn't truncated */
353         if (sizeof(*rsc) + rsc->num_of_vrings * sizeof(struct fw_rsc_vdev_vring)
354                         + rsc->config_len > avail) {
355                 dev_err(dev, "vdev rsc is truncated\n");
356                 return -EINVAL;
357         }
358
359         /* make sure reserved bytes are zeroes */
360         if (rsc->reserved[0] || rsc->reserved[1]) {
361                 dev_err(dev, "vdev rsc has non zero reserved bytes\n");
362                 return -EINVAL;
363         }
364
365         dev_dbg(dev, "vdev rsc: id %d, dfeatures 0x%x, cfg len %d, %d vrings\n",
366                 rsc->id, rsc->dfeatures, rsc->config_len, rsc->num_of_vrings);
367
368         /* we currently support only two vrings per rvdev */
369         if (rsc->num_of_vrings > ARRAY_SIZE(rvdev->vring)) {
370                 dev_err(dev, "too many vrings: %d\n", rsc->num_of_vrings);
371                 return -EINVAL;
372         }
373
374         rvdev = kzalloc(sizeof(*rvdev), GFP_KERNEL);
375         if (!rvdev)
376                 return -ENOMEM;
377
378         kref_init(&rvdev->refcount);
379
380         rvdev->id = rsc->id;
381         rvdev->rproc = rproc;
382
383         /* parse the vrings */
384         for (i = 0; i < rsc->num_of_vrings; i++) {
385                 ret = rproc_parse_vring(rvdev, rsc, i);
386                 if (ret)
387                         goto free_rvdev;
388         }
389
390         /* remember the resource offset*/
391         rvdev->rsc_offset = offset;
392
393         /* allocate the vring resources */
394         for (i = 0; i < rsc->num_of_vrings; i++) {
395                 ret = rproc_alloc_vring(rvdev, i);
396                 if (ret)
397                         goto unwind_vring_allocations;
398         }
399
400         list_add_tail(&rvdev->node, &rproc->rvdevs);
401
402         rproc_add_subdev(rproc, &rvdev->subdev,
403                          rproc_vdev_do_probe, rproc_vdev_do_remove);
404
405         return 0;
406
407 unwind_vring_allocations:
408         for (i--; i >= 0; i--)
409                 rproc_free_vring(&rvdev->vring[i]);
410 free_rvdev:
411         kfree(rvdev);
412         return ret;
413 }
414
415 void rproc_vdev_release(struct kref *ref)
416 {
417         struct rproc_vdev *rvdev = container_of(ref, struct rproc_vdev, refcount);
418         struct rproc_vring *rvring;
419         struct rproc *rproc = rvdev->rproc;
420         int id;
421
422         for (id = 0; id < ARRAY_SIZE(rvdev->vring); id++) {
423                 rvring = &rvdev->vring[id];
424                 if (!rvring->va)
425                         continue;
426
427                 rproc_free_vring(rvring);
428         }
429
430         rproc_remove_subdev(rproc, &rvdev->subdev);
431         list_del(&rvdev->node);
432         kfree(rvdev);
433 }
434
435 /**
436  * rproc_handle_trace() - handle a shared trace buffer resource
437  * @rproc: the remote processor
438  * @rsc: the trace resource descriptor
439  * @avail: size of available data (for sanity checking the image)
440  *
441  * In case the remote processor dumps trace logs into memory,
442  * export it via debugfs.
443  *
444  * Currently, the 'da' member of @rsc should contain the device address
445  * where the remote processor is dumping the traces. Later we could also
446  * support dynamically allocating this address using the generic
447  * DMA API (but currently there isn't a use case for that).
448  *
449  * Returns 0 on success, or an appropriate error code otherwise
450  */
451 static int rproc_handle_trace(struct rproc *rproc, struct fw_rsc_trace *rsc,
452                               int offset, int avail)
453 {
454         struct rproc_mem_entry *trace;
455         struct device *dev = &rproc->dev;
456         void *ptr;
457         char name[15];
458
459         if (sizeof(*rsc) > avail) {
460                 dev_err(dev, "trace rsc is truncated\n");
461                 return -EINVAL;
462         }
463
464         /* make sure reserved bytes are zeroes */
465         if (rsc->reserved) {
466                 dev_err(dev, "trace rsc has non zero reserved bytes\n");
467                 return -EINVAL;
468         }
469
470         /* what's the kernel address of this resource ? */
471         ptr = rproc_da_to_va(rproc, rsc->da, rsc->len);
472         if (!ptr) {
473                 dev_err(dev, "erroneous trace resource entry\n");
474                 return -EINVAL;
475         }
476
477         trace = kzalloc(sizeof(*trace), GFP_KERNEL);
478         if (!trace)
479                 return -ENOMEM;
480
481         /* set the trace buffer dma properties */
482         trace->len = rsc->len;
483         trace->va = ptr;
484
485         /* make sure snprintf always null terminates, even if truncating */
486         snprintf(name, sizeof(name), "trace%d", rproc->num_traces);
487
488         /* create the debugfs entry */
489         trace->priv = rproc_create_trace_file(name, rproc, trace);
490         if (!trace->priv) {
491                 trace->va = NULL;
492                 kfree(trace);
493                 return -EINVAL;
494         }
495
496         list_add_tail(&trace->node, &rproc->traces);
497
498         rproc->num_traces++;
499
500         dev_dbg(dev, "%s added: va %p, da 0x%x, len 0x%x\n",
501                 name, ptr, rsc->da, rsc->len);
502
503         return 0;
504 }
505
506 /**
507  * rproc_handle_devmem() - handle devmem resource entry
508  * @rproc: remote processor handle
509  * @rsc: the devmem resource entry
510  * @avail: size of available data (for sanity checking the image)
511  *
512  * Remote processors commonly need to access certain on-chip peripherals.
513  *
514  * Some of these remote processors access memory via an iommu device,
515  * and might require us to configure their iommu before they can access
516  * the on-chip peripherals they need.
517  *
518  * This resource entry is a request to map such a peripheral device.
519  *
520  * These devmem entries will contain the physical address of the device in
521  * the 'pa' member. If a specific device address is expected, then 'da' will
522  * contain it (currently this is the only use case supported). 'len' will
523  * contain the size of the physical region we need to map.
524  *
525  * Currently we just "trust" those devmem entries to contain valid physical
526  * addresses, but this is going to change: we want the implementations to
527  * tell us ranges of physical addresses the firmware is allowed to request,
528  * and not allow firmwares to request access to physical addresses that
529  * are outside those ranges.
530  */
531 static int rproc_handle_devmem(struct rproc *rproc, struct fw_rsc_devmem *rsc,
532                                int offset, int avail)
533 {
534         struct rproc_mem_entry *mapping;
535         struct device *dev = &rproc->dev;
536         int ret;
537
538         /* no point in handling this resource without a valid iommu domain */
539         if (!rproc->domain)
540                 return -EINVAL;
541
542         if (sizeof(*rsc) > avail) {
543                 dev_err(dev, "devmem rsc is truncated\n");
544                 return -EINVAL;
545         }
546
547         /* make sure reserved bytes are zeroes */
548         if (rsc->reserved) {
549                 dev_err(dev, "devmem rsc has non zero reserved bytes\n");
550                 return -EINVAL;
551         }
552
553         mapping = kzalloc(sizeof(*mapping), GFP_KERNEL);
554         if (!mapping)
555                 return -ENOMEM;
556
557         ret = iommu_map(rproc->domain, rsc->da, rsc->pa, rsc->len, rsc->flags);
558         if (ret) {
559                 dev_err(dev, "failed to map devmem: %d\n", ret);
560                 goto out;
561         }
562
563         /*
564          * We'll need this info later when we'll want to unmap everything
565          * (e.g. on shutdown).
566          *
567          * We can't trust the remote processor not to change the resource
568          * table, so we must maintain this info independently.
569          */
570         mapping->da = rsc->da;
571         mapping->len = rsc->len;
572         list_add_tail(&mapping->node, &rproc->mappings);
573
574         dev_dbg(dev, "mapped devmem pa 0x%x, da 0x%x, len 0x%x\n",
575                 rsc->pa, rsc->da, rsc->len);
576
577         return 0;
578
579 out:
580         kfree(mapping);
581         return ret;
582 }
583
584 /**
585  * rproc_handle_carveout() - handle phys contig memory allocation requests
586  * @rproc: rproc handle
587  * @rsc: the resource entry
588  * @avail: size of available data (for image validation)
589  *
590  * This function will handle firmware requests for allocation of physically
591  * contiguous memory regions.
592  *
593  * These request entries should come first in the firmware's resource table,
594  * as other firmware entries might request placing other data objects inside
595  * these memory regions (e.g. data/code segments, trace resource entries, ...).
596  *
597  * Allocating memory this way helps utilizing the reserved physical memory
598  * (e.g. CMA) more efficiently, and also minimizes the number of TLB entries
599  * needed to map it (in case @rproc is using an IOMMU). Reducing the TLB
600  * pressure is important; it may have a substantial impact on performance.
601  */
602 static int rproc_handle_carveout(struct rproc *rproc,
603                                  struct fw_rsc_carveout *rsc,
604                                  int offset, int avail)
605 {
606         struct rproc_mem_entry *carveout, *mapping;
607         struct device *dev = &rproc->dev;
608         dma_addr_t dma;
609         void *va;
610         int ret;
611
612         if (sizeof(*rsc) > avail) {
613                 dev_err(dev, "carveout rsc is truncated\n");
614                 return -EINVAL;
615         }
616
617         /* make sure reserved bytes are zeroes */
618         if (rsc->reserved) {
619                 dev_err(dev, "carveout rsc has non zero reserved bytes\n");
620                 return -EINVAL;
621         }
622
623         dev_dbg(dev, "carveout rsc: name: %s, da 0x%x, pa 0x%x, len 0x%x, flags 0x%x\n",
624                 rsc->name, rsc->da, rsc->pa, rsc->len, rsc->flags);
625
626         carveout = kzalloc(sizeof(*carveout), GFP_KERNEL);
627         if (!carveout)
628                 return -ENOMEM;
629
630         va = dma_alloc_coherent(dev->parent, rsc->len, &dma, GFP_KERNEL);
631         if (!va) {
632                 dev_err(dev->parent,
633                         "failed to allocate dma memory: len 0x%x\n", rsc->len);
634                 ret = -ENOMEM;
635                 goto free_carv;
636         }
637
638         dev_dbg(dev, "carveout va %p, dma %pad, len 0x%x\n",
639                 va, &dma, rsc->len);
640
641         /*
642          * Ok, this is non-standard.
643          *
644          * Sometimes we can't rely on the generic iommu-based DMA API
645          * to dynamically allocate the device address and then set the IOMMU
646          * tables accordingly, because some remote processors might
647          * _require_ us to use hard coded device addresses that their
648          * firmware was compiled with.
649          *
650          * In this case, we must use the IOMMU API directly and map
651          * the memory to the device address as expected by the remote
652          * processor.
653          *
654          * Obviously such remote processor devices should not be configured
655          * to use the iommu-based DMA API: we expect 'dma' to contain the
656          * physical address in this case.
657          */
658         if (rproc->domain) {
659                 mapping = kzalloc(sizeof(*mapping), GFP_KERNEL);
660                 if (!mapping) {
661                         ret = -ENOMEM;
662                         goto dma_free;
663                 }
664
665                 ret = iommu_map(rproc->domain, rsc->da, dma, rsc->len,
666                                 rsc->flags);
667                 if (ret) {
668                         dev_err(dev, "iommu_map failed: %d\n", ret);
669                         goto free_mapping;
670                 }
671
672                 /*
673                  * We'll need this info later when we'll want to unmap
674                  * everything (e.g. on shutdown).
675                  *
676                  * We can't trust the remote processor not to change the
677                  * resource table, so we must maintain this info independently.
678                  */
679                 mapping->da = rsc->da;
680                 mapping->len = rsc->len;
681                 list_add_tail(&mapping->node, &rproc->mappings);
682
683                 dev_dbg(dev, "carveout mapped 0x%x to %pad\n",
684                         rsc->da, &dma);
685         }
686
687         /*
688          * Some remote processors might need to know the pa
689          * even though they are behind an IOMMU. E.g., OMAP4's
690          * remote M3 processor needs this so it can control
691          * on-chip hardware accelerators that are not behind
692          * the IOMMU, and therefor must know the pa.
693          *
694          * Generally we don't want to expose physical addresses
695          * if we don't have to (remote processors are generally
696          * _not_ trusted), so we might want to do this only for
697          * remote processor that _must_ have this (e.g. OMAP4's
698          * dual M3 subsystem).
699          *
700          * Non-IOMMU processors might also want to have this info.
701          * In this case, the device address and the physical address
702          * are the same.
703          */
704         rsc->pa = dma;
705
706         carveout->va = va;
707         carveout->len = rsc->len;
708         carveout->dma = dma;
709         carveout->da = rsc->da;
710
711         list_add_tail(&carveout->node, &rproc->carveouts);
712
713         return 0;
714
715 free_mapping:
716         kfree(mapping);
717 dma_free:
718         dma_free_coherent(dev->parent, rsc->len, va, dma);
719 free_carv:
720         kfree(carveout);
721         return ret;
722 }
723
724 /*
725  * A lookup table for resource handlers. The indices are defined in
726  * enum fw_resource_type.
727  */
728 static rproc_handle_resource_t rproc_loading_handlers[RSC_LAST] = {
729         [RSC_CARVEOUT] = (rproc_handle_resource_t)rproc_handle_carveout,
730         [RSC_DEVMEM] = (rproc_handle_resource_t)rproc_handle_devmem,
731         [RSC_TRACE] = (rproc_handle_resource_t)rproc_handle_trace,
732         [RSC_VDEV] = (rproc_handle_resource_t)rproc_handle_vdev,
733 };
734
735 /* handle firmware resource entries before booting the remote processor */
736 static int rproc_handle_resources(struct rproc *rproc,
737                                   rproc_handle_resource_t handlers[RSC_LAST])
738 {
739         struct device *dev = &rproc->dev;
740         rproc_handle_resource_t handler;
741         int ret = 0, i;
742
743         if (!rproc->table_ptr)
744                 return 0;
745
746         for (i = 0; i < rproc->table_ptr->num; i++) {
747                 int offset = rproc->table_ptr->offset[i];
748                 struct fw_rsc_hdr *hdr = (void *)rproc->table_ptr + offset;
749                 int avail = rproc->table_sz - offset - sizeof(*hdr);
750                 void *rsc = (void *)hdr + sizeof(*hdr);
751
752                 /* make sure table isn't truncated */
753                 if (avail < 0) {
754                         dev_err(dev, "rsc table is truncated\n");
755                         return -EINVAL;
756                 }
757
758                 dev_dbg(dev, "rsc: type %d\n", hdr->type);
759
760                 if (hdr->type >= RSC_LAST) {
761                         dev_warn(dev, "unsupported resource %d\n", hdr->type);
762                         continue;
763                 }
764
765                 handler = handlers[hdr->type];
766                 if (!handler)
767                         continue;
768
769                 ret = handler(rproc, rsc, offset + sizeof(*hdr), avail);
770                 if (ret)
771                         break;
772         }
773
774         return ret;
775 }
776
777 static int rproc_probe_subdevices(struct rproc *rproc)
778 {
779         struct rproc_subdev *subdev;
780         int ret;
781
782         list_for_each_entry(subdev, &rproc->subdevs, node) {
783                 ret = subdev->probe(subdev);
784                 if (ret)
785                         goto unroll_registration;
786         }
787
788         return 0;
789
790 unroll_registration:
791         list_for_each_entry_continue_reverse(subdev, &rproc->subdevs, node)
792                 subdev->remove(subdev, true);
793
794         return ret;
795 }
796
797 static void rproc_remove_subdevices(struct rproc *rproc, bool crashed)
798 {
799         struct rproc_subdev *subdev;
800
801         list_for_each_entry_reverse(subdev, &rproc->subdevs, node)
802                 subdev->remove(subdev, crashed);
803 }
804
805 /**
806  * rproc_coredump_cleanup() - clean up dump_segments list
807  * @rproc: the remote processor handle
808  */
809 static void rproc_coredump_cleanup(struct rproc *rproc)
810 {
811         struct rproc_dump_segment *entry, *tmp;
812
813         list_for_each_entry_safe(entry, tmp, &rproc->dump_segments, node) {
814                 list_del(&entry->node);
815                 kfree(entry);
816         }
817 }
818
819 /**
820  * rproc_resource_cleanup() - clean up and free all acquired resources
821  * @rproc: rproc handle
822  *
823  * This function will free all resources acquired for @rproc, and it
824  * is called whenever @rproc either shuts down or fails to boot.
825  */
826 static void rproc_resource_cleanup(struct rproc *rproc)
827 {
828         struct rproc_mem_entry *entry, *tmp;
829         struct rproc_vdev *rvdev, *rvtmp;
830         struct device *dev = &rproc->dev;
831
832         /* clean up debugfs trace entries */
833         list_for_each_entry_safe(entry, tmp, &rproc->traces, node) {
834                 rproc_remove_trace_file(entry->priv);
835                 rproc->num_traces--;
836                 list_del(&entry->node);
837                 kfree(entry);
838         }
839
840         /* clean up iommu mapping entries */
841         list_for_each_entry_safe(entry, tmp, &rproc->mappings, node) {
842                 size_t unmapped;
843
844                 unmapped = iommu_unmap(rproc->domain, entry->da, entry->len);
845                 if (unmapped != entry->len) {
846                         /* nothing much to do besides complaining */
847                         dev_err(dev, "failed to unmap %u/%zu\n", entry->len,
848                                 unmapped);
849                 }
850
851                 list_del(&entry->node);
852                 kfree(entry);
853         }
854
855         /* clean up carveout allocations */
856         list_for_each_entry_safe(entry, tmp, &rproc->carveouts, node) {
857                 dma_free_coherent(dev->parent, entry->len, entry->va,
858                                   entry->dma);
859                 list_del(&entry->node);
860                 kfree(entry);
861         }
862
863         /* clean up remote vdev entries */
864         list_for_each_entry_safe(rvdev, rvtmp, &rproc->rvdevs, node)
865                 kref_put(&rvdev->refcount, rproc_vdev_release);
866
867         rproc_coredump_cleanup(rproc);
868 }
869
870 static int rproc_start(struct rproc *rproc, const struct firmware *fw)
871 {
872         struct resource_table *loaded_table;
873         struct device *dev = &rproc->dev;
874         int ret;
875
876         /* load the ELF segments to memory */
877         ret = rproc_load_segments(rproc, fw);
878         if (ret) {
879                 dev_err(dev, "Failed to load program segments: %d\n", ret);
880                 return ret;
881         }
882
883         /*
884          * The starting device has been given the rproc->cached_table as the
885          * resource table. The address of the vring along with the other
886          * allocated resources (carveouts etc) is stored in cached_table.
887          * In order to pass this information to the remote device we must copy
888          * this information to device memory. We also update the table_ptr so
889          * that any subsequent changes will be applied to the loaded version.
890          */
891         loaded_table = rproc_find_loaded_rsc_table(rproc, fw);
892         if (loaded_table) {
893                 memcpy(loaded_table, rproc->cached_table, rproc->table_sz);
894                 rproc->table_ptr = loaded_table;
895         }
896
897         /* power up the remote processor */
898         ret = rproc->ops->start(rproc);
899         if (ret) {
900                 dev_err(dev, "can't start rproc %s: %d\n", rproc->name, ret);
901                 return ret;
902         }
903
904         /* probe any subdevices for the remote processor */
905         ret = rproc_probe_subdevices(rproc);
906         if (ret) {
907                 dev_err(dev, "failed to probe subdevices for %s: %d\n",
908                         rproc->name, ret);
909                 rproc->ops->stop(rproc);
910                 return ret;
911         }
912
913         rproc->state = RPROC_RUNNING;
914
915         dev_info(dev, "remote processor %s is now up\n", rproc->name);
916
917         return 0;
918 }
919
920 /*
921  * take a firmware and boot a remote processor with it.
922  */
923 static int rproc_fw_boot(struct rproc *rproc, const struct firmware *fw)
924 {
925         struct device *dev = &rproc->dev;
926         const char *name = rproc->firmware;
927         int ret;
928
929         ret = rproc_fw_sanity_check(rproc, fw);
930         if (ret)
931                 return ret;
932
933         dev_info(dev, "Booting fw image %s, size %zd\n", name, fw->size);
934
935         /*
936          * if enabling an IOMMU isn't relevant for this rproc, this is
937          * just a nop
938          */
939         ret = rproc_enable_iommu(rproc);
940         if (ret) {
941                 dev_err(dev, "can't enable iommu: %d\n", ret);
942                 return ret;
943         }
944
945         rproc->bootaddr = rproc_get_boot_addr(rproc, fw);
946
947         /* Load resource table, core dump segment list etc from the firmware */
948         ret = rproc_parse_fw(rproc, fw);
949         if (ret)
950                 goto disable_iommu;
951
952         /* reset max_notifyid */
953         rproc->max_notifyid = -1;
954
955         /* handle fw resources which are required to boot rproc */
956         ret = rproc_handle_resources(rproc, rproc_loading_handlers);
957         if (ret) {
958                 dev_err(dev, "Failed to process resources: %d\n", ret);
959                 goto clean_up_resources;
960         }
961
962         ret = rproc_start(rproc, fw);
963         if (ret)
964                 goto clean_up_resources;
965
966         return 0;
967
968 clean_up_resources:
969         rproc_resource_cleanup(rproc);
970         kfree(rproc->cached_table);
971         rproc->cached_table = NULL;
972         rproc->table_ptr = NULL;
973 disable_iommu:
974         rproc_disable_iommu(rproc);
975         return ret;
976 }
977
978 /*
979  * take a firmware and boot it up.
980  *
981  * Note: this function is called asynchronously upon registration of the
982  * remote processor (so we must wait until it completes before we try
983  * to unregister the device. one other option is just to use kref here,
984  * that might be cleaner).
985  */
986 static void rproc_auto_boot_callback(const struct firmware *fw, void *context)
987 {
988         struct rproc *rproc = context;
989
990         rproc_boot(rproc);
991
992         release_firmware(fw);
993 }
994
995 static int rproc_trigger_auto_boot(struct rproc *rproc)
996 {
997         int ret;
998
999         /*
1000          * We're initiating an asynchronous firmware loading, so we can
1001          * be built-in kernel code, without hanging the boot process.
1002          */
1003         ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_HOTPLUG,
1004                                       rproc->firmware, &rproc->dev, GFP_KERNEL,
1005                                       rproc, rproc_auto_boot_callback);
1006         if (ret < 0)
1007                 dev_err(&rproc->dev, "request_firmware_nowait err: %d\n", ret);
1008
1009         return ret;
1010 }
1011
1012 static int rproc_stop(struct rproc *rproc, bool crashed)
1013 {
1014         struct device *dev = &rproc->dev;
1015         int ret;
1016
1017         /* remove any subdevices for the remote processor */
1018         rproc_remove_subdevices(rproc, crashed);
1019
1020         /* the installed resource table is no longer accessible */
1021         rproc->table_ptr = rproc->cached_table;
1022
1023         /* power off the remote processor */
1024         ret = rproc->ops->stop(rproc);
1025         if (ret) {
1026                 dev_err(dev, "can't stop rproc: %d\n", ret);
1027                 return ret;
1028         }
1029
1030         rproc->state = RPROC_OFFLINE;
1031
1032         dev_info(dev, "stopped remote processor %s\n", rproc->name);
1033
1034         return 0;
1035 }
1036
1037 /**
1038  * rproc_coredump_add_segment() - add segment of device memory to coredump
1039  * @rproc:      handle of a remote processor
1040  * @da:         device address
1041  * @size:       size of segment
1042  *
1043  * Add device memory to the list of segments to be included in a coredump for
1044  * the remoteproc.
1045  *
1046  * Return: 0 on success, negative errno on error.
1047  */
1048 int rproc_coredump_add_segment(struct rproc *rproc, dma_addr_t da, size_t size)
1049 {
1050         struct rproc_dump_segment *segment;
1051
1052         segment = kzalloc(sizeof(*segment), GFP_KERNEL);
1053         if (!segment)
1054                 return -ENOMEM;
1055
1056         segment->da = da;
1057         segment->size = size;
1058
1059         list_add_tail(&segment->node, &rproc->dump_segments);
1060
1061         return 0;
1062 }
1063 EXPORT_SYMBOL(rproc_coredump_add_segment);
1064
1065 /**
1066  * rproc_coredump() - perform coredump
1067  * @rproc:      rproc handle
1068  *
1069  * This function will generate an ELF header for the registered segments
1070  * and create a devcoredump device associated with rproc.
1071  */
1072 static void rproc_coredump(struct rproc *rproc)
1073 {
1074         struct rproc_dump_segment *segment;
1075         struct elf32_phdr *phdr;
1076         struct elf32_hdr *ehdr;
1077         size_t data_size;
1078         size_t offset;
1079         void *data;
1080         void *ptr;
1081         int phnum = 0;
1082
1083         if (list_empty(&rproc->dump_segments))
1084                 return;
1085
1086         data_size = sizeof(*ehdr);
1087         list_for_each_entry(segment, &rproc->dump_segments, node) {
1088                 data_size += sizeof(*phdr) + segment->size;
1089
1090                 phnum++;
1091         }
1092
1093         data = vmalloc(data_size);
1094         if (!data)
1095                 return;
1096
1097         ehdr = data;
1098
1099         memset(ehdr, 0, sizeof(*ehdr));
1100         memcpy(ehdr->e_ident, ELFMAG, SELFMAG);
1101         ehdr->e_ident[EI_CLASS] = ELFCLASS32;
1102         ehdr->e_ident[EI_DATA] = ELFDATA2LSB;
1103         ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1104         ehdr->e_ident[EI_OSABI] = ELFOSABI_NONE;
1105         ehdr->e_type = ET_CORE;
1106         ehdr->e_machine = EM_NONE;
1107         ehdr->e_version = EV_CURRENT;
1108         ehdr->e_entry = rproc->bootaddr;
1109         ehdr->e_phoff = sizeof(*ehdr);
1110         ehdr->e_ehsize = sizeof(*ehdr);
1111         ehdr->e_phentsize = sizeof(*phdr);
1112         ehdr->e_phnum = phnum;
1113
1114         phdr = data + ehdr->e_phoff;
1115         offset = ehdr->e_phoff + sizeof(*phdr) * ehdr->e_phnum;
1116         list_for_each_entry(segment, &rproc->dump_segments, node) {
1117                 memset(phdr, 0, sizeof(*phdr));
1118                 phdr->p_type = PT_LOAD;
1119                 phdr->p_offset = offset;
1120                 phdr->p_vaddr = segment->da;
1121                 phdr->p_paddr = segment->da;
1122                 phdr->p_filesz = segment->size;
1123                 phdr->p_memsz = segment->size;
1124                 phdr->p_flags = PF_R | PF_W | PF_X;
1125                 phdr->p_align = 0;
1126
1127                 ptr = rproc_da_to_va(rproc, segment->da, segment->size);
1128                 if (!ptr) {
1129                         dev_err(&rproc->dev,
1130                                 "invalid coredump segment (%pad, %zu)\n",
1131                                 &segment->da, segment->size);
1132                         memset(data + offset, 0xff, segment->size);
1133                 } else {
1134                         memcpy(data + offset, ptr, segment->size);
1135                 }
1136
1137                 offset += phdr->p_filesz;
1138                 phdr++;
1139         }
1140
1141         dev_coredumpv(&rproc->dev, data, data_size, GFP_KERNEL);
1142 }
1143
1144 /**
1145  * rproc_trigger_recovery() - recover a remoteproc
1146  * @rproc: the remote processor
1147  *
1148  * The recovery is done by resetting all the virtio devices, that way all the
1149  * rpmsg drivers will be reseted along with the remote processor making the
1150  * remoteproc functional again.
1151  *
1152  * This function can sleep, so it cannot be called from atomic context.
1153  */
1154 int rproc_trigger_recovery(struct rproc *rproc)
1155 {
1156         const struct firmware *firmware_p;
1157         struct device *dev = &rproc->dev;
1158         int ret;
1159
1160         dev_err(dev, "recovering %s\n", rproc->name);
1161
1162         ret = mutex_lock_interruptible(&rproc->lock);
1163         if (ret)
1164                 return ret;
1165
1166         ret = rproc_stop(rproc, true);
1167         if (ret)
1168                 goto unlock_mutex;
1169
1170         /* generate coredump */
1171         rproc_coredump(rproc);
1172
1173         /* load firmware */
1174         ret = request_firmware(&firmware_p, rproc->firmware, dev);
1175         if (ret < 0) {
1176                 dev_err(dev, "request_firmware failed: %d\n", ret);
1177                 goto unlock_mutex;
1178         }
1179
1180         /* boot the remote processor up again */
1181         ret = rproc_start(rproc, firmware_p);
1182
1183         release_firmware(firmware_p);
1184
1185 unlock_mutex:
1186         mutex_unlock(&rproc->lock);
1187         return ret;
1188 }
1189
1190 /**
1191  * rproc_crash_handler_work() - handle a crash
1192  *
1193  * This function needs to handle everything related to a crash, like cpu
1194  * registers and stack dump, information to help to debug the fatal error, etc.
1195  */
1196 static void rproc_crash_handler_work(struct work_struct *work)
1197 {
1198         struct rproc *rproc = container_of(work, struct rproc, crash_handler);
1199         struct device *dev = &rproc->dev;
1200
1201         dev_dbg(dev, "enter %s\n", __func__);
1202
1203         mutex_lock(&rproc->lock);
1204
1205         if (rproc->state == RPROC_CRASHED || rproc->state == RPROC_OFFLINE) {
1206                 /* handle only the first crash detected */
1207                 mutex_unlock(&rproc->lock);
1208                 return;
1209         }
1210
1211         rproc->state = RPROC_CRASHED;
1212         dev_err(dev, "handling crash #%u in %s\n", ++rproc->crash_cnt,
1213                 rproc->name);
1214
1215         mutex_unlock(&rproc->lock);
1216
1217         if (!rproc->recovery_disabled)
1218                 rproc_trigger_recovery(rproc);
1219 }
1220
1221 /**
1222  * rproc_boot() - boot a remote processor
1223  * @rproc: handle of a remote processor
1224  *
1225  * Boot a remote processor (i.e. load its firmware, power it on, ...).
1226  *
1227  * If the remote processor is already powered on, this function immediately
1228  * returns (successfully).
1229  *
1230  * Returns 0 on success, and an appropriate error value otherwise.
1231  */
1232 int rproc_boot(struct rproc *rproc)
1233 {
1234         const struct firmware *firmware_p;
1235         struct device *dev;
1236         int ret;
1237
1238         if (!rproc) {
1239                 pr_err("invalid rproc handle\n");
1240                 return -EINVAL;
1241         }
1242
1243         dev = &rproc->dev;
1244
1245         ret = mutex_lock_interruptible(&rproc->lock);
1246         if (ret) {
1247                 dev_err(dev, "can't lock rproc %s: %d\n", rproc->name, ret);
1248                 return ret;
1249         }
1250
1251         if (rproc->state == RPROC_DELETED) {
1252                 ret = -ENODEV;
1253                 dev_err(dev, "can't boot deleted rproc %s\n", rproc->name);
1254                 goto unlock_mutex;
1255         }
1256
1257         /* skip the boot process if rproc is already powered up */
1258         if (atomic_inc_return(&rproc->power) > 1) {
1259                 ret = 0;
1260                 goto unlock_mutex;
1261         }
1262
1263         dev_info(dev, "powering up %s\n", rproc->name);
1264
1265         /* load firmware */
1266         ret = request_firmware(&firmware_p, rproc->firmware, dev);
1267         if (ret < 0) {
1268                 dev_err(dev, "request_firmware failed: %d\n", ret);
1269                 goto downref_rproc;
1270         }
1271
1272         ret = rproc_fw_boot(rproc, firmware_p);
1273
1274         release_firmware(firmware_p);
1275
1276 downref_rproc:
1277         if (ret)
1278                 atomic_dec(&rproc->power);
1279 unlock_mutex:
1280         mutex_unlock(&rproc->lock);
1281         return ret;
1282 }
1283 EXPORT_SYMBOL(rproc_boot);
1284
1285 /**
1286  * rproc_shutdown() - power off the remote processor
1287  * @rproc: the remote processor
1288  *
1289  * Power off a remote processor (previously booted with rproc_boot()).
1290  *
1291  * In case @rproc is still being used by an additional user(s), then
1292  * this function will just decrement the power refcount and exit,
1293  * without really powering off the device.
1294  *
1295  * Every call to rproc_boot() must (eventually) be accompanied by a call
1296  * to rproc_shutdown(). Calling rproc_shutdown() redundantly is a bug.
1297  *
1298  * Notes:
1299  * - we're not decrementing the rproc's refcount, only the power refcount.
1300  *   which means that the @rproc handle stays valid even after rproc_shutdown()
1301  *   returns, and users can still use it with a subsequent rproc_boot(), if
1302  *   needed.
1303  */
1304 void rproc_shutdown(struct rproc *rproc)
1305 {
1306         struct device *dev = &rproc->dev;
1307         int ret;
1308
1309         ret = mutex_lock_interruptible(&rproc->lock);
1310         if (ret) {
1311                 dev_err(dev, "can't lock rproc %s: %d\n", rproc->name, ret);
1312                 return;
1313         }
1314
1315         /* if the remote proc is still needed, bail out */
1316         if (!atomic_dec_and_test(&rproc->power))
1317                 goto out;
1318
1319         ret = rproc_stop(rproc, false);
1320         if (ret) {
1321                 atomic_inc(&rproc->power);
1322                 goto out;
1323         }
1324
1325         /* clean up all acquired resources */
1326         rproc_resource_cleanup(rproc);
1327
1328         rproc_disable_iommu(rproc);
1329
1330         /* Free the copy of the resource table */
1331         kfree(rproc->cached_table);
1332         rproc->cached_table = NULL;
1333         rproc->table_ptr = NULL;
1334 out:
1335         mutex_unlock(&rproc->lock);
1336 }
1337 EXPORT_SYMBOL(rproc_shutdown);
1338
1339 /**
1340  * rproc_get_by_phandle() - find a remote processor by phandle
1341  * @phandle: phandle to the rproc
1342  *
1343  * Finds an rproc handle using the remote processor's phandle, and then
1344  * return a handle to the rproc.
1345  *
1346  * This function increments the remote processor's refcount, so always
1347  * use rproc_put() to decrement it back once rproc isn't needed anymore.
1348  *
1349  * Returns the rproc handle on success, and NULL on failure.
1350  */
1351 #ifdef CONFIG_OF
1352 struct rproc *rproc_get_by_phandle(phandle phandle)
1353 {
1354         struct rproc *rproc = NULL, *r;
1355         struct device_node *np;
1356
1357         np = of_find_node_by_phandle(phandle);
1358         if (!np)
1359                 return NULL;
1360
1361         mutex_lock(&rproc_list_mutex);
1362         list_for_each_entry(r, &rproc_list, node) {
1363                 if (r->dev.parent && r->dev.parent->of_node == np) {
1364                         /* prevent underlying implementation from being removed */
1365                         if (!try_module_get(r->dev.parent->driver->owner)) {
1366                                 dev_err(&r->dev, "can't get owner\n");
1367                                 break;
1368                         }
1369
1370                         rproc = r;
1371                         get_device(&rproc->dev);
1372                         break;
1373                 }
1374         }
1375         mutex_unlock(&rproc_list_mutex);
1376
1377         of_node_put(np);
1378
1379         return rproc;
1380 }
1381 #else
1382 struct rproc *rproc_get_by_phandle(phandle phandle)
1383 {
1384         return NULL;
1385 }
1386 #endif
1387 EXPORT_SYMBOL(rproc_get_by_phandle);
1388
1389 /**
1390  * rproc_add() - register a remote processor
1391  * @rproc: the remote processor handle to register
1392  *
1393  * Registers @rproc with the remoteproc framework, after it has been
1394  * allocated with rproc_alloc().
1395  *
1396  * This is called by the platform-specific rproc implementation, whenever
1397  * a new remote processor device is probed.
1398  *
1399  * Returns 0 on success and an appropriate error code otherwise.
1400  *
1401  * Note: this function initiates an asynchronous firmware loading
1402  * context, which will look for virtio devices supported by the rproc's
1403  * firmware.
1404  *
1405  * If found, those virtio devices will be created and added, so as a result
1406  * of registering this remote processor, additional virtio drivers might be
1407  * probed.
1408  */
1409 int rproc_add(struct rproc *rproc)
1410 {
1411         struct device *dev = &rproc->dev;
1412         int ret;
1413
1414         ret = device_add(dev);
1415         if (ret < 0)
1416                 return ret;
1417
1418         dev_info(dev, "%s is available\n", rproc->name);
1419
1420         /* create debugfs entries */
1421         rproc_create_debug_dir(rproc);
1422
1423         /* if rproc is marked always-on, request it to boot */
1424         if (rproc->auto_boot) {
1425                 ret = rproc_trigger_auto_boot(rproc);
1426                 if (ret < 0)
1427                         return ret;
1428         }
1429
1430         /* expose to rproc_get_by_phandle users */
1431         mutex_lock(&rproc_list_mutex);
1432         list_add(&rproc->node, &rproc_list);
1433         mutex_unlock(&rproc_list_mutex);
1434
1435         return 0;
1436 }
1437 EXPORT_SYMBOL(rproc_add);
1438
1439 /**
1440  * rproc_type_release() - release a remote processor instance
1441  * @dev: the rproc's device
1442  *
1443  * This function should _never_ be called directly.
1444  *
1445  * It will be called by the driver core when no one holds a valid pointer
1446  * to @dev anymore.
1447  */
1448 static void rproc_type_release(struct device *dev)
1449 {
1450         struct rproc *rproc = container_of(dev, struct rproc, dev);
1451
1452         dev_info(&rproc->dev, "releasing %s\n", rproc->name);
1453
1454         idr_destroy(&rproc->notifyids);
1455
1456         if (rproc->index >= 0)
1457                 ida_simple_remove(&rproc_dev_index, rproc->index);
1458
1459         kfree(rproc->firmware);
1460         kfree(rproc->ops);
1461         kfree(rproc);
1462 }
1463
1464 static const struct device_type rproc_type = {
1465         .name           = "remoteproc",
1466         .release        = rproc_type_release,
1467 };
1468
1469 /**
1470  * rproc_alloc() - allocate a remote processor handle
1471  * @dev: the underlying device
1472  * @name: name of this remote processor
1473  * @ops: platform-specific handlers (mainly start/stop)
1474  * @firmware: name of firmware file to load, can be NULL
1475  * @len: length of private data needed by the rproc driver (in bytes)
1476  *
1477  * Allocates a new remote processor handle, but does not register
1478  * it yet. if @firmware is NULL, a default name is used.
1479  *
1480  * This function should be used by rproc implementations during initialization
1481  * of the remote processor.
1482  *
1483  * After creating an rproc handle using this function, and when ready,
1484  * implementations should then call rproc_add() to complete
1485  * the registration of the remote processor.
1486  *
1487  * On success the new rproc is returned, and on failure, NULL.
1488  *
1489  * Note: _never_ directly deallocate @rproc, even if it was not registered
1490  * yet. Instead, when you need to unroll rproc_alloc(), use rproc_free().
1491  */
1492 struct rproc *rproc_alloc(struct device *dev, const char *name,
1493                           const struct rproc_ops *ops,
1494                           const char *firmware, int len)
1495 {
1496         struct rproc *rproc;
1497         char *p, *template = "rproc-%s-fw";
1498         int name_len;
1499
1500         if (!dev || !name || !ops)
1501                 return NULL;
1502
1503         if (!firmware) {
1504                 /*
1505                  * If the caller didn't pass in a firmware name then
1506                  * construct a default name.
1507                  */
1508                 name_len = strlen(name) + strlen(template) - 2 + 1;
1509                 p = kmalloc(name_len, GFP_KERNEL);
1510                 if (!p)
1511                         return NULL;
1512                 snprintf(p, name_len, template, name);
1513         } else {
1514                 p = kstrdup(firmware, GFP_KERNEL);
1515                 if (!p)
1516                         return NULL;
1517         }
1518
1519         rproc = kzalloc(sizeof(struct rproc) + len, GFP_KERNEL);
1520         if (!rproc) {
1521                 kfree(p);
1522                 return NULL;
1523         }
1524
1525         rproc->ops = kmemdup(ops, sizeof(*ops), GFP_KERNEL);
1526         if (!rproc->ops) {
1527                 kfree(p);
1528                 kfree(rproc);
1529                 return NULL;
1530         }
1531
1532         rproc->firmware = p;
1533         rproc->name = name;
1534         rproc->priv = &rproc[1];
1535         rproc->auto_boot = true;
1536
1537         device_initialize(&rproc->dev);
1538         rproc->dev.parent = dev;
1539         rproc->dev.type = &rproc_type;
1540         rproc->dev.class = &rproc_class;
1541         rproc->dev.driver_data = rproc;
1542
1543         /* Assign a unique device index and name */
1544         rproc->index = ida_simple_get(&rproc_dev_index, 0, 0, GFP_KERNEL);
1545         if (rproc->index < 0) {
1546                 dev_err(dev, "ida_simple_get failed: %d\n", rproc->index);
1547                 put_device(&rproc->dev);
1548                 return NULL;
1549         }
1550
1551         dev_set_name(&rproc->dev, "remoteproc%d", rproc->index);
1552
1553         atomic_set(&rproc->power, 0);
1554
1555         /* Default to ELF loader if no load function is specified */
1556         if (!rproc->ops->load) {
1557                 rproc->ops->load = rproc_elf_load_segments;
1558                 rproc->ops->parse_fw = rproc_elf_load_rsc_table;
1559                 rproc->ops->find_loaded_rsc_table = rproc_elf_find_loaded_rsc_table;
1560                 rproc->ops->sanity_check = rproc_elf_sanity_check;
1561                 rproc->ops->get_boot_addr = rproc_elf_get_boot_addr;
1562         }
1563
1564         mutex_init(&rproc->lock);
1565
1566         idr_init(&rproc->notifyids);
1567
1568         INIT_LIST_HEAD(&rproc->carveouts);
1569         INIT_LIST_HEAD(&rproc->mappings);
1570         INIT_LIST_HEAD(&rproc->traces);
1571         INIT_LIST_HEAD(&rproc->rvdevs);
1572         INIT_LIST_HEAD(&rproc->subdevs);
1573         INIT_LIST_HEAD(&rproc->dump_segments);
1574
1575         INIT_WORK(&rproc->crash_handler, rproc_crash_handler_work);
1576
1577         rproc->state = RPROC_OFFLINE;
1578
1579         return rproc;
1580 }
1581 EXPORT_SYMBOL(rproc_alloc);
1582
1583 /**
1584  * rproc_free() - unroll rproc_alloc()
1585  * @rproc: the remote processor handle
1586  *
1587  * This function decrements the rproc dev refcount.
1588  *
1589  * If no one holds any reference to rproc anymore, then its refcount would
1590  * now drop to zero, and it would be freed.
1591  */
1592 void rproc_free(struct rproc *rproc)
1593 {
1594         put_device(&rproc->dev);
1595 }
1596 EXPORT_SYMBOL(rproc_free);
1597
1598 /**
1599  * rproc_put() - release rproc reference
1600  * @rproc: the remote processor handle
1601  *
1602  * This function decrements the rproc dev refcount.
1603  *
1604  * If no one holds any reference to rproc anymore, then its refcount would
1605  * now drop to zero, and it would be freed.
1606  */
1607 void rproc_put(struct rproc *rproc)
1608 {
1609         module_put(rproc->dev.parent->driver->owner);
1610         put_device(&rproc->dev);
1611 }
1612 EXPORT_SYMBOL(rproc_put);
1613
1614 /**
1615  * rproc_del() - unregister a remote processor
1616  * @rproc: rproc handle to unregister
1617  *
1618  * This function should be called when the platform specific rproc
1619  * implementation decides to remove the rproc device. it should
1620  * _only_ be called if a previous invocation of rproc_add()
1621  * has completed successfully.
1622  *
1623  * After rproc_del() returns, @rproc isn't freed yet, because
1624  * of the outstanding reference created by rproc_alloc. To decrement that
1625  * one last refcount, one still needs to call rproc_free().
1626  *
1627  * Returns 0 on success and -EINVAL if @rproc isn't valid.
1628  */
1629 int rproc_del(struct rproc *rproc)
1630 {
1631         if (!rproc)
1632                 return -EINVAL;
1633
1634         /* if rproc is marked always-on, rproc_add() booted it */
1635         /* TODO: make sure this works with rproc->power > 1 */
1636         if (rproc->auto_boot)
1637                 rproc_shutdown(rproc);
1638
1639         mutex_lock(&rproc->lock);
1640         rproc->state = RPROC_DELETED;
1641         mutex_unlock(&rproc->lock);
1642
1643         rproc_delete_debug_dir(rproc);
1644
1645         /* the rproc is downref'ed as soon as it's removed from the klist */
1646         mutex_lock(&rproc_list_mutex);
1647         list_del(&rproc->node);
1648         mutex_unlock(&rproc_list_mutex);
1649
1650         device_del(&rproc->dev);
1651
1652         return 0;
1653 }
1654 EXPORT_SYMBOL(rproc_del);
1655
1656 /**
1657  * rproc_add_subdev() - add a subdevice to a remoteproc
1658  * @rproc: rproc handle to add the subdevice to
1659  * @subdev: subdev handle to register
1660  * @probe: function to call when the rproc boots
1661  * @remove: function to call when the rproc shuts down
1662  */
1663 void rproc_add_subdev(struct rproc *rproc,
1664                       struct rproc_subdev *subdev,
1665                       int (*probe)(struct rproc_subdev *subdev),
1666                       void (*remove)(struct rproc_subdev *subdev, bool crashed))
1667 {
1668         subdev->probe = probe;
1669         subdev->remove = remove;
1670
1671         list_add_tail(&subdev->node, &rproc->subdevs);
1672 }
1673 EXPORT_SYMBOL(rproc_add_subdev);
1674
1675 /**
1676  * rproc_remove_subdev() - remove a subdevice from a remoteproc
1677  * @rproc: rproc handle to remove the subdevice from
1678  * @subdev: subdev handle, previously registered with rproc_add_subdev()
1679  */
1680 void rproc_remove_subdev(struct rproc *rproc, struct rproc_subdev *subdev)
1681 {
1682         list_del(&subdev->node);
1683 }
1684 EXPORT_SYMBOL(rproc_remove_subdev);
1685
1686 /**
1687  * rproc_get_by_child() - acquire rproc handle of @dev's ancestor
1688  * @dev:        child device to find ancestor of
1689  *
1690  * Returns the ancestor rproc instance, or NULL if not found.
1691  */
1692 struct rproc *rproc_get_by_child(struct device *dev)
1693 {
1694         for (dev = dev->parent; dev; dev = dev->parent) {
1695                 if (dev->type == &rproc_type)
1696                         return dev->driver_data;
1697         }
1698
1699         return NULL;
1700 }
1701 EXPORT_SYMBOL(rproc_get_by_child);
1702
1703 /**
1704  * rproc_report_crash() - rproc crash reporter function
1705  * @rproc: remote processor
1706  * @type: crash type
1707  *
1708  * This function must be called every time a crash is detected by the low-level
1709  * drivers implementing a specific remoteproc. This should not be called from a
1710  * non-remoteproc driver.
1711  *
1712  * This function can be called from atomic/interrupt context.
1713  */
1714 void rproc_report_crash(struct rproc *rproc, enum rproc_crash_type type)
1715 {
1716         if (!rproc) {
1717                 pr_err("NULL rproc pointer\n");
1718                 return;
1719         }
1720
1721         dev_err(&rproc->dev, "crash detected in %s: type %s\n",
1722                 rproc->name, rproc_crash_to_string(type));
1723
1724         /* create a new task to handle the error */
1725         schedule_work(&rproc->crash_handler);
1726 }
1727 EXPORT_SYMBOL(rproc_report_crash);
1728
1729 static int __init remoteproc_init(void)
1730 {
1731         rproc_init_sysfs();
1732         rproc_init_debugfs();
1733
1734         return 0;
1735 }
1736 module_init(remoteproc_init);
1737
1738 static void __exit remoteproc_exit(void)
1739 {
1740         ida_destroy(&rproc_dev_index);
1741
1742         rproc_exit_debugfs();
1743         rproc_exit_sysfs();
1744 }
1745 module_exit(remoteproc_exit);
1746
1747 MODULE_LICENSE("GPL v2");
1748 MODULE_DESCRIPTION("Generic Remote Processor Framework");