misc: fastrpc: Fix use-after-free and race in fastrpc_map_find
[platform/kernel/linux-starfive.git] / drivers / misc / fastrpc.c
1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2011-2018, The Linux Foundation. All rights reserved.
3 // Copyright (c) 2018, Linaro Limited
4
5 #include <linux/completion.h>
6 #include <linux/device.h>
7 #include <linux/dma-buf.h>
8 #include <linux/dma-mapping.h>
9 #include <linux/idr.h>
10 #include <linux/list.h>
11 #include <linux/miscdevice.h>
12 #include <linux/module.h>
13 #include <linux/of_address.h>
14 #include <linux/of.h>
15 #include <linux/sort.h>
16 #include <linux/of_platform.h>
17 #include <linux/rpmsg.h>
18 #include <linux/scatterlist.h>
19 #include <linux/slab.h>
20 #include <linux/qcom_scm.h>
21 #include <uapi/misc/fastrpc.h>
22
23 #define ADSP_DOMAIN_ID (0)
24 #define MDSP_DOMAIN_ID (1)
25 #define SDSP_DOMAIN_ID (2)
26 #define CDSP_DOMAIN_ID (3)
27 #define FASTRPC_DEV_MAX         4 /* adsp, mdsp, slpi, cdsp*/
28 #define FASTRPC_MAX_SESSIONS    14
29 #define FASTRPC_MAX_VMIDS       16
30 #define FASTRPC_ALIGN           128
31 #define FASTRPC_MAX_FDLIST      16
32 #define FASTRPC_MAX_CRCLIST     64
33 #define FASTRPC_PHYS(p) ((p) & 0xffffffff)
34 #define FASTRPC_CTX_MAX (256)
35 #define FASTRPC_INIT_HANDLE     1
36 #define FASTRPC_DSP_UTILITIES_HANDLE    2
37 #define FASTRPC_CTXID_MASK (0xFF0)
38 #define INIT_FILELEN_MAX (2 * 1024 * 1024)
39 #define FASTRPC_DEVICE_NAME     "fastrpc"
40 #define ADSP_MMAP_ADD_PAGES 0x1000
41 #define DSP_UNSUPPORTED_API (0x80000414)
42 /* MAX NUMBER of DSP ATTRIBUTES SUPPORTED */
43 #define FASTRPC_MAX_DSP_ATTRIBUTES (256)
44 #define FASTRPC_MAX_DSP_ATTRIBUTES_LEN (sizeof(u32) * FASTRPC_MAX_DSP_ATTRIBUTES)
45
46 /* Retrives number of input buffers from the scalars parameter */
47 #define REMOTE_SCALARS_INBUFS(sc)       (((sc) >> 16) & 0x0ff)
48
49 /* Retrives number of output buffers from the scalars parameter */
50 #define REMOTE_SCALARS_OUTBUFS(sc)      (((sc) >> 8) & 0x0ff)
51
52 /* Retrives number of input handles from the scalars parameter */
53 #define REMOTE_SCALARS_INHANDLES(sc)    (((sc) >> 4) & 0x0f)
54
55 /* Retrives number of output handles from the scalars parameter */
56 #define REMOTE_SCALARS_OUTHANDLES(sc)   ((sc) & 0x0f)
57
58 #define REMOTE_SCALARS_LENGTH(sc)       (REMOTE_SCALARS_INBUFS(sc) +   \
59                                          REMOTE_SCALARS_OUTBUFS(sc) +  \
60                                          REMOTE_SCALARS_INHANDLES(sc)+ \
61                                          REMOTE_SCALARS_OUTHANDLES(sc))
62 #define FASTRPC_BUILD_SCALARS(attr, method, in, out, oin, oout)  \
63                                 (((attr & 0x07) << 29) |                \
64                                 ((method & 0x1f) << 24) |       \
65                                 ((in & 0xff) << 16) |           \
66                                 ((out & 0xff) <<  8) |          \
67                                 ((oin & 0x0f) <<  4) |          \
68                                 (oout & 0x0f))
69
70 #define FASTRPC_SCALARS(method, in, out) \
71                 FASTRPC_BUILD_SCALARS(0, method, in, out, 0, 0)
72
73 #define FASTRPC_CREATE_PROCESS_NARGS    6
74 /* Remote Method id table */
75 #define FASTRPC_RMID_INIT_ATTACH        0
76 #define FASTRPC_RMID_INIT_RELEASE       1
77 #define FASTRPC_RMID_INIT_MMAP          4
78 #define FASTRPC_RMID_INIT_MUNMAP        5
79 #define FASTRPC_RMID_INIT_CREATE        6
80 #define FASTRPC_RMID_INIT_CREATE_ATTR   7
81 #define FASTRPC_RMID_INIT_CREATE_STATIC 8
82 #define FASTRPC_RMID_INIT_MEM_MAP      10
83 #define FASTRPC_RMID_INIT_MEM_UNMAP    11
84
85 /* Protection Domain(PD) ids */
86 #define AUDIO_PD        (0) /* also GUEST_OS PD? */
87 #define USER_PD         (1)
88 #define SENSORS_PD      (2)
89
90 #define miscdev_to_fdevice(d) container_of(d, struct fastrpc_device, miscdev)
91
92 static const char *domains[FASTRPC_DEV_MAX] = { "adsp", "mdsp",
93                                                 "sdsp", "cdsp"};
94 struct fastrpc_phy_page {
95         u64 addr;               /* physical address */
96         u64 size;               /* size of contiguous region */
97 };
98
99 struct fastrpc_invoke_buf {
100         u32 num;                /* number of contiguous regions */
101         u32 pgidx;              /* index to start of contiguous region */
102 };
103
104 struct fastrpc_remote_dmahandle {
105         s32 fd;         /* dma handle fd */
106         u32 offset;     /* dma handle offset */
107         u32 len;        /* dma handle length */
108 };
109
110 struct fastrpc_remote_buf {
111         u64 pv;         /* buffer pointer */
112         u64 len;        /* length of buffer */
113 };
114
115 union fastrpc_remote_arg {
116         struct fastrpc_remote_buf buf;
117         struct fastrpc_remote_dmahandle dma;
118 };
119
120 struct fastrpc_mmap_rsp_msg {
121         u64 vaddr;
122 };
123
124 struct fastrpc_mmap_req_msg {
125         s32 pgid;
126         u32 flags;
127         u64 vaddr;
128         s32 num;
129 };
130
131 struct fastrpc_mem_map_req_msg {
132         s32 pgid;
133         s32 fd;
134         s32 offset;
135         u32 flags;
136         u64 vaddrin;
137         s32 num;
138         s32 data_len;
139 };
140
141 struct fastrpc_munmap_req_msg {
142         s32 pgid;
143         u64 vaddr;
144         u64 size;
145 };
146
147 struct fastrpc_mem_unmap_req_msg {
148         s32 pgid;
149         s32 fd;
150         u64 vaddrin;
151         u64 len;
152 };
153
154 struct fastrpc_msg {
155         int pid;                /* process group id */
156         int tid;                /* thread id */
157         u64 ctx;                /* invoke caller context */
158         u32 handle;     /* handle to invoke */
159         u32 sc;         /* scalars structure describing the data */
160         u64 addr;               /* physical address */
161         u64 size;               /* size of contiguous region */
162 };
163
164 struct fastrpc_invoke_rsp {
165         u64 ctx;                /* invoke caller context */
166         int retval;             /* invoke return value */
167 };
168
169 struct fastrpc_buf_overlap {
170         u64 start;
171         u64 end;
172         int raix;
173         u64 mstart;
174         u64 mend;
175         u64 offset;
176 };
177
178 struct fastrpc_buf {
179         struct fastrpc_user *fl;
180         struct dma_buf *dmabuf;
181         struct device *dev;
182         void *virt;
183         u64 phys;
184         u64 size;
185         /* Lock for dma buf attachments */
186         struct mutex lock;
187         struct list_head attachments;
188         /* mmap support */
189         struct list_head node; /* list of user requested mmaps */
190         uintptr_t raddr;
191 };
192
193 struct fastrpc_dma_buf_attachment {
194         struct device *dev;
195         struct sg_table sgt;
196         struct list_head node;
197 };
198
199 struct fastrpc_map {
200         struct list_head node;
201         struct fastrpc_user *fl;
202         int fd;
203         struct dma_buf *buf;
204         struct sg_table *table;
205         struct dma_buf_attachment *attach;
206         u64 phys;
207         u64 size;
208         void *va;
209         u64 len;
210         u64 raddr;
211         u32 attr;
212         struct kref refcount;
213 };
214
215 struct fastrpc_invoke_ctx {
216         int nscalars;
217         int nbufs;
218         int retval;
219         int pid;
220         int tgid;
221         u32 sc;
222         u32 *crc;
223         u64 ctxid;
224         u64 msg_sz;
225         struct kref refcount;
226         struct list_head node; /* list of ctxs */
227         struct completion work;
228         struct work_struct put_work;
229         struct fastrpc_msg msg;
230         struct fastrpc_user *fl;
231         union fastrpc_remote_arg *rpra;
232         struct fastrpc_map **maps;
233         struct fastrpc_buf *buf;
234         struct fastrpc_invoke_args *args;
235         struct fastrpc_buf_overlap *olaps;
236         struct fastrpc_channel_ctx *cctx;
237 };
238
239 struct fastrpc_session_ctx {
240         struct device *dev;
241         int sid;
242         bool used;
243         bool valid;
244 };
245
246 struct fastrpc_channel_ctx {
247         int domain_id;
248         int sesscount;
249         int vmcount;
250         u32 perms;
251         struct qcom_scm_vmperm vmperms[FASTRPC_MAX_VMIDS];
252         struct rpmsg_device *rpdev;
253         struct fastrpc_session_ctx session[FASTRPC_MAX_SESSIONS];
254         spinlock_t lock;
255         struct idr ctx_idr;
256         struct list_head users;
257         struct kref refcount;
258         /* Flag if dsp attributes are cached */
259         bool valid_attributes;
260         u32 dsp_attributes[FASTRPC_MAX_DSP_ATTRIBUTES];
261         struct fastrpc_device *secure_fdevice;
262         struct fastrpc_device *fdevice;
263         bool secure;
264         bool unsigned_support;
265 };
266
267 struct fastrpc_device {
268         struct fastrpc_channel_ctx *cctx;
269         struct miscdevice miscdev;
270         bool secure;
271 };
272
273 struct fastrpc_user {
274         struct list_head user;
275         struct list_head maps;
276         struct list_head pending;
277         struct list_head mmaps;
278
279         struct fastrpc_channel_ctx *cctx;
280         struct fastrpc_session_ctx *sctx;
281         struct fastrpc_buf *init_mem;
282
283         int tgid;
284         int pd;
285         bool is_secure_dev;
286         /* Lock for lists */
287         spinlock_t lock;
288         /* lock for allocations */
289         struct mutex mutex;
290 };
291
292 static void fastrpc_free_map(struct kref *ref)
293 {
294         struct fastrpc_map *map;
295
296         map = container_of(ref, struct fastrpc_map, refcount);
297
298         if (map->table) {
299                 if (map->attr & FASTRPC_ATTR_SECUREMAP) {
300                         struct qcom_scm_vmperm perm;
301                         int err = 0;
302
303                         perm.vmid = QCOM_SCM_VMID_HLOS;
304                         perm.perm = QCOM_SCM_PERM_RWX;
305                         err = qcom_scm_assign_mem(map->phys, map->size,
306                                 &(map->fl->cctx->vmperms[0].vmid), &perm, 1);
307                         if (err) {
308                                 dev_err(map->fl->sctx->dev, "Failed to assign memory phys 0x%llx size 0x%llx err %d",
309                                                 map->phys, map->size, err);
310                                 return;
311                         }
312                 }
313                 dma_buf_unmap_attachment(map->attach, map->table,
314                                          DMA_BIDIRECTIONAL);
315                 dma_buf_detach(map->buf, map->attach);
316                 dma_buf_put(map->buf);
317         }
318
319         kfree(map);
320 }
321
322 static void fastrpc_map_put(struct fastrpc_map *map)
323 {
324         if (map)
325                 kref_put(&map->refcount, fastrpc_free_map);
326 }
327
328 static void fastrpc_map_get(struct fastrpc_map *map)
329 {
330         if (map)
331                 kref_get(&map->refcount);
332 }
333
334
335 static int fastrpc_map_lookup(struct fastrpc_user *fl, int fd,
336                             struct fastrpc_map **ppmap, bool take_ref)
337 {
338         struct fastrpc_session_ctx *sess = fl->sctx;
339         struct fastrpc_map *map = NULL;
340         int ret = -ENOENT;
341
342         spin_lock(&fl->lock);
343         list_for_each_entry(map, &fl->maps, node) {
344                 if (map->fd != fd)
345                         continue;
346
347                 if (take_ref) {
348                         ret = fastrpc_map_get(map);
349                         if (ret) {
350                                 dev_dbg(sess->dev, "%s: Failed to get map fd=%d ret=%d\n",
351                                         __func__, fd, ret);
352                                 break;
353                         }
354                 }
355
356                 *ppmap = map;
357                 ret = 0;
358                 break;
359         }
360         spin_unlock(&fl->lock);
361
362         return ret;
363 }
364
365 static void fastrpc_buf_free(struct fastrpc_buf *buf)
366 {
367         dma_free_coherent(buf->dev, buf->size, buf->virt,
368                           FASTRPC_PHYS(buf->phys));
369         kfree(buf);
370 }
371
372 static int fastrpc_buf_alloc(struct fastrpc_user *fl, struct device *dev,
373                              u64 size, struct fastrpc_buf **obuf)
374 {
375         struct fastrpc_buf *buf;
376
377         buf = kzalloc(sizeof(*buf), GFP_KERNEL);
378         if (!buf)
379                 return -ENOMEM;
380
381         INIT_LIST_HEAD(&buf->attachments);
382         INIT_LIST_HEAD(&buf->node);
383         mutex_init(&buf->lock);
384
385         buf->fl = fl;
386         buf->virt = NULL;
387         buf->phys = 0;
388         buf->size = size;
389         buf->dev = dev;
390         buf->raddr = 0;
391
392         buf->virt = dma_alloc_coherent(dev, buf->size, (dma_addr_t *)&buf->phys,
393                                        GFP_KERNEL);
394         if (!buf->virt) {
395                 mutex_destroy(&buf->lock);
396                 kfree(buf);
397                 return -ENOMEM;
398         }
399
400         if (fl->sctx && fl->sctx->sid)
401                 buf->phys += ((u64)fl->sctx->sid << 32);
402
403         *obuf = buf;
404
405         return 0;
406 }
407
408 static void fastrpc_channel_ctx_free(struct kref *ref)
409 {
410         struct fastrpc_channel_ctx *cctx;
411
412         cctx = container_of(ref, struct fastrpc_channel_ctx, refcount);
413
414         kfree(cctx);
415 }
416
417 static void fastrpc_channel_ctx_get(struct fastrpc_channel_ctx *cctx)
418 {
419         kref_get(&cctx->refcount);
420 }
421
422 static void fastrpc_channel_ctx_put(struct fastrpc_channel_ctx *cctx)
423 {
424         kref_put(&cctx->refcount, fastrpc_channel_ctx_free);
425 }
426
427 static void fastrpc_context_free(struct kref *ref)
428 {
429         struct fastrpc_invoke_ctx *ctx;
430         struct fastrpc_channel_ctx *cctx;
431         unsigned long flags;
432         int i;
433
434         ctx = container_of(ref, struct fastrpc_invoke_ctx, refcount);
435         cctx = ctx->cctx;
436
437         for (i = 0; i < ctx->nbufs; i++)
438                 fastrpc_map_put(ctx->maps[i]);
439
440         if (ctx->buf)
441                 fastrpc_buf_free(ctx->buf);
442
443         spin_lock_irqsave(&cctx->lock, flags);
444         idr_remove(&cctx->ctx_idr, ctx->ctxid >> 4);
445         spin_unlock_irqrestore(&cctx->lock, flags);
446
447         kfree(ctx->maps);
448         kfree(ctx->olaps);
449         kfree(ctx);
450
451         fastrpc_channel_ctx_put(cctx);
452 }
453
454 static void fastrpc_context_get(struct fastrpc_invoke_ctx *ctx)
455 {
456         kref_get(&ctx->refcount);
457 }
458
459 static void fastrpc_context_put(struct fastrpc_invoke_ctx *ctx)
460 {
461         kref_put(&ctx->refcount, fastrpc_context_free);
462 }
463
464 static void fastrpc_context_put_wq(struct work_struct *work)
465 {
466         struct fastrpc_invoke_ctx *ctx =
467                         container_of(work, struct fastrpc_invoke_ctx, put_work);
468
469         fastrpc_context_put(ctx);
470 }
471
472 #define CMP(aa, bb) ((aa) == (bb) ? 0 : (aa) < (bb) ? -1 : 1)
473 static int olaps_cmp(const void *a, const void *b)
474 {
475         struct fastrpc_buf_overlap *pa = (struct fastrpc_buf_overlap *)a;
476         struct fastrpc_buf_overlap *pb = (struct fastrpc_buf_overlap *)b;
477         /* sort with lowest starting buffer first */
478         int st = CMP(pa->start, pb->start);
479         /* sort with highest ending buffer first */
480         int ed = CMP(pb->end, pa->end);
481
482         return st == 0 ? ed : st;
483 }
484
485 static void fastrpc_get_buff_overlaps(struct fastrpc_invoke_ctx *ctx)
486 {
487         u64 max_end = 0;
488         int i;
489
490         for (i = 0; i < ctx->nbufs; ++i) {
491                 ctx->olaps[i].start = ctx->args[i].ptr;
492                 ctx->olaps[i].end = ctx->olaps[i].start + ctx->args[i].length;
493                 ctx->olaps[i].raix = i;
494         }
495
496         sort(ctx->olaps, ctx->nbufs, sizeof(*ctx->olaps), olaps_cmp, NULL);
497
498         for (i = 0; i < ctx->nbufs; ++i) {
499                 /* Falling inside previous range */
500                 if (ctx->olaps[i].start < max_end) {
501                         ctx->olaps[i].mstart = max_end;
502                         ctx->olaps[i].mend = ctx->olaps[i].end;
503                         ctx->olaps[i].offset = max_end - ctx->olaps[i].start;
504
505                         if (ctx->olaps[i].end > max_end) {
506                                 max_end = ctx->olaps[i].end;
507                         } else {
508                                 ctx->olaps[i].mend = 0;
509                                 ctx->olaps[i].mstart = 0;
510                         }
511
512                 } else  {
513                         ctx->olaps[i].mend = ctx->olaps[i].end;
514                         ctx->olaps[i].mstart = ctx->olaps[i].start;
515                         ctx->olaps[i].offset = 0;
516                         max_end = ctx->olaps[i].end;
517                 }
518         }
519 }
520
521 static struct fastrpc_invoke_ctx *fastrpc_context_alloc(
522                         struct fastrpc_user *user, u32 kernel, u32 sc,
523                         struct fastrpc_invoke_args *args)
524 {
525         struct fastrpc_channel_ctx *cctx = user->cctx;
526         struct fastrpc_invoke_ctx *ctx = NULL;
527         unsigned long flags;
528         int ret;
529
530         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
531         if (!ctx)
532                 return ERR_PTR(-ENOMEM);
533
534         INIT_LIST_HEAD(&ctx->node);
535         ctx->fl = user;
536         ctx->nscalars = REMOTE_SCALARS_LENGTH(sc);
537         ctx->nbufs = REMOTE_SCALARS_INBUFS(sc) +
538                      REMOTE_SCALARS_OUTBUFS(sc);
539
540         if (ctx->nscalars) {
541                 ctx->maps = kcalloc(ctx->nscalars,
542                                     sizeof(*ctx->maps), GFP_KERNEL);
543                 if (!ctx->maps) {
544                         kfree(ctx);
545                         return ERR_PTR(-ENOMEM);
546                 }
547                 ctx->olaps = kcalloc(ctx->nscalars,
548                                     sizeof(*ctx->olaps), GFP_KERNEL);
549                 if (!ctx->olaps) {
550                         kfree(ctx->maps);
551                         kfree(ctx);
552                         return ERR_PTR(-ENOMEM);
553                 }
554                 ctx->args = args;
555                 fastrpc_get_buff_overlaps(ctx);
556         }
557
558         /* Released in fastrpc_context_put() */
559         fastrpc_channel_ctx_get(cctx);
560
561         ctx->sc = sc;
562         ctx->retval = -1;
563         ctx->pid = current->pid;
564         ctx->tgid = user->tgid;
565         ctx->cctx = cctx;
566         init_completion(&ctx->work);
567         INIT_WORK(&ctx->put_work, fastrpc_context_put_wq);
568
569         spin_lock(&user->lock);
570         list_add_tail(&ctx->node, &user->pending);
571         spin_unlock(&user->lock);
572
573         spin_lock_irqsave(&cctx->lock, flags);
574         ret = idr_alloc_cyclic(&cctx->ctx_idr, ctx, 1,
575                                FASTRPC_CTX_MAX, GFP_ATOMIC);
576         if (ret < 0) {
577                 spin_unlock_irqrestore(&cctx->lock, flags);
578                 goto err_idr;
579         }
580         ctx->ctxid = ret << 4;
581         spin_unlock_irqrestore(&cctx->lock, flags);
582
583         kref_init(&ctx->refcount);
584
585         return ctx;
586 err_idr:
587         spin_lock(&user->lock);
588         list_del(&ctx->node);
589         spin_unlock(&user->lock);
590         fastrpc_channel_ctx_put(cctx);
591         kfree(ctx->maps);
592         kfree(ctx->olaps);
593         kfree(ctx);
594
595         return ERR_PTR(ret);
596 }
597
598 static struct sg_table *
599 fastrpc_map_dma_buf(struct dma_buf_attachment *attachment,
600                     enum dma_data_direction dir)
601 {
602         struct fastrpc_dma_buf_attachment *a = attachment->priv;
603         struct sg_table *table;
604         int ret;
605
606         table = &a->sgt;
607
608         ret = dma_map_sgtable(attachment->dev, table, dir, 0);
609         if (ret)
610                 table = ERR_PTR(ret);
611         return table;
612 }
613
614 static void fastrpc_unmap_dma_buf(struct dma_buf_attachment *attach,
615                                   struct sg_table *table,
616                                   enum dma_data_direction dir)
617 {
618         dma_unmap_sgtable(attach->dev, table, dir, 0);
619 }
620
621 static void fastrpc_release(struct dma_buf *dmabuf)
622 {
623         struct fastrpc_buf *buffer = dmabuf->priv;
624
625         fastrpc_buf_free(buffer);
626 }
627
628 static int fastrpc_dma_buf_attach(struct dma_buf *dmabuf,
629                                   struct dma_buf_attachment *attachment)
630 {
631         struct fastrpc_dma_buf_attachment *a;
632         struct fastrpc_buf *buffer = dmabuf->priv;
633         int ret;
634
635         a = kzalloc(sizeof(*a), GFP_KERNEL);
636         if (!a)
637                 return -ENOMEM;
638
639         ret = dma_get_sgtable(buffer->dev, &a->sgt, buffer->virt,
640                               FASTRPC_PHYS(buffer->phys), buffer->size);
641         if (ret < 0) {
642                 dev_err(buffer->dev, "failed to get scatterlist from DMA API\n");
643                 kfree(a);
644                 return -EINVAL;
645         }
646
647         a->dev = attachment->dev;
648         INIT_LIST_HEAD(&a->node);
649         attachment->priv = a;
650
651         mutex_lock(&buffer->lock);
652         list_add(&a->node, &buffer->attachments);
653         mutex_unlock(&buffer->lock);
654
655         return 0;
656 }
657
658 static void fastrpc_dma_buf_detatch(struct dma_buf *dmabuf,
659                                     struct dma_buf_attachment *attachment)
660 {
661         struct fastrpc_dma_buf_attachment *a = attachment->priv;
662         struct fastrpc_buf *buffer = dmabuf->priv;
663
664         mutex_lock(&buffer->lock);
665         list_del(&a->node);
666         mutex_unlock(&buffer->lock);
667         sg_free_table(&a->sgt);
668         kfree(a);
669 }
670
671 static int fastrpc_vmap(struct dma_buf *dmabuf, struct iosys_map *map)
672 {
673         struct fastrpc_buf *buf = dmabuf->priv;
674
675         iosys_map_set_vaddr(map, buf->virt);
676
677         return 0;
678 }
679
680 static int fastrpc_mmap(struct dma_buf *dmabuf,
681                         struct vm_area_struct *vma)
682 {
683         struct fastrpc_buf *buf = dmabuf->priv;
684         size_t size = vma->vm_end - vma->vm_start;
685
686         return dma_mmap_coherent(buf->dev, vma, buf->virt,
687                                  FASTRPC_PHYS(buf->phys), size);
688 }
689
690 static const struct dma_buf_ops fastrpc_dma_buf_ops = {
691         .attach = fastrpc_dma_buf_attach,
692         .detach = fastrpc_dma_buf_detatch,
693         .map_dma_buf = fastrpc_map_dma_buf,
694         .unmap_dma_buf = fastrpc_unmap_dma_buf,
695         .mmap = fastrpc_mmap,
696         .vmap = fastrpc_vmap,
697         .release = fastrpc_release,
698 };
699
700 static int fastrpc_map_create(struct fastrpc_user *fl, int fd,
701                               u64 len, u32 attr, struct fastrpc_map **ppmap)
702 {
703         struct fastrpc_session_ctx *sess = fl->sctx;
704         struct fastrpc_map *map = NULL;
705         int err = 0;
706
707         if (!fastrpc_map_lookup(fl, fd, ppmap, true))
708                 return 0;
709
710         map = kzalloc(sizeof(*map), GFP_KERNEL);
711         if (!map)
712                 return -ENOMEM;
713
714         INIT_LIST_HEAD(&map->node);
715         map->fl = fl;
716         map->fd = fd;
717         map->buf = dma_buf_get(fd);
718         if (IS_ERR(map->buf)) {
719                 err = PTR_ERR(map->buf);
720                 goto get_err;
721         }
722
723         map->attach = dma_buf_attach(map->buf, sess->dev);
724         if (IS_ERR(map->attach)) {
725                 dev_err(sess->dev, "Failed to attach dmabuf\n");
726                 err = PTR_ERR(map->attach);
727                 goto attach_err;
728         }
729
730         map->table = dma_buf_map_attachment(map->attach, DMA_BIDIRECTIONAL);
731         if (IS_ERR(map->table)) {
732                 err = PTR_ERR(map->table);
733                 goto map_err;
734         }
735
736         map->phys = sg_dma_address(map->table->sgl);
737         map->phys += ((u64)fl->sctx->sid << 32);
738         map->size = len;
739         map->va = sg_virt(map->table->sgl);
740         map->len = len;
741         kref_init(&map->refcount);
742
743         if (attr & FASTRPC_ATTR_SECUREMAP) {
744                 /*
745                  * If subsystem VMIDs are defined in DTSI, then do
746                  * hyp_assign from HLOS to those VM(s)
747                  */
748                 unsigned int perms = BIT(QCOM_SCM_VMID_HLOS);
749
750                 map->attr = attr;
751                 err = qcom_scm_assign_mem(map->phys, (u64)map->size, &perms,
752                                 fl->cctx->vmperms, fl->cctx->vmcount);
753                 if (err) {
754                         dev_err(sess->dev, "Failed to assign memory with phys 0x%llx size 0x%llx err %d",
755                                         map->phys, map->size, err);
756                         goto map_err;
757                 }
758         }
759         spin_lock(&fl->lock);
760         list_add_tail(&map->node, &fl->maps);
761         spin_unlock(&fl->lock);
762         *ppmap = map;
763
764         return 0;
765
766 map_err:
767         dma_buf_detach(map->buf, map->attach);
768 attach_err:
769         dma_buf_put(map->buf);
770 get_err:
771         kfree(map);
772
773         return err;
774 }
775
776 /*
777  * Fastrpc payload buffer with metadata looks like:
778  *
779  * >>>>>>  START of METADATA <<<<<<<<<
780  * +---------------------------------+
781  * |           Arguments             |
782  * | type:(union fastrpc_remote_arg)|
783  * |             (0 - N)             |
784  * +---------------------------------+
785  * |         Invoke Buffer list      |
786  * | type:(struct fastrpc_invoke_buf)|
787  * |           (0 - N)               |
788  * +---------------------------------+
789  * |         Page info list          |
790  * | type:(struct fastrpc_phy_page)  |
791  * |             (0 - N)             |
792  * +---------------------------------+
793  * |         Optional info           |
794  * |(can be specific to SoC/Firmware)|
795  * +---------------------------------+
796  * >>>>>>>>  END of METADATA <<<<<<<<<
797  * +---------------------------------+
798  * |         Inline ARGS             |
799  * |            (0-N)                |
800  * +---------------------------------+
801  */
802
803 static int fastrpc_get_meta_size(struct fastrpc_invoke_ctx *ctx)
804 {
805         int size = 0;
806
807         size = (sizeof(struct fastrpc_remote_buf) +
808                 sizeof(struct fastrpc_invoke_buf) +
809                 sizeof(struct fastrpc_phy_page)) * ctx->nscalars +
810                 sizeof(u64) * FASTRPC_MAX_FDLIST +
811                 sizeof(u32) * FASTRPC_MAX_CRCLIST;
812
813         return size;
814 }
815
816 static u64 fastrpc_get_payload_size(struct fastrpc_invoke_ctx *ctx, int metalen)
817 {
818         u64 size = 0;
819         int oix;
820
821         size = ALIGN(metalen, FASTRPC_ALIGN);
822         for (oix = 0; oix < ctx->nbufs; oix++) {
823                 int i = ctx->olaps[oix].raix;
824
825                 if (ctx->args[i].fd == 0 || ctx->args[i].fd == -1) {
826
827                         if (ctx->olaps[oix].offset == 0)
828                                 size = ALIGN(size, FASTRPC_ALIGN);
829
830                         size += (ctx->olaps[oix].mend - ctx->olaps[oix].mstart);
831                 }
832         }
833
834         return size;
835 }
836
837 static int fastrpc_create_maps(struct fastrpc_invoke_ctx *ctx)
838 {
839         struct device *dev = ctx->fl->sctx->dev;
840         int i, err;
841
842         for (i = 0; i < ctx->nscalars; ++i) {
843
844                 if (ctx->args[i].fd == 0 || ctx->args[i].fd == -1 ||
845                     ctx->args[i].length == 0)
846                         continue;
847
848                 err = fastrpc_map_create(ctx->fl, ctx->args[i].fd,
849                          ctx->args[i].length, ctx->args[i].attr, &ctx->maps[i]);
850                 if (err) {
851                         dev_err(dev, "Error Creating map %d\n", err);
852                         return -EINVAL;
853                 }
854
855         }
856         return 0;
857 }
858
859 static struct fastrpc_invoke_buf *fastrpc_invoke_buf_start(union fastrpc_remote_arg *pra, int len)
860 {
861         return (struct fastrpc_invoke_buf *)(&pra[len]);
862 }
863
864 static struct fastrpc_phy_page *fastrpc_phy_page_start(struct fastrpc_invoke_buf *buf, int len)
865 {
866         return (struct fastrpc_phy_page *)(&buf[len]);
867 }
868
869 static int fastrpc_get_args(u32 kernel, struct fastrpc_invoke_ctx *ctx)
870 {
871         struct device *dev = ctx->fl->sctx->dev;
872         union fastrpc_remote_arg *rpra;
873         struct fastrpc_invoke_buf *list;
874         struct fastrpc_phy_page *pages;
875         int inbufs, i, oix, err = 0;
876         u64 len, rlen, pkt_size;
877         u64 pg_start, pg_end;
878         uintptr_t args;
879         int metalen;
880
881         inbufs = REMOTE_SCALARS_INBUFS(ctx->sc);
882         metalen = fastrpc_get_meta_size(ctx);
883         pkt_size = fastrpc_get_payload_size(ctx, metalen);
884
885         err = fastrpc_create_maps(ctx);
886         if (err)
887                 return err;
888
889         ctx->msg_sz = pkt_size;
890
891         err = fastrpc_buf_alloc(ctx->fl, dev, pkt_size, &ctx->buf);
892         if (err)
893                 return err;
894
895         rpra = ctx->buf->virt;
896         list = fastrpc_invoke_buf_start(rpra, ctx->nscalars);
897         pages = fastrpc_phy_page_start(list, ctx->nscalars);
898         args = (uintptr_t)ctx->buf->virt + metalen;
899         rlen = pkt_size - metalen;
900         ctx->rpra = rpra;
901
902         for (oix = 0; oix < ctx->nbufs; ++oix) {
903                 int mlen;
904
905                 i = ctx->olaps[oix].raix;
906                 len = ctx->args[i].length;
907
908                 rpra[i].buf.pv = 0;
909                 rpra[i].buf.len = len;
910                 list[i].num = len ? 1 : 0;
911                 list[i].pgidx = i;
912
913                 if (!len)
914                         continue;
915
916                 if (ctx->maps[i]) {
917                         struct vm_area_struct *vma = NULL;
918
919                         rpra[i].buf.pv = (u64) ctx->args[i].ptr;
920                         pages[i].addr = ctx->maps[i]->phys;
921
922                         mmap_read_lock(current->mm);
923                         vma = find_vma(current->mm, ctx->args[i].ptr);
924                         if (vma)
925                                 pages[i].addr += ctx->args[i].ptr -
926                                                  vma->vm_start;
927                         mmap_read_unlock(current->mm);
928
929                         pg_start = (ctx->args[i].ptr & PAGE_MASK) >> PAGE_SHIFT;
930                         pg_end = ((ctx->args[i].ptr + len - 1) & PAGE_MASK) >>
931                                   PAGE_SHIFT;
932                         pages[i].size = (pg_end - pg_start + 1) * PAGE_SIZE;
933
934                 } else {
935
936                         if (ctx->olaps[oix].offset == 0) {
937                                 rlen -= ALIGN(args, FASTRPC_ALIGN) - args;
938                                 args = ALIGN(args, FASTRPC_ALIGN);
939                         }
940
941                         mlen = ctx->olaps[oix].mend - ctx->olaps[oix].mstart;
942
943                         if (rlen < mlen)
944                                 goto bail;
945
946                         rpra[i].buf.pv = args - ctx->olaps[oix].offset;
947                         pages[i].addr = ctx->buf->phys -
948                                         ctx->olaps[oix].offset +
949                                         (pkt_size - rlen);
950                         pages[i].addr = pages[i].addr & PAGE_MASK;
951
952                         pg_start = (args & PAGE_MASK) >> PAGE_SHIFT;
953                         pg_end = ((args + len - 1) & PAGE_MASK) >> PAGE_SHIFT;
954                         pages[i].size = (pg_end - pg_start + 1) * PAGE_SIZE;
955                         args = args + mlen;
956                         rlen -= mlen;
957                 }
958
959                 if (i < inbufs && !ctx->maps[i]) {
960                         void *dst = (void *)(uintptr_t)rpra[i].buf.pv;
961                         void *src = (void *)(uintptr_t)ctx->args[i].ptr;
962
963                         if (!kernel) {
964                                 if (copy_from_user(dst, (void __user *)src,
965                                                    len)) {
966                                         err = -EFAULT;
967                                         goto bail;
968                                 }
969                         } else {
970                                 memcpy(dst, src, len);
971                         }
972                 }
973         }
974
975         for (i = ctx->nbufs; i < ctx->nscalars; ++i) {
976                 list[i].num = ctx->args[i].length ? 1 : 0;
977                 list[i].pgidx = i;
978                 if (ctx->maps[i]) {
979                         pages[i].addr = ctx->maps[i]->phys;
980                         pages[i].size = ctx->maps[i]->size;
981                 }
982                 rpra[i].dma.fd = ctx->args[i].fd;
983                 rpra[i].dma.len = ctx->args[i].length;
984                 rpra[i].dma.offset = (u64) ctx->args[i].ptr;
985         }
986
987 bail:
988         if (err)
989                 dev_err(dev, "Error: get invoke args failed:%d\n", err);
990
991         return err;
992 }
993
994 static int fastrpc_put_args(struct fastrpc_invoke_ctx *ctx,
995                             u32 kernel)
996 {
997         union fastrpc_remote_arg *rpra = ctx->rpra;
998         struct fastrpc_user *fl = ctx->fl;
999         struct fastrpc_map *mmap = NULL;
1000         struct fastrpc_invoke_buf *list;
1001         struct fastrpc_phy_page *pages;
1002         u64 *fdlist;
1003         int i, inbufs, outbufs, handles;
1004
1005         inbufs = REMOTE_SCALARS_INBUFS(ctx->sc);
1006         outbufs = REMOTE_SCALARS_OUTBUFS(ctx->sc);
1007         handles = REMOTE_SCALARS_INHANDLES(ctx->sc) + REMOTE_SCALARS_OUTHANDLES(ctx->sc);
1008         list = fastrpc_invoke_buf_start(rpra, ctx->nscalars);
1009         pages = fastrpc_phy_page_start(list, ctx->nscalars);
1010         fdlist = (uint64_t *)(pages + inbufs + outbufs + handles);
1011
1012         for (i = inbufs; i < ctx->nbufs; ++i) {
1013                 if (!ctx->maps[i]) {
1014                         void *src = (void *)(uintptr_t)rpra[i].buf.pv;
1015                         void *dst = (void *)(uintptr_t)ctx->args[i].ptr;
1016                         u64 len = rpra[i].buf.len;
1017
1018                         if (!kernel) {
1019                                 if (copy_to_user((void __user *)dst, src, len))
1020                                         return -EFAULT;
1021                         } else {
1022                                 memcpy(dst, src, len);
1023                         }
1024                 }
1025         }
1026
1027         for (i = 0; i < FASTRPC_MAX_FDLIST; i++) {
1028                 if (!fdlist[i])
1029                         break;
1030                 if (!fastrpc_map_lookup(fl, (int)fdlist[i], &mmap, false))
1031                         fastrpc_map_put(mmap);
1032         }
1033
1034         return 0;
1035 }
1036
1037 static int fastrpc_invoke_send(struct fastrpc_session_ctx *sctx,
1038                                struct fastrpc_invoke_ctx *ctx,
1039                                u32 kernel, uint32_t handle)
1040 {
1041         struct fastrpc_channel_ctx *cctx;
1042         struct fastrpc_user *fl = ctx->fl;
1043         struct fastrpc_msg *msg = &ctx->msg;
1044         int ret;
1045
1046         cctx = fl->cctx;
1047         msg->pid = fl->tgid;
1048         msg->tid = current->pid;
1049
1050         if (kernel)
1051                 msg->pid = 0;
1052
1053         msg->ctx = ctx->ctxid | fl->pd;
1054         msg->handle = handle;
1055         msg->sc = ctx->sc;
1056         msg->addr = ctx->buf ? ctx->buf->phys : 0;
1057         msg->size = roundup(ctx->msg_sz, PAGE_SIZE);
1058         fastrpc_context_get(ctx);
1059
1060         ret = rpmsg_send(cctx->rpdev->ept, (void *)msg, sizeof(*msg));
1061
1062         if (ret)
1063                 fastrpc_context_put(ctx);
1064
1065         return ret;
1066
1067 }
1068
1069 static int fastrpc_internal_invoke(struct fastrpc_user *fl,  u32 kernel,
1070                                    u32 handle, u32 sc,
1071                                    struct fastrpc_invoke_args *args)
1072 {
1073         struct fastrpc_invoke_ctx *ctx = NULL;
1074         int err = 0;
1075
1076         if (!fl->sctx)
1077                 return -EINVAL;
1078
1079         if (!fl->cctx->rpdev)
1080                 return -EPIPE;
1081
1082         if (handle == FASTRPC_INIT_HANDLE && !kernel) {
1083                 dev_warn_ratelimited(fl->sctx->dev, "user app trying to send a kernel RPC message (%d)\n",  handle);
1084                 return -EPERM;
1085         }
1086
1087         ctx = fastrpc_context_alloc(fl, kernel, sc, args);
1088         if (IS_ERR(ctx))
1089                 return PTR_ERR(ctx);
1090
1091         if (ctx->nscalars) {
1092                 err = fastrpc_get_args(kernel, ctx);
1093                 if (err)
1094                         goto bail;
1095         }
1096
1097         /* make sure that all CPU memory writes are seen by DSP */
1098         dma_wmb();
1099         /* Send invoke buffer to remote dsp */
1100         err = fastrpc_invoke_send(fl->sctx, ctx, kernel, handle);
1101         if (err)
1102                 goto bail;
1103
1104         if (kernel) {
1105                 if (!wait_for_completion_timeout(&ctx->work, 10 * HZ))
1106                         err = -ETIMEDOUT;
1107         } else {
1108                 err = wait_for_completion_interruptible(&ctx->work);
1109         }
1110
1111         if (err)
1112                 goto bail;
1113
1114         /* Check the response from remote dsp */
1115         err = ctx->retval;
1116         if (err)
1117                 goto bail;
1118
1119         if (ctx->nscalars) {
1120                 /* make sure that all memory writes by DSP are seen by CPU */
1121                 dma_rmb();
1122                 /* populate all the output buffers with results */
1123                 err = fastrpc_put_args(ctx, kernel);
1124                 if (err)
1125                         goto bail;
1126         }
1127
1128 bail:
1129         if (err != -ERESTARTSYS && err != -ETIMEDOUT) {
1130                 /* We are done with this compute context */
1131                 spin_lock(&fl->lock);
1132                 list_del(&ctx->node);
1133                 spin_unlock(&fl->lock);
1134                 fastrpc_context_put(ctx);
1135         }
1136         if (err)
1137                 dev_dbg(fl->sctx->dev, "Error: Invoke Failed %d\n", err);
1138
1139         return err;
1140 }
1141
1142 static bool is_session_rejected(struct fastrpc_user *fl, bool unsigned_pd_request)
1143 {
1144         /* Check if the device node is non-secure and channel is secure*/
1145         if (!fl->is_secure_dev && fl->cctx->secure) {
1146                 /*
1147                  * Allow untrusted applications to offload only to Unsigned PD when
1148                  * channel is configured as secure and block untrusted apps on channel
1149                  * that does not support unsigned PD offload
1150                  */
1151                 if (!fl->cctx->unsigned_support || !unsigned_pd_request) {
1152                         dev_err(&fl->cctx->rpdev->dev, "Error: Untrusted application trying to offload to signed PD");
1153                         return true;
1154                 }
1155         }
1156
1157         return false;
1158 }
1159
1160 static int fastrpc_init_create_process(struct fastrpc_user *fl,
1161                                         char __user *argp)
1162 {
1163         struct fastrpc_init_create init;
1164         struct fastrpc_invoke_args *args;
1165         struct fastrpc_phy_page pages[1];
1166         struct fastrpc_map *map = NULL;
1167         struct fastrpc_buf *imem = NULL;
1168         int memlen;
1169         int err;
1170         struct {
1171                 int pgid;
1172                 u32 namelen;
1173                 u32 filelen;
1174                 u32 pageslen;
1175                 u32 attrs;
1176                 u32 siglen;
1177         } inbuf;
1178         u32 sc;
1179         bool unsigned_module = false;
1180
1181         args = kcalloc(FASTRPC_CREATE_PROCESS_NARGS, sizeof(*args), GFP_KERNEL);
1182         if (!args)
1183                 return -ENOMEM;
1184
1185         if (copy_from_user(&init, argp, sizeof(init))) {
1186                 err = -EFAULT;
1187                 goto err;
1188         }
1189
1190         if (init.attrs & FASTRPC_MODE_UNSIGNED_MODULE)
1191                 unsigned_module = true;
1192
1193         if (is_session_rejected(fl, unsigned_module)) {
1194                 err = -ECONNREFUSED;
1195                 goto err;
1196         }
1197
1198         if (init.filelen > INIT_FILELEN_MAX) {
1199                 err = -EINVAL;
1200                 goto err;
1201         }
1202
1203         inbuf.pgid = fl->tgid;
1204         inbuf.namelen = strlen(current->comm) + 1;
1205         inbuf.filelen = init.filelen;
1206         inbuf.pageslen = 1;
1207         inbuf.attrs = init.attrs;
1208         inbuf.siglen = init.siglen;
1209         fl->pd = USER_PD;
1210
1211         if (init.filelen && init.filefd) {
1212                 err = fastrpc_map_create(fl, init.filefd, init.filelen, 0, &map);
1213                 if (err)
1214                         goto err;
1215         }
1216
1217         memlen = ALIGN(max(INIT_FILELEN_MAX, (int)init.filelen * 4),
1218                        1024 * 1024);
1219         err = fastrpc_buf_alloc(fl, fl->sctx->dev, memlen,
1220                                 &imem);
1221         if (err)
1222                 goto err_alloc;
1223
1224         fl->init_mem = imem;
1225         args[0].ptr = (u64)(uintptr_t)&inbuf;
1226         args[0].length = sizeof(inbuf);
1227         args[0].fd = -1;
1228
1229         args[1].ptr = (u64)(uintptr_t)current->comm;
1230         args[1].length = inbuf.namelen;
1231         args[1].fd = -1;
1232
1233         args[2].ptr = (u64) init.file;
1234         args[2].length = inbuf.filelen;
1235         args[2].fd = init.filefd;
1236
1237         pages[0].addr = imem->phys;
1238         pages[0].size = imem->size;
1239
1240         args[3].ptr = (u64)(uintptr_t) pages;
1241         args[3].length = 1 * sizeof(*pages);
1242         args[3].fd = -1;
1243
1244         args[4].ptr = (u64)(uintptr_t)&inbuf.attrs;
1245         args[4].length = sizeof(inbuf.attrs);
1246         args[4].fd = -1;
1247
1248         args[5].ptr = (u64)(uintptr_t) &inbuf.siglen;
1249         args[5].length = sizeof(inbuf.siglen);
1250         args[5].fd = -1;
1251
1252         sc = FASTRPC_SCALARS(FASTRPC_RMID_INIT_CREATE, 4, 0);
1253         if (init.attrs)
1254                 sc = FASTRPC_SCALARS(FASTRPC_RMID_INIT_CREATE_ATTR, 6, 0);
1255
1256         err = fastrpc_internal_invoke(fl, true, FASTRPC_INIT_HANDLE,
1257                                       sc, args);
1258         if (err)
1259                 goto err_invoke;
1260
1261         kfree(args);
1262
1263         return 0;
1264
1265 err_invoke:
1266         fl->init_mem = NULL;
1267         fastrpc_buf_free(imem);
1268 err_alloc:
1269         if (map) {
1270                 spin_lock(&fl->lock);
1271                 list_del(&map->node);
1272                 spin_unlock(&fl->lock);
1273                 fastrpc_map_put(map);
1274         }
1275 err:
1276         kfree(args);
1277
1278         return err;
1279 }
1280
1281 static struct fastrpc_session_ctx *fastrpc_session_alloc(
1282                                         struct fastrpc_channel_ctx *cctx)
1283 {
1284         struct fastrpc_session_ctx *session = NULL;
1285         unsigned long flags;
1286         int i;
1287
1288         spin_lock_irqsave(&cctx->lock, flags);
1289         for (i = 0; i < cctx->sesscount; i++) {
1290                 if (!cctx->session[i].used && cctx->session[i].valid) {
1291                         cctx->session[i].used = true;
1292                         session = &cctx->session[i];
1293                         break;
1294                 }
1295         }
1296         spin_unlock_irqrestore(&cctx->lock, flags);
1297
1298         return session;
1299 }
1300
1301 static void fastrpc_session_free(struct fastrpc_channel_ctx *cctx,
1302                                  struct fastrpc_session_ctx *session)
1303 {
1304         unsigned long flags;
1305
1306         spin_lock_irqsave(&cctx->lock, flags);
1307         session->used = false;
1308         spin_unlock_irqrestore(&cctx->lock, flags);
1309 }
1310
1311 static int fastrpc_release_current_dsp_process(struct fastrpc_user *fl)
1312 {
1313         struct fastrpc_invoke_args args[1];
1314         int tgid = 0;
1315         u32 sc;
1316
1317         tgid = fl->tgid;
1318         args[0].ptr = (u64)(uintptr_t) &tgid;
1319         args[0].length = sizeof(tgid);
1320         args[0].fd = -1;
1321         sc = FASTRPC_SCALARS(FASTRPC_RMID_INIT_RELEASE, 1, 0);
1322
1323         return fastrpc_internal_invoke(fl, true, FASTRPC_INIT_HANDLE,
1324                                        sc, &args[0]);
1325 }
1326
1327 static int fastrpc_device_release(struct inode *inode, struct file *file)
1328 {
1329         struct fastrpc_user *fl = (struct fastrpc_user *)file->private_data;
1330         struct fastrpc_channel_ctx *cctx = fl->cctx;
1331         struct fastrpc_invoke_ctx *ctx, *n;
1332         struct fastrpc_map *map, *m;
1333         struct fastrpc_buf *buf, *b;
1334         unsigned long flags;
1335
1336         fastrpc_release_current_dsp_process(fl);
1337
1338         spin_lock_irqsave(&cctx->lock, flags);
1339         list_del(&fl->user);
1340         spin_unlock_irqrestore(&cctx->lock, flags);
1341
1342         if (fl->init_mem)
1343                 fastrpc_buf_free(fl->init_mem);
1344
1345         list_for_each_entry_safe(ctx, n, &fl->pending, node) {
1346                 list_del(&ctx->node);
1347                 fastrpc_context_put(ctx);
1348         }
1349
1350         list_for_each_entry_safe(map, m, &fl->maps, node) {
1351                 list_del(&map->node);
1352                 fastrpc_map_put(map);
1353         }
1354
1355         list_for_each_entry_safe(buf, b, &fl->mmaps, node) {
1356                 list_del(&buf->node);
1357                 fastrpc_buf_free(buf);
1358         }
1359
1360         fastrpc_session_free(cctx, fl->sctx);
1361         fastrpc_channel_ctx_put(cctx);
1362
1363         mutex_destroy(&fl->mutex);
1364         kfree(fl);
1365         file->private_data = NULL;
1366
1367         return 0;
1368 }
1369
1370 static int fastrpc_device_open(struct inode *inode, struct file *filp)
1371 {
1372         struct fastrpc_channel_ctx *cctx;
1373         struct fastrpc_device *fdevice;
1374         struct fastrpc_user *fl = NULL;
1375         unsigned long flags;
1376
1377         fdevice = miscdev_to_fdevice(filp->private_data);
1378         cctx = fdevice->cctx;
1379
1380         fl = kzalloc(sizeof(*fl), GFP_KERNEL);
1381         if (!fl)
1382                 return -ENOMEM;
1383
1384         /* Released in fastrpc_device_release() */
1385         fastrpc_channel_ctx_get(cctx);
1386
1387         filp->private_data = fl;
1388         spin_lock_init(&fl->lock);
1389         mutex_init(&fl->mutex);
1390         INIT_LIST_HEAD(&fl->pending);
1391         INIT_LIST_HEAD(&fl->maps);
1392         INIT_LIST_HEAD(&fl->mmaps);
1393         INIT_LIST_HEAD(&fl->user);
1394         fl->tgid = current->tgid;
1395         fl->cctx = cctx;
1396         fl->is_secure_dev = fdevice->secure;
1397
1398         fl->sctx = fastrpc_session_alloc(cctx);
1399         if (!fl->sctx) {
1400                 dev_err(&cctx->rpdev->dev, "No session available\n");
1401                 mutex_destroy(&fl->mutex);
1402                 kfree(fl);
1403
1404                 return -EBUSY;
1405         }
1406
1407         spin_lock_irqsave(&cctx->lock, flags);
1408         list_add_tail(&fl->user, &cctx->users);
1409         spin_unlock_irqrestore(&cctx->lock, flags);
1410
1411         return 0;
1412 }
1413
1414 static int fastrpc_dmabuf_alloc(struct fastrpc_user *fl, char __user *argp)
1415 {
1416         struct fastrpc_alloc_dma_buf bp;
1417         DEFINE_DMA_BUF_EXPORT_INFO(exp_info);
1418         struct fastrpc_buf *buf = NULL;
1419         int err;
1420
1421         if (copy_from_user(&bp, argp, sizeof(bp)))
1422                 return -EFAULT;
1423
1424         err = fastrpc_buf_alloc(fl, fl->sctx->dev, bp.size, &buf);
1425         if (err)
1426                 return err;
1427         exp_info.ops = &fastrpc_dma_buf_ops;
1428         exp_info.size = bp.size;
1429         exp_info.flags = O_RDWR;
1430         exp_info.priv = buf;
1431         buf->dmabuf = dma_buf_export(&exp_info);
1432         if (IS_ERR(buf->dmabuf)) {
1433                 err = PTR_ERR(buf->dmabuf);
1434                 fastrpc_buf_free(buf);
1435                 return err;
1436         }
1437
1438         bp.fd = dma_buf_fd(buf->dmabuf, O_ACCMODE);
1439         if (bp.fd < 0) {
1440                 dma_buf_put(buf->dmabuf);
1441                 return -EINVAL;
1442         }
1443
1444         if (copy_to_user(argp, &bp, sizeof(bp))) {
1445                 /*
1446                  * The usercopy failed, but we can't do much about it, as
1447                  * dma_buf_fd() already called fd_install() and made the
1448                  * file descriptor accessible for the current process. It
1449                  * might already be closed and dmabuf no longer valid when
1450                  * we reach this point. Therefore "leak" the fd and rely on
1451                  * the process exit path to do any required cleanup.
1452                  */
1453                 return -EFAULT;
1454         }
1455
1456         return 0;
1457 }
1458
1459 static int fastrpc_init_attach(struct fastrpc_user *fl, int pd)
1460 {
1461         struct fastrpc_invoke_args args[1];
1462         int tgid = fl->tgid;
1463         u32 sc;
1464
1465         args[0].ptr = (u64)(uintptr_t) &tgid;
1466         args[0].length = sizeof(tgid);
1467         args[0].fd = -1;
1468         sc = FASTRPC_SCALARS(FASTRPC_RMID_INIT_ATTACH, 1, 0);
1469         fl->pd = pd;
1470
1471         return fastrpc_internal_invoke(fl, true, FASTRPC_INIT_HANDLE,
1472                                        sc, &args[0]);
1473 }
1474
1475 static int fastrpc_invoke(struct fastrpc_user *fl, char __user *argp)
1476 {
1477         struct fastrpc_invoke_args *args = NULL;
1478         struct fastrpc_invoke inv;
1479         u32 nscalars;
1480         int err;
1481
1482         if (copy_from_user(&inv, argp, sizeof(inv)))
1483                 return -EFAULT;
1484
1485         /* nscalars is truncated here to max supported value */
1486         nscalars = REMOTE_SCALARS_LENGTH(inv.sc);
1487         if (nscalars) {
1488                 args = kcalloc(nscalars, sizeof(*args), GFP_KERNEL);
1489                 if (!args)
1490                         return -ENOMEM;
1491
1492                 if (copy_from_user(args, (void __user *)(uintptr_t)inv.args,
1493                                    nscalars * sizeof(*args))) {
1494                         kfree(args);
1495                         return -EFAULT;
1496                 }
1497         }
1498
1499         err = fastrpc_internal_invoke(fl, false, inv.handle, inv.sc, args);
1500         kfree(args);
1501
1502         return err;
1503 }
1504
1505 static int fastrpc_get_info_from_dsp(struct fastrpc_user *fl, uint32_t *dsp_attr_buf,
1506                                      uint32_t dsp_attr_buf_len)
1507 {
1508         struct fastrpc_invoke_args args[2] = { 0 };
1509
1510         /* Capability filled in userspace */
1511         dsp_attr_buf[0] = 0;
1512
1513         args[0].ptr = (u64)(uintptr_t)&dsp_attr_buf_len;
1514         args[0].length = sizeof(dsp_attr_buf_len);
1515         args[0].fd = -1;
1516         args[1].ptr = (u64)(uintptr_t)&dsp_attr_buf[1];
1517         args[1].length = dsp_attr_buf_len;
1518         args[1].fd = -1;
1519         fl->pd = USER_PD;
1520
1521         return fastrpc_internal_invoke(fl, true, FASTRPC_DSP_UTILITIES_HANDLE,
1522                                        FASTRPC_SCALARS(0, 1, 1), args);
1523 }
1524
1525 static int fastrpc_get_info_from_kernel(struct fastrpc_ioctl_capability *cap,
1526                                         struct fastrpc_user *fl)
1527 {
1528         struct fastrpc_channel_ctx *cctx = fl->cctx;
1529         uint32_t attribute_id = cap->attribute_id;
1530         uint32_t *dsp_attributes;
1531         unsigned long flags;
1532         uint32_t domain = cap->domain;
1533         int err;
1534
1535         spin_lock_irqsave(&cctx->lock, flags);
1536         /* check if we already have queried dsp for attributes */
1537         if (cctx->valid_attributes) {
1538                 spin_unlock_irqrestore(&cctx->lock, flags);
1539                 goto done;
1540         }
1541         spin_unlock_irqrestore(&cctx->lock, flags);
1542
1543         dsp_attributes = kzalloc(FASTRPC_MAX_DSP_ATTRIBUTES_LEN, GFP_KERNEL);
1544         if (!dsp_attributes)
1545                 return -ENOMEM;
1546
1547         err = fastrpc_get_info_from_dsp(fl, dsp_attributes, FASTRPC_MAX_DSP_ATTRIBUTES_LEN);
1548         if (err == DSP_UNSUPPORTED_API) {
1549                 dev_info(&cctx->rpdev->dev,
1550                          "Warning: DSP capabilities not supported on domain: %d\n", domain);
1551                 kfree(dsp_attributes);
1552                 return -EOPNOTSUPP;
1553         } else if (err) {
1554                 dev_err(&cctx->rpdev->dev, "Error: dsp information is incorrect err: %d\n", err);
1555                 kfree(dsp_attributes);
1556                 return err;
1557         }
1558
1559         spin_lock_irqsave(&cctx->lock, flags);
1560         memcpy(cctx->dsp_attributes, dsp_attributes, FASTRPC_MAX_DSP_ATTRIBUTES_LEN);
1561         cctx->valid_attributes = true;
1562         spin_unlock_irqrestore(&cctx->lock, flags);
1563         kfree(dsp_attributes);
1564 done:
1565         cap->capability = cctx->dsp_attributes[attribute_id];
1566         return 0;
1567 }
1568
1569 static int fastrpc_get_dsp_info(struct fastrpc_user *fl, char __user *argp)
1570 {
1571         struct fastrpc_ioctl_capability cap = {0};
1572         int err = 0;
1573
1574         if (copy_from_user(&cap, argp, sizeof(cap)))
1575                 return  -EFAULT;
1576
1577         cap.capability = 0;
1578         if (cap.domain >= FASTRPC_DEV_MAX) {
1579                 dev_err(&fl->cctx->rpdev->dev, "Error: Invalid domain id:%d, err:%d\n",
1580                         cap.domain, err);
1581                 return -ECHRNG;
1582         }
1583
1584         /* Fastrpc Capablities does not support modem domain */
1585         if (cap.domain == MDSP_DOMAIN_ID) {
1586                 dev_err(&fl->cctx->rpdev->dev, "Error: modem not supported %d\n", err);
1587                 return -ECHRNG;
1588         }
1589
1590         if (cap.attribute_id >= FASTRPC_MAX_DSP_ATTRIBUTES) {
1591                 dev_err(&fl->cctx->rpdev->dev, "Error: invalid attribute: %d, err: %d\n",
1592                         cap.attribute_id, err);
1593                 return -EOVERFLOW;
1594         }
1595
1596         err = fastrpc_get_info_from_kernel(&cap, fl);
1597         if (err)
1598                 return err;
1599
1600         if (copy_to_user(argp, &cap.capability, sizeof(cap.capability)))
1601                 return -EFAULT;
1602
1603         return 0;
1604 }
1605
1606 static int fastrpc_req_munmap_impl(struct fastrpc_user *fl,
1607                                    struct fastrpc_req_munmap *req)
1608 {
1609         struct fastrpc_invoke_args args[1] = { [0] = { 0 } };
1610         struct fastrpc_buf *buf = NULL, *iter, *b;
1611         struct fastrpc_munmap_req_msg req_msg;
1612         struct device *dev = fl->sctx->dev;
1613         int err;
1614         u32 sc;
1615
1616         spin_lock(&fl->lock);
1617         list_for_each_entry_safe(iter, b, &fl->mmaps, node) {
1618                 if ((iter->raddr == req->vaddrout) && (iter->size == req->size)) {
1619                         buf = iter;
1620                         break;
1621                 }
1622         }
1623         spin_unlock(&fl->lock);
1624
1625         if (!buf) {
1626                 dev_err(dev, "mmap not in list\n");
1627                 return -EINVAL;
1628         }
1629
1630         req_msg.pgid = fl->tgid;
1631         req_msg.size = buf->size;
1632         req_msg.vaddr = buf->raddr;
1633
1634         args[0].ptr = (u64) (uintptr_t) &req_msg;
1635         args[0].length = sizeof(req_msg);
1636
1637         sc = FASTRPC_SCALARS(FASTRPC_RMID_INIT_MUNMAP, 1, 0);
1638         err = fastrpc_internal_invoke(fl, true, FASTRPC_INIT_HANDLE, sc,
1639                                       &args[0]);
1640         if (!err) {
1641                 dev_dbg(dev, "unmmap\tpt 0x%09lx OK\n", buf->raddr);
1642                 spin_lock(&fl->lock);
1643                 list_del(&buf->node);
1644                 spin_unlock(&fl->lock);
1645                 fastrpc_buf_free(buf);
1646         } else {
1647                 dev_err(dev, "unmmap\tpt 0x%09lx ERROR\n", buf->raddr);
1648         }
1649
1650         return err;
1651 }
1652
1653 static int fastrpc_req_munmap(struct fastrpc_user *fl, char __user *argp)
1654 {
1655         struct fastrpc_req_munmap req;
1656
1657         if (copy_from_user(&req, argp, sizeof(req)))
1658                 return -EFAULT;
1659
1660         return fastrpc_req_munmap_impl(fl, &req);
1661 }
1662
1663 static int fastrpc_req_mmap(struct fastrpc_user *fl, char __user *argp)
1664 {
1665         struct fastrpc_invoke_args args[3] = { [0 ... 2] = { 0 } };
1666         struct fastrpc_buf *buf = NULL;
1667         struct fastrpc_mmap_req_msg req_msg;
1668         struct fastrpc_mmap_rsp_msg rsp_msg;
1669         struct fastrpc_req_munmap req_unmap;
1670         struct fastrpc_phy_page pages;
1671         struct fastrpc_req_mmap req;
1672         struct device *dev = fl->sctx->dev;
1673         int err;
1674         u32 sc;
1675
1676         if (copy_from_user(&req, argp, sizeof(req)))
1677                 return -EFAULT;
1678
1679         if (req.flags != ADSP_MMAP_ADD_PAGES) {
1680                 dev_err(dev, "flag not supported 0x%x\n", req.flags);
1681                 return -EINVAL;
1682         }
1683
1684         if (req.vaddrin) {
1685                 dev_err(dev, "adding user allocated pages is not supported\n");
1686                 return -EINVAL;
1687         }
1688
1689         err = fastrpc_buf_alloc(fl, fl->sctx->dev, req.size, &buf);
1690         if (err) {
1691                 dev_err(dev, "failed to allocate buffer\n");
1692                 return err;
1693         }
1694
1695         req_msg.pgid = fl->tgid;
1696         req_msg.flags = req.flags;
1697         req_msg.vaddr = req.vaddrin;
1698         req_msg.num = sizeof(pages);
1699
1700         args[0].ptr = (u64) (uintptr_t) &req_msg;
1701         args[0].length = sizeof(req_msg);
1702
1703         pages.addr = buf->phys;
1704         pages.size = buf->size;
1705
1706         args[1].ptr = (u64) (uintptr_t) &pages;
1707         args[1].length = sizeof(pages);
1708
1709         args[2].ptr = (u64) (uintptr_t) &rsp_msg;
1710         args[2].length = sizeof(rsp_msg);
1711
1712         sc = FASTRPC_SCALARS(FASTRPC_RMID_INIT_MMAP, 2, 1);
1713         err = fastrpc_internal_invoke(fl, true, FASTRPC_INIT_HANDLE, sc,
1714                                       &args[0]);
1715         if (err) {
1716                 dev_err(dev, "mmap error (len 0x%08llx)\n", buf->size);
1717                 goto err_invoke;
1718         }
1719
1720         /* update the buffer to be able to deallocate the memory on the DSP */
1721         buf->raddr = (uintptr_t) rsp_msg.vaddr;
1722
1723         /* let the client know the address to use */
1724         req.vaddrout = rsp_msg.vaddr;
1725
1726         spin_lock(&fl->lock);
1727         list_add_tail(&buf->node, &fl->mmaps);
1728         spin_unlock(&fl->lock);
1729
1730         if (copy_to_user((void __user *)argp, &req, sizeof(req))) {
1731                 /* unmap the memory and release the buffer */
1732                 req_unmap.vaddrout = buf->raddr;
1733                 req_unmap.size = buf->size;
1734                 fastrpc_req_munmap_impl(fl, &req_unmap);
1735                 return -EFAULT;
1736         }
1737
1738         dev_dbg(dev, "mmap\t\tpt 0x%09lx OK [len 0x%08llx]\n",
1739                 buf->raddr, buf->size);
1740
1741         return 0;
1742
1743 err_invoke:
1744         fastrpc_buf_free(buf);
1745
1746         return err;
1747 }
1748
1749 static int fastrpc_req_mem_unmap_impl(struct fastrpc_user *fl, struct fastrpc_mem_unmap *req)
1750 {
1751         struct fastrpc_invoke_args args[1] = { [0] = { 0 } };
1752         struct fastrpc_map *map = NULL, *iter, *m;
1753         struct fastrpc_mem_unmap_req_msg req_msg = { 0 };
1754         int err = 0;
1755         u32 sc;
1756         struct device *dev = fl->sctx->dev;
1757
1758         spin_lock(&fl->lock);
1759         list_for_each_entry_safe(iter, m, &fl->maps, node) {
1760                 if ((req->fd < 0 || iter->fd == req->fd) && (iter->raddr == req->vaddr)) {
1761                         map = iter;
1762                         break;
1763                 }
1764         }
1765
1766         spin_unlock(&fl->lock);
1767
1768         if (!map) {
1769                 dev_err(dev, "map not in list\n");
1770                 return -EINVAL;
1771         }
1772
1773         req_msg.pgid = fl->tgid;
1774         req_msg.len = map->len;
1775         req_msg.vaddrin = map->raddr;
1776         req_msg.fd = map->fd;
1777
1778         args[0].ptr = (u64) (uintptr_t) &req_msg;
1779         args[0].length = sizeof(req_msg);
1780
1781         sc = FASTRPC_SCALARS(FASTRPC_RMID_INIT_MEM_UNMAP, 1, 0);
1782         err = fastrpc_internal_invoke(fl, true, FASTRPC_INIT_HANDLE, sc,
1783                                       &args[0]);
1784         fastrpc_map_put(map);
1785         if (err)
1786                 dev_err(dev, "unmmap\tpt fd = %d, 0x%09llx error\n",  map->fd, map->raddr);
1787
1788         return err;
1789 }
1790
1791 static int fastrpc_req_mem_unmap(struct fastrpc_user *fl, char __user *argp)
1792 {
1793         struct fastrpc_mem_unmap req;
1794
1795         if (copy_from_user(&req, argp, sizeof(req)))
1796                 return -EFAULT;
1797
1798         return fastrpc_req_mem_unmap_impl(fl, &req);
1799 }
1800
1801 static int fastrpc_req_mem_map(struct fastrpc_user *fl, char __user *argp)
1802 {
1803         struct fastrpc_invoke_args args[4] = { [0 ... 3] = { 0 } };
1804         struct fastrpc_mem_map_req_msg req_msg = { 0 };
1805         struct fastrpc_mmap_rsp_msg rsp_msg = { 0 };
1806         struct fastrpc_mem_unmap req_unmap = { 0 };
1807         struct fastrpc_phy_page pages = { 0 };
1808         struct fastrpc_mem_map req;
1809         struct device *dev = fl->sctx->dev;
1810         struct fastrpc_map *map = NULL;
1811         int err;
1812         u32 sc;
1813
1814         if (copy_from_user(&req, argp, sizeof(req)))
1815                 return -EFAULT;
1816
1817         /* create SMMU mapping */
1818         err = fastrpc_map_create(fl, req.fd, req.length, 0, &map);
1819         if (err) {
1820                 dev_err(dev, "failed to map buffer, fd = %d\n", req.fd);
1821                 return err;
1822         }
1823
1824         req_msg.pgid = fl->tgid;
1825         req_msg.fd = req.fd;
1826         req_msg.offset = req.offset;
1827         req_msg.vaddrin = req.vaddrin;
1828         map->va = (void *) (uintptr_t) req.vaddrin;
1829         req_msg.flags = req.flags;
1830         req_msg.num = sizeof(pages);
1831         req_msg.data_len = 0;
1832
1833         args[0].ptr = (u64) (uintptr_t) &req_msg;
1834         args[0].length = sizeof(req_msg);
1835
1836         pages.addr = map->phys;
1837         pages.size = map->size;
1838
1839         args[1].ptr = (u64) (uintptr_t) &pages;
1840         args[1].length = sizeof(pages);
1841
1842         args[2].ptr = (u64) (uintptr_t) &pages;
1843         args[2].length = 0;
1844
1845         args[3].ptr = (u64) (uintptr_t) &rsp_msg;
1846         args[3].length = sizeof(rsp_msg);
1847
1848         sc = FASTRPC_SCALARS(FASTRPC_RMID_INIT_MEM_MAP, 3, 1);
1849         err = fastrpc_internal_invoke(fl, true, FASTRPC_INIT_HANDLE, sc, &args[0]);
1850         if (err) {
1851                 dev_err(dev, "mem mmap error, fd %d, vaddr %llx, size %lld\n",
1852                         req.fd, req.vaddrin, map->size);
1853                 goto err_invoke;
1854         }
1855
1856         /* update the buffer to be able to deallocate the memory on the DSP */
1857         map->raddr = rsp_msg.vaddr;
1858
1859         /* let the client know the address to use */
1860         req.vaddrout = rsp_msg.vaddr;
1861
1862         if (copy_to_user((void __user *)argp, &req, sizeof(req))) {
1863                 /* unmap the memory and release the buffer */
1864                 req_unmap.vaddr = (uintptr_t) rsp_msg.vaddr;
1865                 req_unmap.length = map->size;
1866                 fastrpc_req_mem_unmap_impl(fl, &req_unmap);
1867                 return -EFAULT;
1868         }
1869
1870         return 0;
1871
1872 err_invoke:
1873         fastrpc_map_put(map);
1874
1875         return err;
1876 }
1877
1878 static long fastrpc_device_ioctl(struct file *file, unsigned int cmd,
1879                                  unsigned long arg)
1880 {
1881         struct fastrpc_user *fl = (struct fastrpc_user *)file->private_data;
1882         char __user *argp = (char __user *)arg;
1883         int err;
1884
1885         switch (cmd) {
1886         case FASTRPC_IOCTL_INVOKE:
1887                 err = fastrpc_invoke(fl, argp);
1888                 break;
1889         case FASTRPC_IOCTL_INIT_ATTACH:
1890                 err = fastrpc_init_attach(fl, AUDIO_PD);
1891                 break;
1892         case FASTRPC_IOCTL_INIT_ATTACH_SNS:
1893                 err = fastrpc_init_attach(fl, SENSORS_PD);
1894                 break;
1895         case FASTRPC_IOCTL_INIT_CREATE:
1896                 err = fastrpc_init_create_process(fl, argp);
1897                 break;
1898         case FASTRPC_IOCTL_ALLOC_DMA_BUFF:
1899                 err = fastrpc_dmabuf_alloc(fl, argp);
1900                 break;
1901         case FASTRPC_IOCTL_MMAP:
1902                 err = fastrpc_req_mmap(fl, argp);
1903                 break;
1904         case FASTRPC_IOCTL_MUNMAP:
1905                 err = fastrpc_req_munmap(fl, argp);
1906                 break;
1907         case FASTRPC_IOCTL_MEM_MAP:
1908                 err = fastrpc_req_mem_map(fl, argp);
1909                 break;
1910         case FASTRPC_IOCTL_MEM_UNMAP:
1911                 err = fastrpc_req_mem_unmap(fl, argp);
1912                 break;
1913         case FASTRPC_IOCTL_GET_DSP_INFO:
1914                 err = fastrpc_get_dsp_info(fl, argp);
1915                 break;
1916         default:
1917                 err = -ENOTTY;
1918                 break;
1919         }
1920
1921         return err;
1922 }
1923
1924 static const struct file_operations fastrpc_fops = {
1925         .open = fastrpc_device_open,
1926         .release = fastrpc_device_release,
1927         .unlocked_ioctl = fastrpc_device_ioctl,
1928         .compat_ioctl = fastrpc_device_ioctl,
1929 };
1930
1931 static int fastrpc_cb_probe(struct platform_device *pdev)
1932 {
1933         struct fastrpc_channel_ctx *cctx;
1934         struct fastrpc_session_ctx *sess;
1935         struct device *dev = &pdev->dev;
1936         int i, sessions = 0;
1937         unsigned long flags;
1938         int rc;
1939
1940         cctx = dev_get_drvdata(dev->parent);
1941         if (!cctx)
1942                 return -EINVAL;
1943
1944         of_property_read_u32(dev->of_node, "qcom,nsessions", &sessions);
1945
1946         spin_lock_irqsave(&cctx->lock, flags);
1947         if (cctx->sesscount >= FASTRPC_MAX_SESSIONS) {
1948                 dev_err(&pdev->dev, "too many sessions\n");
1949                 spin_unlock_irqrestore(&cctx->lock, flags);
1950                 return -ENOSPC;
1951         }
1952         sess = &cctx->session[cctx->sesscount++];
1953         sess->used = false;
1954         sess->valid = true;
1955         sess->dev = dev;
1956         dev_set_drvdata(dev, sess);
1957
1958         if (of_property_read_u32(dev->of_node, "reg", &sess->sid))
1959                 dev_info(dev, "FastRPC Session ID not specified in DT\n");
1960
1961         if (sessions > 0) {
1962                 struct fastrpc_session_ctx *dup_sess;
1963
1964                 for (i = 1; i < sessions; i++) {
1965                         if (cctx->sesscount >= FASTRPC_MAX_SESSIONS)
1966                                 break;
1967                         dup_sess = &cctx->session[cctx->sesscount++];
1968                         memcpy(dup_sess, sess, sizeof(*dup_sess));
1969                 }
1970         }
1971         spin_unlock_irqrestore(&cctx->lock, flags);
1972         rc = dma_set_mask(dev, DMA_BIT_MASK(32));
1973         if (rc) {
1974                 dev_err(dev, "32-bit DMA enable failed\n");
1975                 return rc;
1976         }
1977
1978         return 0;
1979 }
1980
1981 static int fastrpc_cb_remove(struct platform_device *pdev)
1982 {
1983         struct fastrpc_channel_ctx *cctx = dev_get_drvdata(pdev->dev.parent);
1984         struct fastrpc_session_ctx *sess = dev_get_drvdata(&pdev->dev);
1985         unsigned long flags;
1986         int i;
1987
1988         spin_lock_irqsave(&cctx->lock, flags);
1989         for (i = 1; i < FASTRPC_MAX_SESSIONS; i++) {
1990                 if (cctx->session[i].sid == sess->sid) {
1991                         cctx->session[i].valid = false;
1992                         cctx->sesscount--;
1993                 }
1994         }
1995         spin_unlock_irqrestore(&cctx->lock, flags);
1996
1997         return 0;
1998 }
1999
2000 static const struct of_device_id fastrpc_match_table[] = {
2001         { .compatible = "qcom,fastrpc-compute-cb", },
2002         {}
2003 };
2004
2005 static struct platform_driver fastrpc_cb_driver = {
2006         .probe = fastrpc_cb_probe,
2007         .remove = fastrpc_cb_remove,
2008         .driver = {
2009                 .name = "qcom,fastrpc-cb",
2010                 .of_match_table = fastrpc_match_table,
2011                 .suppress_bind_attrs = true,
2012         },
2013 };
2014
2015 static int fastrpc_device_register(struct device *dev, struct fastrpc_channel_ctx *cctx,
2016                                    bool is_secured, const char *domain)
2017 {
2018         struct fastrpc_device *fdev;
2019         int err;
2020
2021         fdev = devm_kzalloc(dev, sizeof(*fdev), GFP_KERNEL);
2022         if (!fdev)
2023                 return -ENOMEM;
2024
2025         fdev->secure = is_secured;
2026         fdev->cctx = cctx;
2027         fdev->miscdev.minor = MISC_DYNAMIC_MINOR;
2028         fdev->miscdev.fops = &fastrpc_fops;
2029         fdev->miscdev.name = devm_kasprintf(dev, GFP_KERNEL, "fastrpc-%s%s",
2030                                             domain, is_secured ? "-secure" : "");
2031         err = misc_register(&fdev->miscdev);
2032         if (!err) {
2033                 if (is_secured)
2034                         cctx->secure_fdevice = fdev;
2035                 else
2036                         cctx->fdevice = fdev;
2037         }
2038
2039         return err;
2040 }
2041
2042 static int fastrpc_rpmsg_probe(struct rpmsg_device *rpdev)
2043 {
2044         struct device *rdev = &rpdev->dev;
2045         struct fastrpc_channel_ctx *data;
2046         int i, err, domain_id = -1, vmcount;
2047         const char *domain;
2048         bool secure_dsp;
2049         unsigned int vmids[FASTRPC_MAX_VMIDS];
2050
2051         err = of_property_read_string(rdev->of_node, "label", &domain);
2052         if (err) {
2053                 dev_info(rdev, "FastRPC Domain not specified in DT\n");
2054                 return err;
2055         }
2056
2057         for (i = 0; i <= CDSP_DOMAIN_ID; i++) {
2058                 if (!strcmp(domains[i], domain)) {
2059                         domain_id = i;
2060                         break;
2061                 }
2062         }
2063
2064         if (domain_id < 0) {
2065                 dev_info(rdev, "FastRPC Invalid Domain ID %d\n", domain_id);
2066                 return -EINVAL;
2067         }
2068
2069         vmcount = of_property_read_variable_u32_array(rdev->of_node,
2070                                 "qcom,vmids", &vmids[0], 0, FASTRPC_MAX_VMIDS);
2071         if (vmcount < 0)
2072                 vmcount = 0;
2073         else if (!qcom_scm_is_available())
2074                 return -EPROBE_DEFER;
2075
2076         data = kzalloc(sizeof(*data), GFP_KERNEL);
2077         if (!data)
2078                 return -ENOMEM;
2079
2080         if (vmcount) {
2081                 data->vmcount = vmcount;
2082                 data->perms = BIT(QCOM_SCM_VMID_HLOS);
2083                 for (i = 0; i < data->vmcount; i++) {
2084                         data->vmperms[i].vmid = vmids[i];
2085                         data->vmperms[i].perm = QCOM_SCM_PERM_RWX;
2086                 }
2087         }
2088
2089         secure_dsp = !(of_property_read_bool(rdev->of_node, "qcom,non-secure-domain"));
2090         data->secure = secure_dsp;
2091
2092         switch (domain_id) {
2093         case ADSP_DOMAIN_ID:
2094         case MDSP_DOMAIN_ID:
2095         case SDSP_DOMAIN_ID:
2096                 /* Unsigned PD offloading is only supported on CDSP*/
2097                 data->unsigned_support = false;
2098                 err = fastrpc_device_register(rdev, data, secure_dsp, domains[domain_id]);
2099                 if (err)
2100                         goto fdev_error;
2101                 break;
2102         case CDSP_DOMAIN_ID:
2103                 data->unsigned_support = true;
2104                 /* Create both device nodes so that we can allow both Signed and Unsigned PD */
2105                 err = fastrpc_device_register(rdev, data, true, domains[domain_id]);
2106                 if (err)
2107                         goto fdev_error;
2108
2109                 err = fastrpc_device_register(rdev, data, false, domains[domain_id]);
2110                 if (err)
2111                         goto fdev_error;
2112                 break;
2113         default:
2114                 err = -EINVAL;
2115                 goto fdev_error;
2116         }
2117
2118         kref_init(&data->refcount);
2119
2120         dev_set_drvdata(&rpdev->dev, data);
2121         dma_set_mask_and_coherent(rdev, DMA_BIT_MASK(32));
2122         INIT_LIST_HEAD(&data->users);
2123         spin_lock_init(&data->lock);
2124         idr_init(&data->ctx_idr);
2125         data->domain_id = domain_id;
2126         data->rpdev = rpdev;
2127
2128         return of_platform_populate(rdev->of_node, NULL, NULL, rdev);
2129 fdev_error:
2130         kfree(data);
2131         return err;
2132 }
2133
2134 static void fastrpc_notify_users(struct fastrpc_user *user)
2135 {
2136         struct fastrpc_invoke_ctx *ctx;
2137
2138         spin_lock(&user->lock);
2139         list_for_each_entry(ctx, &user->pending, node)
2140                 complete(&ctx->work);
2141         spin_unlock(&user->lock);
2142 }
2143
2144 static void fastrpc_rpmsg_remove(struct rpmsg_device *rpdev)
2145 {
2146         struct fastrpc_channel_ctx *cctx = dev_get_drvdata(&rpdev->dev);
2147         struct fastrpc_user *user;
2148         unsigned long flags;
2149
2150         spin_lock_irqsave(&cctx->lock, flags);
2151         list_for_each_entry(user, &cctx->users, user)
2152                 fastrpc_notify_users(user);
2153         spin_unlock_irqrestore(&cctx->lock, flags);
2154
2155         if (cctx->fdevice)
2156                 misc_deregister(&cctx->fdevice->miscdev);
2157
2158         if (cctx->secure_fdevice)
2159                 misc_deregister(&cctx->secure_fdevice->miscdev);
2160
2161         of_platform_depopulate(&rpdev->dev);
2162
2163         cctx->rpdev = NULL;
2164         fastrpc_channel_ctx_put(cctx);
2165 }
2166
2167 static int fastrpc_rpmsg_callback(struct rpmsg_device *rpdev, void *data,
2168                                   int len, void *priv, u32 addr)
2169 {
2170         struct fastrpc_channel_ctx *cctx = dev_get_drvdata(&rpdev->dev);
2171         struct fastrpc_invoke_rsp *rsp = data;
2172         struct fastrpc_invoke_ctx *ctx;
2173         unsigned long flags;
2174         unsigned long ctxid;
2175
2176         if (len < sizeof(*rsp))
2177                 return -EINVAL;
2178
2179         ctxid = ((rsp->ctx & FASTRPC_CTXID_MASK) >> 4);
2180
2181         spin_lock_irqsave(&cctx->lock, flags);
2182         ctx = idr_find(&cctx->ctx_idr, ctxid);
2183         spin_unlock_irqrestore(&cctx->lock, flags);
2184
2185         if (!ctx) {
2186                 dev_err(&rpdev->dev, "No context ID matches response\n");
2187                 return -ENOENT;
2188         }
2189
2190         ctx->retval = rsp->retval;
2191         complete(&ctx->work);
2192
2193         /*
2194          * The DMA buffer associated with the context cannot be freed in
2195          * interrupt context so schedule it through a worker thread to
2196          * avoid a kernel BUG.
2197          */
2198         schedule_work(&ctx->put_work);
2199
2200         return 0;
2201 }
2202
2203 static const struct of_device_id fastrpc_rpmsg_of_match[] = {
2204         { .compatible = "qcom,fastrpc" },
2205         { },
2206 };
2207 MODULE_DEVICE_TABLE(of, fastrpc_rpmsg_of_match);
2208
2209 static struct rpmsg_driver fastrpc_driver = {
2210         .probe = fastrpc_rpmsg_probe,
2211         .remove = fastrpc_rpmsg_remove,
2212         .callback = fastrpc_rpmsg_callback,
2213         .drv = {
2214                 .name = "qcom,fastrpc",
2215                 .of_match_table = fastrpc_rpmsg_of_match,
2216         },
2217 };
2218
2219 static int fastrpc_init(void)
2220 {
2221         int ret;
2222
2223         ret = platform_driver_register(&fastrpc_cb_driver);
2224         if (ret < 0) {
2225                 pr_err("fastrpc: failed to register cb driver\n");
2226                 return ret;
2227         }
2228
2229         ret = register_rpmsg_driver(&fastrpc_driver);
2230         if (ret < 0) {
2231                 pr_err("fastrpc: failed to register rpmsg driver\n");
2232                 platform_driver_unregister(&fastrpc_cb_driver);
2233                 return ret;
2234         }
2235
2236         return 0;
2237 }
2238 module_init(fastrpc_init);
2239
2240 static void fastrpc_exit(void)
2241 {
2242         platform_driver_unregister(&fastrpc_cb_driver);
2243         unregister_rpmsg_driver(&fastrpc_driver);
2244 }
2245 module_exit(fastrpc_exit);
2246
2247 MODULE_LICENSE("GPL v2");
2248 MODULE_IMPORT_NS(DMA_BUF);