]> rtime.felk.cvut.cz Git - zynq/linux.git/blob - drivers/remoteproc/remoteproc_core.c
Merge tag 'v3.9' into master-next
[zynq/linux.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/remoteproc.h>
37 #include <linux/iommu.h>
38 #include <linux/idr.h>
39 #include <linux/elf.h>
40 #include <linux/virtio_ids.h>
41 #include <linux/virtio_ring.h>
42 #include <asm/byteorder.h>
43
44 #include "remoteproc_internal.h"
45
46 typedef int (*rproc_handle_resources_t)(struct rproc *rproc,
47                                 struct resource_table *table, int len);
48 typedef int (*rproc_handle_resource_t)(struct rproc *rproc, void *, int avail);
49
50 /* Unique indices for remoteproc devices */
51 static DEFINE_IDA(rproc_dev_index);
52
53 static const char * const rproc_crash_names[] = {
54         [RPROC_MMUFAULT]        = "mmufault",
55 };
56
57 /* translate rproc_crash_type to string */
58 static const char *rproc_crash_to_string(enum rproc_crash_type type)
59 {
60         if (type < ARRAY_SIZE(rproc_crash_names))
61                 return rproc_crash_names[type];
62         return "unkown";
63 }
64
65 /*
66  * This is the IOMMU fault handler we register with the IOMMU API
67  * (when relevant; not all remote processors access memory through
68  * an IOMMU).
69  *
70  * IOMMU core will invoke this handler whenever the remote processor
71  * will try to access an unmapped device address.
72  */
73 static int rproc_iommu_fault(struct iommu_domain *domain, struct device *dev,
74                 unsigned long iova, int flags, void *token)
75 {
76         struct rproc *rproc = token;
77
78         dev_err(dev, "iommu fault: da 0x%lx flags 0x%x\n", iova, flags);
79
80         rproc_report_crash(rproc, RPROC_MMUFAULT);
81
82         /*
83          * Let the iommu core know we're not really handling this fault;
84          * we just used it as a recovery trigger.
85          */
86         return -ENOSYS;
87 }
88
89 static int rproc_enable_iommu(struct rproc *rproc)
90 {
91         struct iommu_domain *domain;
92         struct device *dev = rproc->dev.parent;
93         int ret;
94
95         /*
96          * We currently use iommu_present() to decide if an IOMMU
97          * setup is needed.
98          *
99          * This works for simple cases, but will easily fail with
100          * platforms that do have an IOMMU, but not for this specific
101          * rproc.
102          *
103          * This will be easily solved by introducing hw capabilities
104          * that will be set by the remoteproc driver.
105          */
106         if (!iommu_present(dev->bus)) {
107                 dev_dbg(dev, "iommu not found\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
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         return;
146 }
147
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).
152  *
153  * They may then ask us to copy objects into specific device addresses (e.g.
154  * code/data sections) or expose us certain symbols in other device address
155  * (e.g. their trace buffer).
156  *
157  * This function is an internal helper with which we can go over the allocated
158  * carveouts and translate specific device address to kernel virtual addresses
159  * so we can access the referenced memory.
160  *
161  * Note: phys_to_virt(iommu_iova_to_phys(rproc->domain, da)) will work too,
162  * but only on kernel direct mapped RAM memory. Instead, we're just using
163  * here the output of the DMA API, which should be more correct.
164  */
165 void *rproc_da_to_va(struct rproc *rproc, u64 da, int len)
166 {
167         struct rproc_mem_entry *carveout;
168         void *ptr = NULL;
169
170         list_for_each_entry(carveout, &rproc->carveouts, node) {
171                 int offset = da - carveout->da;
172
173                 /* try next carveout if da is too small */
174                 if (offset < 0)
175                         continue;
176
177                 /* try next carveout if da is too large */
178                 /* FIXME this is breaking offset in carveout - microblaze */
179                 /* if (offset + len > carveout->len)
180                         continue; */
181
182                 ptr = carveout->va + offset;
183
184                 break;
185         }
186
187         return ptr;
188 }
189 EXPORT_SYMBOL(rproc_da_to_va);
190
191 int rproc_alloc_vring(struct rproc_vdev *rvdev, int i)
192 {
193         struct rproc *rproc = rvdev->rproc;
194         struct device *dev = &rproc->dev;
195         struct rproc_vring *rvring = &rvdev->vring[i];
196         dma_addr_t dma;
197         void *va;
198         int ret, size, notifyid;
199
200         /* actual size of vring (in bytes) */
201         size = PAGE_ALIGN(vring_size(rvring->len, rvring->align));
202
203         /*
204          * Allocate non-cacheable memory for the vring. In the future
205          * this call will also configure the IOMMU for us
206          * TODO: let the rproc know the da of this vring
207          */
208         va = dma_alloc_coherent(dev->parent, size, &dma, GFP_KERNEL);
209         if (!va) {
210                 dev_err(dev->parent, "dma_alloc_coherent failed\n");
211                 return -EINVAL;
212         }
213
214         /*
215          * Assign an rproc-wide unique index for this vring
216          * TODO: assign a notifyid for rvdev updates as well
217          * TODO: let the rproc know the notifyid of this vring
218          * TODO: support predefined notifyids (via resource table)
219          */
220         ret = idr_alloc(&rproc->notifyids, rvring, 0, 0, GFP_KERNEL);
221         if (ret < 0) {
222                 dev_err(dev, "idr_alloc failed: %d\n", ret);
223                 dma_free_coherent(dev->parent, size, va, dma);
224                 return ret;
225         }
226         notifyid = ret;
227
228         /* Store largest notifyid */
229         rproc->max_notifyid = max(rproc->max_notifyid, notifyid);
230
231         dev_dbg(dev, "vring%d: va %p dma %llx size %x idr %d\n", i, va,
232                                 (unsigned long long)dma, size, notifyid);
233
234         rvring->va = va;
235         rvring->dma = dma;
236         rvring->notifyid = notifyid;
237
238         return 0;
239 }
240
241 static int
242 rproc_parse_vring(struct rproc_vdev *rvdev, struct fw_rsc_vdev *rsc, int i)
243 {
244         struct rproc *rproc = rvdev->rproc;
245         struct device *dev = &rproc->dev;
246         struct fw_rsc_vdev_vring *vring = &rsc->vring[i];
247         struct rproc_vring *rvring = &rvdev->vring[i];
248
249         dev_dbg(dev, "vdev rsc: vring%d: da %x, qsz %d, align %d\n",
250                                 i, vring->da, vring->num, vring->align);
251
252         /* make sure reserved bytes are zeroes */
253         if (vring->reserved) {
254                 dev_err(dev, "vring rsc has non zero reserved bytes\n");
255                 return -EINVAL;
256         }
257
258         /* verify queue size and vring alignment are sane */
259         if (!vring->num || !vring->align) {
260                 dev_err(dev, "invalid qsz (%d) or alignment (%d)\n",
261                                                 vring->num, vring->align);
262                 return -EINVAL;
263         }
264
265         rvring->len = vring->num;
266         rvring->align = vring->align;
267         rvring->rvdev = rvdev;
268
269         return 0;
270 }
271
272 static int rproc_max_notifyid(int id, void *p, void *data)
273 {
274         int *maxid = data;
275         *maxid = max(*maxid, id);
276         return 0;
277 }
278
279 void rproc_free_vring(struct rproc_vring *rvring)
280 {
281         int size = PAGE_ALIGN(vring_size(rvring->len, rvring->align));
282         struct rproc *rproc = rvring->rvdev->rproc;
283         int maxid = 0;
284
285         dma_free_coherent(rproc->dev.parent, size, rvring->va, rvring->dma);
286         idr_remove(&rproc->notifyids, rvring->notifyid);
287
288         /* Find the largest remaining notifyid */
289         idr_for_each(&rproc->notifyids, rproc_max_notifyid, &maxid);
290         rproc->max_notifyid = maxid;
291 }
292
293 /**
294  * rproc_handle_vdev() - handle a vdev fw resource
295  * @rproc: the remote processor
296  * @rsc: the vring resource descriptor
297  * @avail: size of available data (for sanity checking the image)
298  *
299  * This resource entry requests the host to statically register a virtio
300  * device (vdev), and setup everything needed to support it. It contains
301  * everything needed to make it possible: the virtio device id, virtio
302  * device features, vrings information, virtio config space, etc...
303  *
304  * Before registering the vdev, the vrings are allocated from non-cacheable
305  * physically contiguous memory. Currently we only support two vrings per
306  * remote processor (temporary limitation). We might also want to consider
307  * doing the vring allocation only later when ->find_vqs() is invoked, and
308  * then release them upon ->del_vqs().
309  *
310  * Note: @da is currently not really handled correctly: we dynamically
311  * allocate it using the DMA API, ignoring requested hard coded addresses,
312  * and we don't take care of any required IOMMU programming. This is all
313  * going to be taken care of when the generic iommu-based DMA API will be
314  * merged. Meanwhile, statically-addressed iommu-based firmware images should
315  * use RSC_DEVMEM resource entries to map their required @da to the physical
316  * address of their base CMA region (ouch, hacky!).
317  *
318  * Returns 0 on success, or an appropriate error code otherwise
319  */
320 static int rproc_handle_vdev(struct rproc *rproc, struct fw_rsc_vdev *rsc,
321                                                                 int avail)
322 {
323         struct device *dev = &rproc->dev;
324         struct rproc_vdev *rvdev;
325         int i, ret;
326
327         /* make sure resource isn't truncated */
328         if (sizeof(*rsc) + rsc->num_of_vrings * sizeof(struct fw_rsc_vdev_vring)
329                         + rsc->config_len > avail) {
330                 dev_err(dev, "vdev rsc is truncated\n");
331                 return -EINVAL;
332         }
333
334         /* make sure reserved bytes are zeroes */
335         if (rsc->reserved[0] || rsc->reserved[1]) {
336                 dev_err(dev, "vdev rsc has non zero reserved bytes\n");
337                 return -EINVAL;
338         }
339
340         dev_dbg(dev, "vdev rsc: id %d, dfeatures %x, cfg len %d, %d vrings\n",
341                 rsc->id, rsc->dfeatures, rsc->config_len, rsc->num_of_vrings);
342
343         /* we currently support only two vrings per rvdev */
344         if (rsc->num_of_vrings > ARRAY_SIZE(rvdev->vring)) {
345                 dev_err(dev, "too many vrings: %d\n", rsc->num_of_vrings);
346                 return -EINVAL;
347         }
348
349         rvdev = kzalloc(sizeof(struct rproc_vdev), GFP_KERNEL);
350         if (!rvdev)
351                 return -ENOMEM;
352
353         rvdev->rproc = rproc;
354
355         /* parse the vrings */
356         for (i = 0; i < rsc->num_of_vrings; i++) {
357                 ret = rproc_parse_vring(rvdev, rsc, i);
358                 if (ret)
359                         goto free_rvdev;
360         }
361
362         /* remember the device features */
363         rvdev->dfeatures = rsc->dfeatures;
364
365         list_add_tail(&rvdev->node, &rproc->rvdevs);
366
367         /* it is now safe to add the virtio device */
368         ret = rproc_add_virtio_dev(rvdev, rsc->id);
369         if (ret)
370                 goto remove_rvdev;
371
372         return 0;
373
374 remove_rvdev:
375         list_del(&rvdev->node);
376 free_rvdev:
377         kfree(rvdev);
378         return ret;
379 }
380
381 /**
382  * rproc_handle_trace() - handle a shared trace buffer resource
383  * @rproc: the remote processor
384  * @rsc: the trace resource descriptor
385  * @avail: size of available data (for sanity checking the image)
386  *
387  * In case the remote processor dumps trace logs into memory,
388  * export it via debugfs.
389  *
390  * Currently, the 'da' member of @rsc should contain the device address
391  * where the remote processor is dumping the traces. Later we could also
392  * support dynamically allocating this address using the generic
393  * DMA API (but currently there isn't a use case for that).
394  *
395  * Returns 0 on success, or an appropriate error code otherwise
396  */
397 static int rproc_handle_trace(struct rproc *rproc, struct fw_rsc_trace *rsc,
398                                                                 int avail)
399 {
400         struct rproc_mem_entry *trace;
401         struct device *dev = &rproc->dev;
402         void *ptr;
403         char name[15];
404
405         if (sizeof(*rsc) > avail) {
406                 dev_err(dev, "trace rsc is truncated\n");
407                 return -EINVAL;
408         }
409
410         /* make sure reserved bytes are zeroes */
411         if (rsc->reserved) {
412                 dev_err(dev, "trace rsc has non zero reserved bytes\n");
413                 return -EINVAL;
414         }
415
416         /* what's the kernel address of this resource ? */
417         ptr = rproc_da_to_va(rproc, rsc->da, rsc->len);
418         if (!ptr) {
419                 dev_err(dev, "erroneous trace resource entry\n");
420                 return -EINVAL;
421         }
422
423         trace = kzalloc(sizeof(*trace), GFP_KERNEL);
424         if (!trace) {
425                 dev_err(dev, "kzalloc trace failed\n");
426                 return -ENOMEM;
427         }
428
429         /* set the trace buffer dma properties */
430         trace->len = rsc->len;
431         trace->va = ptr;
432
433         /* make sure snprintf always null terminates, even if truncating */
434         snprintf(name, sizeof(name), "trace%d", rproc->num_traces);
435
436         /* create the debugfs entry */
437         trace->priv = rproc_create_trace_file(name, rproc, trace);
438         if (!trace->priv) {
439                 trace->va = NULL;
440                 kfree(trace);
441                 return -EINVAL;
442         }
443
444         list_add_tail(&trace->node, &rproc->traces);
445
446         rproc->num_traces++;
447
448         dev_dbg(dev, "%s added: va %p, da 0x%x, len 0x%x\n", name, ptr,
449                                                 rsc->da, rsc->len);
450
451         return 0;
452 }
453
454 /**
455  * rproc_handle_devmem() - handle devmem resource entry
456  * @rproc: remote processor handle
457  * @rsc: the devmem resource entry
458  * @avail: size of available data (for sanity checking the image)
459  *
460  * Remote processors commonly need to access certain on-chip peripherals.
461  *
462  * Some of these remote processors access memory via an iommu device,
463  * and might require us to configure their iommu before they can access
464  * the on-chip peripherals they need.
465  *
466  * This resource entry is a request to map such a peripheral device.
467  *
468  * These devmem entries will contain the physical address of the device in
469  * the 'pa' member. If a specific device address is expected, then 'da' will
470  * contain it (currently this is the only use case supported). 'len' will
471  * contain the size of the physical region we need to map.
472  *
473  * Currently we just "trust" those devmem entries to contain valid physical
474  * addresses, but this is going to change: we want the implementations to
475  * tell us ranges of physical addresses the firmware is allowed to request,
476  * and not allow firmwares to request access to physical addresses that
477  * are outside those ranges.
478  */
479 static int rproc_handle_devmem(struct rproc *rproc, struct fw_rsc_devmem *rsc,
480                                                                 int avail)
481 {
482         struct rproc_mem_entry *mapping;
483         struct device *dev = &rproc->dev;
484         int ret;
485
486         /* no point in handling this resource without a valid iommu domain */
487         if (!rproc->domain)
488                 return -EINVAL;
489
490         if (sizeof(*rsc) > avail) {
491                 dev_err(dev, "devmem rsc is truncated\n");
492                 return -EINVAL;
493         }
494
495         /* make sure reserved bytes are zeroes */
496         if (rsc->reserved) {
497                 dev_err(dev, "devmem rsc has non zero reserved bytes\n");
498                 return -EINVAL;
499         }
500
501         mapping = kzalloc(sizeof(*mapping), GFP_KERNEL);
502         if (!mapping) {
503                 dev_err(dev, "kzalloc mapping failed\n");
504                 return -ENOMEM;
505         }
506
507         ret = iommu_map(rproc->domain, rsc->da, rsc->pa, rsc->len, rsc->flags);
508         if (ret) {
509                 dev_err(dev, "failed to map devmem: %d\n", ret);
510                 goto out;
511         }
512
513         /*
514          * We'll need this info later when we'll want to unmap everything
515          * (e.g. on shutdown).
516          *
517          * We can't trust the remote processor not to change the resource
518          * table, so we must maintain this info independently.
519          */
520         mapping->da = rsc->da;
521         mapping->len = rsc->len;
522         list_add_tail(&mapping->node, &rproc->mappings);
523
524         dev_dbg(dev, "mapped devmem pa 0x%x, da 0x%x, len 0x%x\n",
525                                         rsc->pa, rsc->da, rsc->len);
526
527         return 0;
528
529 out:
530         kfree(mapping);
531         return ret;
532 }
533
534 /**
535  * rproc_handle_carveout() - handle phys contig memory allocation requests
536  * @rproc: rproc handle
537  * @rsc: the resource entry
538  * @avail: size of available data (for image validation)
539  *
540  * This function will handle firmware requests for allocation of physically
541  * contiguous memory regions.
542  *
543  * These request entries should come first in the firmware's resource table,
544  * as other firmware entries might request placing other data objects inside
545  * these memory regions (e.g. data/code segments, trace resource entries, ...).
546  *
547  * Allocating memory this way helps utilizing the reserved physical memory
548  * (e.g. CMA) more efficiently, and also minimizes the number of TLB entries
549  * needed to map it (in case @rproc is using an IOMMU). Reducing the TLB
550  * pressure is important; it may have a substantial impact on performance.
551  */
552 static int rproc_handle_carveout(struct rproc *rproc,
553                                 struct fw_rsc_carveout *rsc, int avail)
554 {
555         struct rproc_mem_entry *carveout, *mapping;
556         struct device *dev = &rproc->dev;
557         dma_addr_t dma;
558         void *va;
559         int ret;
560
561         if (sizeof(*rsc) > avail) {
562                 dev_err(dev, "carveout rsc is truncated\n");
563                 return -EINVAL;
564         }
565
566         /* make sure reserved bytes are zeroes */
567         if (rsc->reserved) {
568                 dev_err(dev, "carveout rsc has non zero reserved bytes\n");
569                 return -EINVAL;
570         }
571
572         dev_dbg(dev, "carveout rsc: da %x, pa %x, len %x, flags %x\n",
573                         rsc->da, rsc->pa, rsc->len, rsc->flags);
574
575         carveout = kzalloc(sizeof(*carveout), GFP_KERNEL);
576         if (!carveout) {
577                 dev_err(dev, "kzalloc carveout failed\n");
578                 return -ENOMEM;
579         }
580
581         va = dma_alloc_coherent(dev->parent, rsc->len, &dma, GFP_KERNEL);
582         if (!va) {
583                 dev_err(dev->parent, "dma_alloc_coherent err: %d\n", rsc->len);
584                 ret = -ENOMEM;
585                 goto free_carv;
586         }
587
588         dev_dbg(dev, "carveout va %p, dma %llx, len 0x%x\n", va,
589                                         (unsigned long long)dma, rsc->len);
590
591         /*
592          * Ok, this is non-standard.
593          *
594          * Sometimes we can't rely on the generic iommu-based DMA API
595          * to dynamically allocate the device address and then set the IOMMU
596          * tables accordingly, because some remote processors might
597          * _require_ us to use hard coded device addresses that their
598          * firmware was compiled with.
599          *
600          * In this case, we must use the IOMMU API directly and map
601          * the memory to the device address as expected by the remote
602          * processor.
603          *
604          * Obviously such remote processor devices should not be configured
605          * to use the iommu-based DMA API: we expect 'dma' to contain the
606          * physical address in this case.
607          */
608         if (rproc->domain) {
609                 mapping = kzalloc(sizeof(*mapping), GFP_KERNEL);
610                 if (!mapping) {
611                         dev_err(dev, "kzalloc mapping failed\n");
612                         ret = -ENOMEM;
613                         goto dma_free;
614                 }
615
616                 ret = iommu_map(rproc->domain, rsc->da, dma, rsc->len,
617                                                                 rsc->flags);
618                 if (ret) {
619                         dev_err(dev, "iommu_map failed: %d\n", ret);
620                         goto free_mapping;
621                 }
622
623                 /*
624                  * We'll need this info later when we'll want to unmap
625                  * everything (e.g. on shutdown).
626                  *
627                  * We can't trust the remote processor not to change the
628                  * resource table, so we must maintain this info independently.
629                  */
630                 mapping->da = rsc->da;
631                 mapping->len = rsc->len;
632                 list_add_tail(&mapping->node, &rproc->mappings);
633
634                 dev_dbg(dev, "carveout mapped 0x%x to 0x%llx\n",
635                                         rsc->da, (unsigned long long)dma);
636         }
637
638         /*
639          * Some remote processors might need to know the pa
640          * even though they are behind an IOMMU. E.g., OMAP4's
641          * remote M3 processor needs this so it can control
642          * on-chip hardware accelerators that are not behind
643          * the IOMMU, and therefor must know the pa.
644          *
645          * Generally we don't want to expose physical addresses
646          * if we don't have to (remote processors are generally
647          * _not_ trusted), so we might want to do this only for
648          * remote processor that _must_ have this (e.g. OMAP4's
649          * dual M3 subsystem).
650          *
651          * Non-IOMMU processors might also want to have this info.
652          * In this case, the device address and the physical address
653          * are the same.
654          */
655         rsc->pa = dma;
656
657         carveout->va = va;
658         carveout->len = rsc->len;
659         carveout->dma = dma;
660         carveout->da = rsc->da;
661
662         list_add_tail(&carveout->node, &rproc->carveouts);
663
664         return 0;
665
666 free_mapping:
667         kfree(mapping);
668 dma_free:
669         dma_free_coherent(dev->parent, rsc->len, va, dma);
670 free_carv:
671         kfree(carveout);
672         return ret;
673 }
674
675 /*
676  * A lookup table for resource handlers. The indices are defined in
677  * enum fw_resource_type.
678  */
679 static rproc_handle_resource_t rproc_handle_rsc[] = {
680         [RSC_CARVEOUT] = NULL,
681         [RSC_DEVMEM] = (rproc_handle_resource_t)rproc_handle_devmem,
682         [RSC_TRACE] = (rproc_handle_resource_t)rproc_handle_trace,
683         [RSC_VDEV] = NULL, /* VDEVs were handled upon registrarion */
684         [RSC_MMU] = NULL, /* For firmware purpose */
685 };
686
687 /* handle firmware resource entries before booting the remote processor */
688 static int
689 rproc_handle_boot_rsc(struct rproc *rproc, struct resource_table *table, int len)
690 {
691         struct device *dev = &rproc->dev;
692         rproc_handle_resource_t handler;
693         int ret = 0, i;
694
695         for (i = 0; i < table->num; i++) {
696                 int offset = table->offset[i];
697                 struct fw_rsc_hdr *hdr = (void *)table + offset;
698                 int avail = len - offset - sizeof(*hdr);
699                 void *rsc = (void *)hdr + sizeof(*hdr);
700
701                 /* make sure table isn't truncated */
702                 if (avail < 0) {
703                         dev_err(dev, "rsc table is truncated\n");
704                         return -EINVAL;
705                 }
706
707                 dev_dbg(dev, "rsc: type %d\n", hdr->type);
708
709                 if (hdr->type >= RSC_LAST) {
710                         dev_warn(dev, "unsupported resource %d\n", hdr->type);
711                         continue;
712                 }
713
714                 handler = rproc_handle_rsc[hdr->type];
715                 if (!handler)
716                         continue;
717
718                 ret = handler(rproc, rsc, avail);
719                 if (ret)
720                         break;
721         }
722
723         return ret;
724 }
725
726 /* handle carveout firmware resource entries while registering the remote processor */
727 static int
728 rproc_handle_carveout_rsc(struct rproc *rproc, struct resource_table *table, int len)
729 {
730         struct device *dev = &rproc->dev;
731         int ret = 0, i;
732
733         for (i = 0; i < table->num; i++) {
734                 int offset = table->offset[i];
735                 struct fw_rsc_hdr *hdr = (void *)table + offset;
736                 int avail = len - offset - sizeof(*hdr);
737                 struct fw_rsc_carveout *crsc;
738
739                 /* make sure table isn't truncated */
740                 if (avail < 0) {
741                         dev_err(dev, "rsc table is truncated\n");
742                         return -EINVAL;
743                 }
744
745                 dev_dbg(dev, "%s: rsc type %d\n", __func__, hdr->type);
746
747                 if (hdr->type != RSC_CARVEOUT)
748                         continue;
749
750                 crsc = (struct fw_rsc_carveout *)hdr->data;
751
752                 ret = rproc_handle_carveout(rproc, crsc, avail);
753                 if (ret)
754                         break;
755         }
756
757         return ret;
758 }
759
760 /* handle firmware resource entries while registering the remote processor */
761 static int
762 rproc_handle_virtio_rsc(struct rproc *rproc, struct resource_table *table, int len)
763 {
764         struct device *dev = &rproc->dev;
765         int ret = 0, i;
766
767         for (i = 0; i < table->num; i++) {
768                 int offset = table->offset[i];
769                 struct fw_rsc_hdr *hdr = (void *)table + offset;
770                 int avail = len - offset - sizeof(*hdr);
771                 struct fw_rsc_vdev *vrsc;
772
773                 /* make sure table isn't truncated */
774                 if (avail < 0) {
775                         dev_err(dev, "rsc table is truncated\n");
776                         return -EINVAL;
777                 }
778
779                 dev_dbg(dev, "%s: rsc type %d\n", __func__, hdr->type);
780
781                 if (hdr->type != RSC_VDEV)
782                         continue;
783
784                 vrsc = (struct fw_rsc_vdev *)hdr->data;
785
786                 ret = rproc_handle_vdev(rproc, vrsc, avail);
787                 if (ret)
788                         break;
789         }
790
791         return ret;
792 }
793
794 /**
795  * rproc_resource_cleanup() - clean up and free all acquired resources
796  * @rproc: rproc handle
797  *
798  * This function will free all resources acquired for @rproc, and it
799  * is called whenever @rproc either shuts down or fails to boot.
800  */
801 static void rproc_resource_cleanup(struct rproc *rproc)
802 {
803         struct rproc_mem_entry *entry, *tmp;
804         struct device *dev = &rproc->dev;
805
806         /* clean up debugfs trace entries */
807         list_for_each_entry_safe(entry, tmp, &rproc->traces, node) {
808                 rproc_remove_trace_file(entry->priv);
809                 rproc->num_traces--;
810                 list_del(&entry->node);
811                 kfree(entry);
812         }
813
814         /* clean up carveout allocations */
815         list_for_each_entry_safe(entry, tmp, &rproc->carveouts, node) {
816                 dma_free_coherent(dev->parent, entry->len, entry->va, entry->dma);
817                 list_del(&entry->node);
818                 kfree(entry);
819         }
820
821         /* clean up iommu mapping entries */
822         list_for_each_entry_safe(entry, tmp, &rproc->mappings, node) {
823                 size_t unmapped;
824
825                 unmapped = iommu_unmap(rproc->domain, entry->da, entry->len);
826                 if (unmapped != entry->len) {
827                         /* nothing much to do besides complaining */
828                         dev_err(dev, "failed to unmap %u/%zu\n", entry->len,
829                                                                 unmapped);
830                 }
831
832                 list_del(&entry->node);
833                 kfree(entry);
834         }
835 }
836
837 /*
838  * take a firmware and boot a remote processor with it.
839  */
840 static int rproc_fw_boot(struct rproc *rproc, const struct firmware *fw)
841 {
842         struct device *dev = &rproc->dev;
843         const char *name = rproc->firmware;
844         struct resource_table *table;
845         int ret, tablesz;
846
847         ret = rproc_fw_sanity_check(rproc, fw);
848         if (ret)
849                 return ret;
850
851         dev_info(dev, "Booting fw image %s, size %zd\n", name, fw->size);
852
853         /*
854          * if enabling an IOMMU isn't relevant for this rproc, this is
855          * just a nop
856          */
857         ret = rproc_enable_iommu(rproc);
858         if (ret) {
859                 dev_err(dev, "can't enable iommu: %d\n", ret);
860                 return ret;
861         }
862
863         rproc->bootaddr = rproc_get_boot_addr(rproc, fw);
864
865         /* look for the resource table */
866         table = rproc_find_rsc_table(rproc, fw, &tablesz);
867         if (!table) {
868                 ret = -EINVAL;
869                 goto clean_up;
870         }
871
872         /* handle fw resources which are required to boot rproc */
873         ret = rproc_handle_boot_rsc(rproc, table, tablesz);
874         if (ret) {
875                 dev_err(dev, "Failed to process resources: %d\n", ret);
876                 goto clean_up;
877         }
878
879         /* load the ELF segments to memory */
880         ret = rproc_load_segments(rproc, fw);
881         if (ret) {
882                 dev_err(dev, "Failed to load program segments: %d\n", ret);
883                 goto clean_up;
884         }
885
886         /* power up the remote processor */
887         ret = rproc->ops->start(rproc);
888         if (ret) {
889                 dev_err(dev, "can't start rproc %s: %d\n", rproc->name, ret);
890                 goto clean_up;
891         }
892
893         rproc->state = RPROC_RUNNING;
894
895         dev_info(dev, "remote processor %s is now up\n", rproc->name);
896
897         return 0;
898
899 clean_up:
900         rproc_resource_cleanup(rproc);
901         rproc_disable_iommu(rproc);
902         return ret;
903 }
904
905 /*
906  * take a firmware and look for virtio devices to register.
907  *
908  * Note: this function is called asynchronously upon registration of the
909  * remote processor (so we must wait until it completes before we try
910  * to unregister the device. one other option is just to use kref here,
911  * that might be cleaner).
912  */
913 static void rproc_fw_config_virtio(const struct firmware *fw, void *context)
914 {
915         struct rproc *rproc = context;
916         struct resource_table *table;
917         int ret, tablesz;
918
919         if (rproc_fw_sanity_check(rproc, fw) < 0)
920                 goto out;
921
922         /* look for the resource table */
923         table = rproc_find_rsc_table(rproc, fw,  &tablesz);
924         if (!table)
925                 goto out;
926
927         /* look for carveout areas and register them first */
928         ret = rproc_handle_carveout_rsc(rproc, table, tablesz);
929         if (ret)
930                 goto out;
931
932         /* look for virtio devices and register them */
933         ret = rproc_handle_virtio_rsc(rproc, table, tablesz);
934         if (ret)
935                 goto out;
936
937 out:
938         release_firmware(fw);
939         /* allow rproc_del() contexts, if any, to proceed */
940         complete_all(&rproc->firmware_loading_complete);
941 }
942
943 static int rproc_add_virtio_devices(struct rproc *rproc)
944 {
945         int ret;
946
947         /* rproc_del() calls must wait until async loader completes */
948         init_completion(&rproc->firmware_loading_complete);
949
950         /*
951          * We must retrieve early virtio configuration info from
952          * the firmware (e.g. whether to register a virtio device,
953          * what virtio features does it support, ...).
954          *
955          * We're initiating an asynchronous firmware loading, so we can
956          * be built-in kernel code, without hanging the boot process.
957          */
958         ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_HOTPLUG,
959                                       rproc->firmware, &rproc->dev, GFP_KERNEL,
960                                       rproc, rproc_fw_config_virtio);
961         if (ret < 0) {
962                 dev_err(&rproc->dev, "request_firmware_nowait err: %d\n", ret);
963                 complete_all(&rproc->firmware_loading_complete);
964         }
965
966         return ret;
967 }
968
969 /**
970  * rproc_trigger_recovery() - recover a remoteproc
971  * @rproc: the remote processor
972  *
973  * The recovery is done by reseting all the virtio devices, that way all the
974  * rpmsg drivers will be reseted along with the remote processor making the
975  * remoteproc functional again.
976  *
977  * This function can sleep, so it cannot be called from atomic context.
978  */
979 int rproc_trigger_recovery(struct rproc *rproc)
980 {
981         struct rproc_vdev *rvdev, *rvtmp;
982
983         dev_err(&rproc->dev, "recovering %s\n", rproc->name);
984
985         init_completion(&rproc->crash_comp);
986
987         /* clean up remote vdev entries */
988         list_for_each_entry_safe(rvdev, rvtmp, &rproc->rvdevs, node)
989                 rproc_remove_virtio_dev(rvdev);
990
991         /* wait until there is no more rproc users */
992         wait_for_completion(&rproc->crash_comp);
993
994         return rproc_add_virtio_devices(rproc);
995 }
996
997 /**
998  * rproc_crash_handler_work() - handle a crash
999  *
1000  * This function needs to handle everything related to a crash, like cpu
1001  * registers and stack dump, information to help to debug the fatal error, etc.
1002  */
1003 static void rproc_crash_handler_work(struct work_struct *work)
1004 {
1005         struct rproc *rproc = container_of(work, struct rproc, crash_handler);
1006         struct device *dev = &rproc->dev;
1007
1008         dev_dbg(dev, "enter %s\n", __func__);
1009
1010         mutex_lock(&rproc->lock);
1011
1012         if (rproc->state == RPROC_CRASHED || rproc->state == RPROC_OFFLINE) {
1013                 /* handle only the first crash detected */
1014                 mutex_unlock(&rproc->lock);
1015                 return;
1016         }
1017
1018         rproc->state = RPROC_CRASHED;
1019         dev_err(dev, "handling crash #%u in %s\n", ++rproc->crash_cnt,
1020                 rproc->name);
1021
1022         mutex_unlock(&rproc->lock);
1023
1024         if (!rproc->recovery_disabled)
1025                 rproc_trigger_recovery(rproc);
1026 }
1027
1028 /**
1029  * rproc_boot() - boot a remote processor
1030  * @rproc: handle of a remote processor
1031  *
1032  * Boot a remote processor (i.e. load its firmware, power it on, ...).
1033  *
1034  * If the remote processor is already powered on, this function immediately
1035  * returns (successfully).
1036  *
1037  * Returns 0 on success, and an appropriate error value otherwise.
1038  */
1039 int rproc_boot(struct rproc *rproc)
1040 {
1041         const struct firmware *firmware_p;
1042         struct device *dev;
1043         int ret;
1044
1045         if (!rproc) {
1046                 pr_err("invalid rproc handle\n");
1047                 return -EINVAL;
1048         }
1049
1050         dev = &rproc->dev;
1051
1052         ret = mutex_lock_interruptible(&rproc->lock);
1053         if (ret) {
1054                 dev_err(dev, "can't lock rproc %s: %d\n", rproc->name, ret);
1055                 return ret;
1056         }
1057
1058         /* loading a firmware is required */
1059         if (!rproc->firmware) {
1060                 dev_err(dev, "%s: no firmware to load\n", __func__);
1061                 ret = -EINVAL;
1062                 goto unlock_mutex;
1063         }
1064
1065         /* prevent underlying implementation from being removed */
1066         if (!try_module_get(dev->parent->driver->owner)) {
1067                 dev_err(dev, "%s: can't get owner\n", __func__);
1068                 ret = -EINVAL;
1069                 goto unlock_mutex;
1070         }
1071
1072         /* skip the boot process if rproc is already powered up */
1073         if (atomic_inc_return(&rproc->power) > 1) {
1074                 ret = 0;
1075                 goto unlock_mutex;
1076         }
1077
1078         dev_info(dev, "powering up %s\n", rproc->name);
1079
1080         /* load firmware */
1081         ret = request_firmware(&firmware_p, rproc->firmware, dev);
1082         if (ret < 0) {
1083                 dev_err(dev, "request_firmware failed: %d\n", ret);
1084                 goto downref_rproc;
1085         }
1086
1087         ret = rproc_fw_boot(rproc, firmware_p);
1088
1089         release_firmware(firmware_p);
1090
1091 downref_rproc:
1092         if (ret) {
1093                 module_put(dev->parent->driver->owner);
1094                 atomic_dec(&rproc->power);
1095         }
1096 unlock_mutex:
1097         mutex_unlock(&rproc->lock);
1098         return ret;
1099 }
1100 EXPORT_SYMBOL(rproc_boot);
1101
1102 /**
1103  * rproc_shutdown() - power off the remote processor
1104  * @rproc: the remote processor
1105  *
1106  * Power off a remote processor (previously booted with rproc_boot()).
1107  *
1108  * In case @rproc is still being used by an additional user(s), then
1109  * this function will just decrement the power refcount and exit,
1110  * without really powering off the device.
1111  *
1112  * Every call to rproc_boot() must (eventually) be accompanied by a call
1113  * to rproc_shutdown(). Calling rproc_shutdown() redundantly is a bug.
1114  *
1115  * Notes:
1116  * - we're not decrementing the rproc's refcount, only the power refcount.
1117  *   which means that the @rproc handle stays valid even after rproc_shutdown()
1118  *   returns, and users can still use it with a subsequent rproc_boot(), if
1119  *   needed.
1120  */
1121 void rproc_shutdown(struct rproc *rproc)
1122 {
1123         struct device *dev = &rproc->dev;
1124         int ret;
1125
1126         ret = mutex_lock_interruptible(&rproc->lock);
1127         if (ret) {
1128                 dev_err(dev, "can't lock rproc %s: %d\n", rproc->name, ret);
1129                 return;
1130         }
1131
1132         /* if the remote proc is still needed, bail out */
1133         if (!atomic_dec_and_test(&rproc->power))
1134                 goto out;
1135
1136         /* power off the remote processor */
1137         ret = rproc->ops->stop(rproc);
1138         if (ret) {
1139                 atomic_inc(&rproc->power);
1140                 dev_err(dev, "can't stop rproc: %d\n", ret);
1141                 goto out;
1142         }
1143
1144         /* clean up all acquired resources */
1145         rproc_resource_cleanup(rproc);
1146
1147         rproc_disable_iommu(rproc);
1148
1149         /* if in crash state, unlock crash handler */
1150         if (rproc->state == RPROC_CRASHED)
1151                 complete_all(&rproc->crash_comp);
1152
1153         rproc->state = RPROC_OFFLINE;
1154
1155         dev_info(dev, "stopped remote processor %s\n", rproc->name);
1156
1157 out:
1158         mutex_unlock(&rproc->lock);
1159         if (!ret)
1160                 module_put(dev->parent->driver->owner);
1161 }
1162 EXPORT_SYMBOL(rproc_shutdown);
1163
1164 /**
1165  * rproc_add() - register a remote processor
1166  * @rproc: the remote processor handle to register
1167  *
1168  * Registers @rproc with the remoteproc framework, after it has been
1169  * allocated with rproc_alloc().
1170  *
1171  * This is called by the platform-specific rproc implementation, whenever
1172  * a new remote processor device is probed.
1173  *
1174  * Returns 0 on success and an appropriate error code otherwise.
1175  *
1176  * Note: this function initiates an asynchronous firmware loading
1177  * context, which will look for virtio devices supported by the rproc's
1178  * firmware.
1179  *
1180  * If found, those virtio devices will be created and added, so as a result
1181  * of registering this remote processor, additional virtio drivers might be
1182  * probed.
1183  */
1184 int rproc_add(struct rproc *rproc)
1185 {
1186         struct device *dev = &rproc->dev;
1187         int ret;
1188
1189         ret = device_add(dev);
1190         if (ret < 0)
1191                 return ret;
1192
1193         dev_info(dev, "%s is available\n", rproc->name);
1194
1195         dev_info(dev, "Note: remoteproc is still under development and considered experimental.\n");
1196         dev_info(dev, "THE BINARY FORMAT IS NOT YET FINALIZED, and backward compatibility isn't yet guaranteed.\n");
1197
1198         /* create debugfs entries */
1199         rproc_create_debug_dir(rproc);
1200
1201         return rproc_add_virtio_devices(rproc);
1202 }
1203 EXPORT_SYMBOL(rproc_add);
1204
1205 /**
1206  * rproc_type_release() - release a remote processor instance
1207  * @dev: the rproc's device
1208  *
1209  * This function should _never_ be called directly.
1210  *
1211  * It will be called by the driver core when no one holds a valid pointer
1212  * to @dev anymore.
1213  */
1214 static void rproc_type_release(struct device *dev)
1215 {
1216         struct rproc *rproc = container_of(dev, struct rproc, dev);
1217
1218         dev_info(&rproc->dev, "releasing %s\n", rproc->name);
1219
1220         rproc_delete_debug_dir(rproc);
1221
1222         idr_destroy(&rproc->notifyids);
1223
1224         if (rproc->index >= 0)
1225                 ida_simple_remove(&rproc_dev_index, rproc->index);
1226
1227         kfree(rproc);
1228 }
1229
1230 static struct device_type rproc_type = {
1231         .name           = "remoteproc",
1232         .release        = rproc_type_release,
1233 };
1234
1235 /**
1236  * rproc_alloc() - allocate a remote processor handle
1237  * @dev: the underlying device
1238  * @name: name of this remote processor
1239  * @ops: platform-specific handlers (mainly start/stop)
1240  * @firmware: name of firmware file to load
1241  * @len: length of private data needed by the rproc driver (in bytes)
1242  *
1243  * Allocates a new remote processor handle, but does not register
1244  * it yet.
1245  *
1246  * This function should be used by rproc implementations during initialization
1247  * of the remote processor.
1248  *
1249  * After creating an rproc handle using this function, and when ready,
1250  * implementations should then call rproc_add() to complete
1251  * the registration of the remote processor.
1252  *
1253  * On success the new rproc is returned, and on failure, NULL.
1254  *
1255  * Note: _never_ directly deallocate @rproc, even if it was not registered
1256  * yet. Instead, when you need to unroll rproc_alloc(), use rproc_put().
1257  */
1258 struct rproc *rproc_alloc(struct device *dev, const char *name,
1259                                 const struct rproc_ops *ops,
1260                                 const char *firmware, int len)
1261 {
1262         struct rproc *rproc;
1263
1264         if (!dev || !name || !ops)
1265                 return NULL;
1266
1267         rproc = kzalloc(sizeof(struct rproc) + len, GFP_KERNEL);
1268         if (!rproc) {
1269                 dev_err(dev, "%s: kzalloc failed\n", __func__);
1270                 return NULL;
1271         }
1272
1273         rproc->name = name;
1274         rproc->ops = ops;
1275         rproc->firmware = firmware;
1276         rproc->priv = &rproc[1];
1277
1278         device_initialize(&rproc->dev);
1279         rproc->dev.parent = dev;
1280         rproc->dev.type = &rproc_type;
1281
1282         /* Assign a unique device index and name */
1283         rproc->index = ida_simple_get(&rproc_dev_index, 0, 0, GFP_KERNEL);
1284         if (rproc->index < 0) {
1285                 dev_err(dev, "ida_simple_get failed: %d\n", rproc->index);
1286                 put_device(&rproc->dev);
1287                 return NULL;
1288         }
1289
1290         dev_set_name(&rproc->dev, "remoteproc%d", rproc->index);
1291
1292         atomic_set(&rproc->power, 0);
1293
1294         /* Set ELF as the default fw_ops handler */
1295         rproc->fw_ops = &rproc_elf_fw_ops;
1296
1297         mutex_init(&rproc->lock);
1298
1299         idr_init(&rproc->notifyids);
1300
1301         INIT_LIST_HEAD(&rproc->carveouts);
1302         INIT_LIST_HEAD(&rproc->mappings);
1303         INIT_LIST_HEAD(&rproc->traces);
1304         INIT_LIST_HEAD(&rproc->rvdevs);
1305
1306         INIT_WORK(&rproc->crash_handler, rproc_crash_handler_work);
1307         init_completion(&rproc->crash_comp);
1308
1309         rproc->state = RPROC_OFFLINE;
1310
1311         return rproc;
1312 }
1313 EXPORT_SYMBOL(rproc_alloc);
1314
1315 /**
1316  * rproc_put() - unroll rproc_alloc()
1317  * @rproc: the remote processor handle
1318  *
1319  * This function decrements the rproc dev refcount.
1320  *
1321  * If no one holds any reference to rproc anymore, then its refcount would
1322  * now drop to zero, and it would be freed.
1323  */
1324 void rproc_put(struct rproc *rproc)
1325 {
1326         put_device(&rproc->dev);
1327 }
1328 EXPORT_SYMBOL(rproc_put);
1329
1330 /**
1331  * rproc_del() - unregister a remote processor
1332  * @rproc: rproc handle to unregister
1333  *
1334  * This function should be called when the platform specific rproc
1335  * implementation decides to remove the rproc device. it should
1336  * _only_ be called if a previous invocation of rproc_add()
1337  * has completed successfully.
1338  *
1339  * After rproc_del() returns, @rproc isn't freed yet, because
1340  * of the outstanding reference created by rproc_alloc. To decrement that
1341  * one last refcount, one still needs to call rproc_put().
1342  *
1343  * Returns 0 on success and -EINVAL if @rproc isn't valid.
1344  */
1345 int rproc_del(struct rproc *rproc)
1346 {
1347         struct rproc_vdev *rvdev, *tmp;
1348
1349         if (!rproc)
1350                 return -EINVAL;
1351
1352         /* if rproc is just being registered, wait */
1353         wait_for_completion(&rproc->firmware_loading_complete);
1354
1355         /* clean up remote vdev entries */
1356         list_for_each_entry_safe(rvdev, tmp, &rproc->rvdevs, node)
1357                 rproc_remove_virtio_dev(rvdev);
1358
1359         device_del(&rproc->dev);
1360
1361         return 0;
1362 }
1363 EXPORT_SYMBOL(rproc_del);
1364
1365 /**
1366  * rproc_report_crash() - rproc crash reporter function
1367  * @rproc: remote processor
1368  * @type: crash type
1369  *
1370  * This function must be called every time a crash is detected by the low-level
1371  * drivers implementing a specific remoteproc. This should not be called from a
1372  * non-remoteproc driver.
1373  *
1374  * This function can be called from atomic/interrupt context.
1375  */
1376 void rproc_report_crash(struct rproc *rproc, enum rproc_crash_type type)
1377 {
1378         if (!rproc) {
1379                 pr_err("NULL rproc pointer\n");
1380                 return;
1381         }
1382
1383         dev_err(&rproc->dev, "crash detected in %s: type %s\n",
1384                 rproc->name, rproc_crash_to_string(type));
1385
1386         /* create a new task to handle the error */
1387         schedule_work(&rproc->crash_handler);
1388 }
1389 EXPORT_SYMBOL(rproc_report_crash);
1390
1391 static int __init remoteproc_init(void)
1392 {
1393         rproc_init_debugfs();
1394
1395         return 0;
1396 }
1397 module_init(remoteproc_init);
1398
1399 static void __exit remoteproc_exit(void)
1400 {
1401         rproc_exit_debugfs();
1402 }
1403 module_exit(remoteproc_exit);
1404
1405 MODULE_LICENSE("GPL v2");
1406 MODULE_DESCRIPTION("Generic Remote Processor Framework");