GNU Linux-libre 4.19.268-gnu1
[releases.git] / drivers / rapidio / devices / rio_mport_cdev.c
1 /*
2  * RapidIO mport character device
3  *
4  * Copyright 2014-2015 Integrated Device Technology, Inc.
5  *    Alexandre Bounine <alexandre.bounine@idt.com>
6  * Copyright 2014-2015 Prodrive Technologies
7  *    Andre van Herk <andre.van.herk@prodrive-technologies.com>
8  *    Jerry Jacobs <jerry.jacobs@prodrive-technologies.com>
9  * Copyright (C) 2014 Texas Instruments Incorporated
10  *    Aurelien Jacquiot <a-jacquiot@ti.com>
11  *
12  * This program is free software; you can redistribute  it and/or modify it
13  * under  the terms of  the GNU General  Public License as published by the
14  * Free Software Foundation;  either version 2 of the  License, or (at your
15  * option) any later version.
16  */
17 #include <linux/module.h>
18 #include <linux/kernel.h>
19 #include <linux/cdev.h>
20 #include <linux/ioctl.h>
21 #include <linux/uaccess.h>
22 #include <linux/list.h>
23 #include <linux/fs.h>
24 #include <linux/err.h>
25 #include <linux/net.h>
26 #include <linux/poll.h>
27 #include <linux/spinlock.h>
28 #include <linux/sched.h>
29 #include <linux/kfifo.h>
30
31 #include <linux/mm.h>
32 #include <linux/slab.h>
33 #include <linux/vmalloc.h>
34 #include <linux/mman.h>
35
36 #include <linux/dma-mapping.h>
37 #ifdef CONFIG_RAPIDIO_DMA_ENGINE
38 #include <linux/dmaengine.h>
39 #endif
40
41 #include <linux/rio.h>
42 #include <linux/rio_ids.h>
43 #include <linux/rio_drv.h>
44 #include <linux/rio_mport_cdev.h>
45
46 #include "../rio.h"
47
48 #define DRV_NAME        "rio_mport"
49 #define DRV_PREFIX      DRV_NAME ": "
50 #define DEV_NAME        "rio_mport"
51 #define DRV_VERSION     "1.0.0"
52
53 /* Debug output filtering masks */
54 enum {
55         DBG_NONE        = 0,
56         DBG_INIT        = BIT(0), /* driver init */
57         DBG_EXIT        = BIT(1), /* driver exit */
58         DBG_MPORT       = BIT(2), /* mport add/remove */
59         DBG_RDEV        = BIT(3), /* RapidIO device add/remove */
60         DBG_DMA         = BIT(4), /* DMA transfer messages */
61         DBG_MMAP        = BIT(5), /* mapping messages */
62         DBG_IBW         = BIT(6), /* inbound window */
63         DBG_EVENT       = BIT(7), /* event handling messages */
64         DBG_OBW         = BIT(8), /* outbound window messages */
65         DBG_DBELL       = BIT(9), /* doorbell messages */
66         DBG_ALL         = ~0,
67 };
68
69 #ifdef DEBUG
70 #define rmcd_debug(level, fmt, arg...)          \
71         do {                                    \
72                 if (DBG_##level & dbg_level)    \
73                         pr_debug(DRV_PREFIX "%s: " fmt "\n", __func__, ##arg); \
74         } while (0)
75 #else
76 #define rmcd_debug(level, fmt, arg...) \
77                 no_printk(KERN_DEBUG pr_fmt(DRV_PREFIX fmt "\n"), ##arg)
78 #endif
79
80 #define rmcd_warn(fmt, arg...) \
81         pr_warn(DRV_PREFIX "%s WARNING " fmt "\n", __func__, ##arg)
82
83 #define rmcd_error(fmt, arg...) \
84         pr_err(DRV_PREFIX "%s ERROR " fmt "\n", __func__, ##arg)
85
86 MODULE_AUTHOR("Jerry Jacobs <jerry.jacobs@prodrive-technologies.com>");
87 MODULE_AUTHOR("Aurelien Jacquiot <a-jacquiot@ti.com>");
88 MODULE_AUTHOR("Alexandre Bounine <alexandre.bounine@idt.com>");
89 MODULE_AUTHOR("Andre van Herk <andre.van.herk@prodrive-technologies.com>");
90 MODULE_DESCRIPTION("RapidIO mport character device driver");
91 MODULE_LICENSE("GPL");
92 MODULE_VERSION(DRV_VERSION);
93
94 static int dma_timeout = 3000; /* DMA transfer timeout in msec */
95 module_param(dma_timeout, int, S_IRUGO);
96 MODULE_PARM_DESC(dma_timeout, "DMA Transfer Timeout in msec (default: 3000)");
97
98 #ifdef DEBUG
99 static u32 dbg_level = DBG_NONE;
100 module_param(dbg_level, uint, S_IWUSR | S_IWGRP | S_IRUGO);
101 MODULE_PARM_DESC(dbg_level, "Debugging output level (default 0 = none)");
102 #endif
103
104 /*
105  * An internal DMA coherent buffer
106  */
107 struct mport_dma_buf {
108         void            *ib_base;
109         dma_addr_t      ib_phys;
110         u32             ib_size;
111         u64             ib_rio_base;
112         bool            ib_map;
113         struct file     *filp;
114 };
115
116 /*
117  * Internal memory mapping structure
118  */
119 enum rio_mport_map_dir {
120         MAP_INBOUND,
121         MAP_OUTBOUND,
122         MAP_DMA,
123 };
124
125 struct rio_mport_mapping {
126         struct list_head node;
127         struct mport_dev *md;
128         enum rio_mport_map_dir dir;
129         u16 rioid;
130         u64 rio_addr;
131         dma_addr_t phys_addr; /* for mmap */
132         void *virt_addr; /* kernel address, for dma_free_coherent */
133         u64 size;
134         struct kref ref; /* refcount of vmas sharing the mapping */
135         struct file *filp;
136 };
137
138 struct rio_mport_dma_map {
139         int valid;
140         u64 length;
141         void *vaddr;
142         dma_addr_t paddr;
143 };
144
145 #define MPORT_MAX_DMA_BUFS      16
146 #define MPORT_EVENT_DEPTH       10
147
148 /*
149  * mport_dev  driver-specific structure that represents mport device
150  * @active    mport device status flag
151  * @node      list node to maintain list of registered mports
152  * @cdev      character device
153  * @dev       associated device object
154  * @mport     associated subsystem's master port device object
155  * @buf_mutex lock for buffer handling
156  * @file_mutex - lock for open files list
157  * @file_list  - list of open files on given mport
158  * @properties properties of this mport
159  * @portwrites queue of inbound portwrites
160  * @pw_lock    lock for port write queue
161  * @mappings   queue for memory mappings
162  * @dma_chan   DMA channels associated with this device
163  * @dma_ref:
164  * @comp:
165  */
166 struct mport_dev {
167         atomic_t                active;
168         struct list_head        node;
169         struct cdev             cdev;
170         struct device           dev;
171         struct rio_mport        *mport;
172         struct mutex            buf_mutex;
173         struct mutex            file_mutex;
174         struct list_head        file_list;
175         struct rio_mport_properties     properties;
176         struct list_head                doorbells;
177         spinlock_t                      db_lock;
178         struct list_head                portwrites;
179         spinlock_t                      pw_lock;
180         struct list_head        mappings;
181 #ifdef CONFIG_RAPIDIO_DMA_ENGINE
182         struct dma_chan *dma_chan;
183         struct kref     dma_ref;
184         struct completion comp;
185 #endif
186 };
187
188 /*
189  * mport_cdev_priv - data structure specific to individual file object
190  *                   associated with an open device
191  * @md    master port character device object
192  * @async_queue - asynchronous notification queue
193  * @list - file objects tracking list
194  * @db_filters    inbound doorbell filters for this descriptor
195  * @pw_filters    portwrite filters for this descriptor
196  * @event_fifo    event fifo for this descriptor
197  * @event_rx_wait wait queue for this descriptor
198  * @fifo_lock     lock for event_fifo
199  * @event_mask    event mask for this descriptor
200  * @dmach DMA engine channel allocated for specific file object
201  */
202 struct mport_cdev_priv {
203         struct mport_dev        *md;
204         struct fasync_struct    *async_queue;
205         struct list_head        list;
206         struct list_head        db_filters;
207         struct list_head        pw_filters;
208         struct kfifo            event_fifo;
209         wait_queue_head_t       event_rx_wait;
210         spinlock_t              fifo_lock;
211         u32                     event_mask; /* RIO_DOORBELL, RIO_PORTWRITE */
212 #ifdef CONFIG_RAPIDIO_DMA_ENGINE
213         struct dma_chan         *dmach;
214         struct list_head        async_list;
215         spinlock_t              req_lock;
216         struct mutex            dma_lock;
217         struct kref             dma_ref;
218         struct completion       comp;
219 #endif
220 };
221
222 /*
223  * rio_mport_pw_filter - structure to describe a portwrite filter
224  * md_node   node in mport device's list
225  * priv_node node in private file object's list
226  * priv      reference to private data
227  * filter    actual portwrite filter
228  */
229 struct rio_mport_pw_filter {
230         struct list_head md_node;
231         struct list_head priv_node;
232         struct mport_cdev_priv *priv;
233         struct rio_pw_filter filter;
234 };
235
236 /*
237  * rio_mport_db_filter - structure to describe a doorbell filter
238  * @data_node reference to device node
239  * @priv_node node in private data
240  * @priv      reference to private data
241  * @filter    actual doorbell filter
242  */
243 struct rio_mport_db_filter {
244         struct list_head data_node;
245         struct list_head priv_node;
246         struct mport_cdev_priv *priv;
247         struct rio_doorbell_filter filter;
248 };
249
250 static LIST_HEAD(mport_devs);
251 static DEFINE_MUTEX(mport_devs_lock);
252
253 #if (0) /* used by commented out portion of poll function : FIXME */
254 static DECLARE_WAIT_QUEUE_HEAD(mport_cdev_wait);
255 #endif
256
257 static struct class *dev_class;
258 static dev_t dev_number;
259
260 static void mport_release_mapping(struct kref *ref);
261
262 static int rio_mport_maint_rd(struct mport_cdev_priv *priv, void __user *arg,
263                               int local)
264 {
265         struct rio_mport *mport = priv->md->mport;
266         struct rio_mport_maint_io maint_io;
267         u32 *buffer;
268         u32 offset;
269         size_t length;
270         int ret, i;
271
272         if (unlikely(copy_from_user(&maint_io, arg, sizeof(maint_io))))
273                 return -EFAULT;
274
275         if ((maint_io.offset % 4) ||
276             (maint_io.length == 0) || (maint_io.length % 4) ||
277             (maint_io.length + maint_io.offset) > RIO_MAINT_SPACE_SZ)
278                 return -EINVAL;
279
280         buffer = vmalloc(maint_io.length);
281         if (buffer == NULL)
282                 return -ENOMEM;
283         length = maint_io.length/sizeof(u32);
284         offset = maint_io.offset;
285
286         for (i = 0; i < length; i++) {
287                 if (local)
288                         ret = __rio_local_read_config_32(mport,
289                                 offset, &buffer[i]);
290                 else
291                         ret = rio_mport_read_config_32(mport, maint_io.rioid,
292                                 maint_io.hopcount, offset, &buffer[i]);
293                 if (ret)
294                         goto out;
295
296                 offset += 4;
297         }
298
299         if (unlikely(copy_to_user((void __user *)(uintptr_t)maint_io.buffer,
300                                    buffer, maint_io.length)))
301                 ret = -EFAULT;
302 out:
303         vfree(buffer);
304         return ret;
305 }
306
307 static int rio_mport_maint_wr(struct mport_cdev_priv *priv, void __user *arg,
308                               int local)
309 {
310         struct rio_mport *mport = priv->md->mport;
311         struct rio_mport_maint_io maint_io;
312         u32 *buffer;
313         u32 offset;
314         size_t length;
315         int ret = -EINVAL, i;
316
317         if (unlikely(copy_from_user(&maint_io, arg, sizeof(maint_io))))
318                 return -EFAULT;
319
320         if ((maint_io.offset % 4) ||
321             (maint_io.length == 0) || (maint_io.length % 4) ||
322             (maint_io.length + maint_io.offset) > RIO_MAINT_SPACE_SZ)
323                 return -EINVAL;
324
325         buffer = vmalloc(maint_io.length);
326         if (buffer == NULL)
327                 return -ENOMEM;
328         length = maint_io.length;
329
330         if (unlikely(copy_from_user(buffer,
331                         (void __user *)(uintptr_t)maint_io.buffer, length))) {
332                 ret = -EFAULT;
333                 goto out;
334         }
335
336         offset = maint_io.offset;
337         length /= sizeof(u32);
338
339         for (i = 0; i < length; i++) {
340                 if (local)
341                         ret = __rio_local_write_config_32(mport,
342                                                           offset, buffer[i]);
343                 else
344                         ret = rio_mport_write_config_32(mport, maint_io.rioid,
345                                                         maint_io.hopcount,
346                                                         offset, buffer[i]);
347                 if (ret)
348                         goto out;
349
350                 offset += 4;
351         }
352
353 out:
354         vfree(buffer);
355         return ret;
356 }
357
358
359 /*
360  * Inbound/outbound memory mapping functions
361  */
362 static int
363 rio_mport_create_outbound_mapping(struct mport_dev *md, struct file *filp,
364                                   u16 rioid, u64 raddr, u32 size,
365                                   dma_addr_t *paddr)
366 {
367         struct rio_mport *mport = md->mport;
368         struct rio_mport_mapping *map;
369         int ret;
370
371         rmcd_debug(OBW, "did=%d ra=0x%llx sz=0x%x", rioid, raddr, size);
372
373         map = kzalloc(sizeof(*map), GFP_KERNEL);
374         if (map == NULL)
375                 return -ENOMEM;
376
377         ret = rio_map_outb_region(mport, rioid, raddr, size, 0, paddr);
378         if (ret < 0)
379                 goto err_map_outb;
380
381         map->dir = MAP_OUTBOUND;
382         map->rioid = rioid;
383         map->rio_addr = raddr;
384         map->size = size;
385         map->phys_addr = *paddr;
386         map->filp = filp;
387         map->md = md;
388         kref_init(&map->ref);
389         list_add_tail(&map->node, &md->mappings);
390         return 0;
391 err_map_outb:
392         kfree(map);
393         return ret;
394 }
395
396 static int
397 rio_mport_get_outbound_mapping(struct mport_dev *md, struct file *filp,
398                                u16 rioid, u64 raddr, u32 size,
399                                dma_addr_t *paddr)
400 {
401         struct rio_mport_mapping *map;
402         int err = -ENOMEM;
403
404         mutex_lock(&md->buf_mutex);
405         list_for_each_entry(map, &md->mappings, node) {
406                 if (map->dir != MAP_OUTBOUND)
407                         continue;
408                 if (rioid == map->rioid &&
409                     raddr == map->rio_addr && size == map->size) {
410                         *paddr = map->phys_addr;
411                         err = 0;
412                         break;
413                 } else if (rioid == map->rioid &&
414                            raddr < (map->rio_addr + map->size - 1) &&
415                            (raddr + size) > map->rio_addr) {
416                         err = -EBUSY;
417                         break;
418                 }
419         }
420
421         /* If not found, create new */
422         if (err == -ENOMEM)
423                 err = rio_mport_create_outbound_mapping(md, filp, rioid, raddr,
424                                                 size, paddr);
425         mutex_unlock(&md->buf_mutex);
426         return err;
427 }
428
429 static int rio_mport_obw_map(struct file *filp, void __user *arg)
430 {
431         struct mport_cdev_priv *priv = filp->private_data;
432         struct mport_dev *data = priv->md;
433         struct rio_mmap map;
434         dma_addr_t paddr;
435         int ret;
436
437         if (unlikely(copy_from_user(&map, arg, sizeof(map))))
438                 return -EFAULT;
439
440         rmcd_debug(OBW, "did=%d ra=0x%llx sz=0x%llx",
441                    map.rioid, map.rio_addr, map.length);
442
443         ret = rio_mport_get_outbound_mapping(data, filp, map.rioid,
444                                              map.rio_addr, map.length, &paddr);
445         if (ret < 0) {
446                 rmcd_error("Failed to set OBW err= %d", ret);
447                 return ret;
448         }
449
450         map.handle = paddr;
451
452         if (unlikely(copy_to_user(arg, &map, sizeof(map))))
453                 return -EFAULT;
454         return 0;
455 }
456
457 /*
458  * rio_mport_obw_free() - unmap an OutBound Window from RapidIO address space
459  *
460  * @priv: driver private data
461  * @arg:  buffer handle returned by allocation routine
462  */
463 static int rio_mport_obw_free(struct file *filp, void __user *arg)
464 {
465         struct mport_cdev_priv *priv = filp->private_data;
466         struct mport_dev *md = priv->md;
467         u64 handle;
468         struct rio_mport_mapping *map, *_map;
469
470         if (!md->mport->ops->unmap_outb)
471                 return -EPROTONOSUPPORT;
472
473         if (copy_from_user(&handle, arg, sizeof(handle)))
474                 return -EFAULT;
475
476         rmcd_debug(OBW, "h=0x%llx", handle);
477
478         mutex_lock(&md->buf_mutex);
479         list_for_each_entry_safe(map, _map, &md->mappings, node) {
480                 if (map->dir == MAP_OUTBOUND && map->phys_addr == handle) {
481                         if (map->filp == filp) {
482                                 rmcd_debug(OBW, "kref_put h=0x%llx", handle);
483                                 map->filp = NULL;
484                                 kref_put(&map->ref, mport_release_mapping);
485                         }
486                         break;
487                 }
488         }
489         mutex_unlock(&md->buf_mutex);
490
491         return 0;
492 }
493
494 /*
495  * maint_hdid_set() - Set the host Device ID
496  * @priv: driver private data
497  * @arg:        Device Id
498  */
499 static int maint_hdid_set(struct mport_cdev_priv *priv, void __user *arg)
500 {
501         struct mport_dev *md = priv->md;
502         u16 hdid;
503
504         if (copy_from_user(&hdid, arg, sizeof(hdid)))
505                 return -EFAULT;
506
507         md->mport->host_deviceid = hdid;
508         md->properties.hdid = hdid;
509         rio_local_set_device_id(md->mport, hdid);
510
511         rmcd_debug(MPORT, "Set host device Id to %d", hdid);
512
513         return 0;
514 }
515
516 /*
517  * maint_comptag_set() - Set the host Component Tag
518  * @priv: driver private data
519  * @arg:        Component Tag
520  */
521 static int maint_comptag_set(struct mport_cdev_priv *priv, void __user *arg)
522 {
523         struct mport_dev *md = priv->md;
524         u32 comptag;
525
526         if (copy_from_user(&comptag, arg, sizeof(comptag)))
527                 return -EFAULT;
528
529         rio_local_write_config_32(md->mport, RIO_COMPONENT_TAG_CSR, comptag);
530
531         rmcd_debug(MPORT, "Set host Component Tag to %d", comptag);
532
533         return 0;
534 }
535
536 #ifdef CONFIG_RAPIDIO_DMA_ENGINE
537
538 struct mport_dma_req {
539         struct kref refcount;
540         struct list_head node;
541         struct file *filp;
542         struct mport_cdev_priv *priv;
543         enum rio_transfer_sync sync;
544         struct sg_table sgt;
545         struct page **page_list;
546         unsigned int nr_pages;
547         struct rio_mport_mapping *map;
548         struct dma_chan *dmach;
549         enum dma_data_direction dir;
550         dma_cookie_t cookie;
551         enum dma_status status;
552         struct completion req_comp;
553 };
554
555 static void mport_release_def_dma(struct kref *dma_ref)
556 {
557         struct mport_dev *md =
558                         container_of(dma_ref, struct mport_dev, dma_ref);
559
560         rmcd_debug(EXIT, "DMA_%d", md->dma_chan->chan_id);
561         rio_release_dma(md->dma_chan);
562         md->dma_chan = NULL;
563 }
564
565 static void mport_release_dma(struct kref *dma_ref)
566 {
567         struct mport_cdev_priv *priv =
568                         container_of(dma_ref, struct mport_cdev_priv, dma_ref);
569
570         rmcd_debug(EXIT, "DMA_%d", priv->dmach->chan_id);
571         complete(&priv->comp);
572 }
573
574 static void dma_req_free(struct kref *ref)
575 {
576         struct mport_dma_req *req = container_of(ref, struct mport_dma_req,
577                         refcount);
578         struct mport_cdev_priv *priv = req->priv;
579         unsigned int i;
580
581         dma_unmap_sg(req->dmach->device->dev,
582                      req->sgt.sgl, req->sgt.nents, req->dir);
583         sg_free_table(&req->sgt);
584         if (req->page_list) {
585                 for (i = 0; i < req->nr_pages; i++)
586                         put_page(req->page_list[i]);
587                 kfree(req->page_list);
588         }
589
590         if (req->map) {
591                 mutex_lock(&req->map->md->buf_mutex);
592                 kref_put(&req->map->ref, mport_release_mapping);
593                 mutex_unlock(&req->map->md->buf_mutex);
594         }
595
596         kref_put(&priv->dma_ref, mport_release_dma);
597
598         kfree(req);
599 }
600
601 static void dma_xfer_callback(void *param)
602 {
603         struct mport_dma_req *req = (struct mport_dma_req *)param;
604         struct mport_cdev_priv *priv = req->priv;
605
606         req->status = dma_async_is_tx_complete(priv->dmach, req->cookie,
607                                                NULL, NULL);
608         complete(&req->req_comp);
609         kref_put(&req->refcount, dma_req_free);
610 }
611
612 /*
613  * prep_dma_xfer() - Configure and send request to DMAengine to prepare DMA
614  *                   transfer object.
615  * Returns pointer to DMA transaction descriptor allocated by DMA driver on
616  * success or ERR_PTR (and/or NULL) if failed. Caller must check returned
617  * non-NULL pointer using IS_ERR macro.
618  */
619 static struct dma_async_tx_descriptor
620 *prep_dma_xfer(struct dma_chan *chan, struct rio_transfer_io *transfer,
621         struct sg_table *sgt, int nents, enum dma_transfer_direction dir,
622         enum dma_ctrl_flags flags)
623 {
624         struct rio_dma_data tx_data;
625
626         tx_data.sg = sgt->sgl;
627         tx_data.sg_len = nents;
628         tx_data.rio_addr_u = 0;
629         tx_data.rio_addr = transfer->rio_addr;
630         if (dir == DMA_MEM_TO_DEV) {
631                 switch (transfer->method) {
632                 case RIO_EXCHANGE_NWRITE:
633                         tx_data.wr_type = RDW_ALL_NWRITE;
634                         break;
635                 case RIO_EXCHANGE_NWRITE_R_ALL:
636                         tx_data.wr_type = RDW_ALL_NWRITE_R;
637                         break;
638                 case RIO_EXCHANGE_NWRITE_R:
639                         tx_data.wr_type = RDW_LAST_NWRITE_R;
640                         break;
641                 case RIO_EXCHANGE_DEFAULT:
642                         tx_data.wr_type = RDW_DEFAULT;
643                         break;
644                 default:
645                         return ERR_PTR(-EINVAL);
646                 }
647         }
648
649         return rio_dma_prep_xfer(chan, transfer->rioid, &tx_data, dir, flags);
650 }
651
652 /* Request DMA channel associated with this mport device.
653  * Try to request DMA channel for every new process that opened given
654  * mport. If a new DMA channel is not available use default channel
655  * which is the first DMA channel opened on mport device.
656  */
657 static int get_dma_channel(struct mport_cdev_priv *priv)
658 {
659         mutex_lock(&priv->dma_lock);
660         if (!priv->dmach) {
661                 priv->dmach = rio_request_mport_dma(priv->md->mport);
662                 if (!priv->dmach) {
663                         /* Use default DMA channel if available */
664                         if (priv->md->dma_chan) {
665                                 priv->dmach = priv->md->dma_chan;
666                                 kref_get(&priv->md->dma_ref);
667                         } else {
668                                 rmcd_error("Failed to get DMA channel");
669                                 mutex_unlock(&priv->dma_lock);
670                                 return -ENODEV;
671                         }
672                 } else if (!priv->md->dma_chan) {
673                         /* Register default DMA channel if we do not have one */
674                         priv->md->dma_chan = priv->dmach;
675                         kref_init(&priv->md->dma_ref);
676                         rmcd_debug(DMA, "Register DMA_chan %d as default",
677                                    priv->dmach->chan_id);
678                 }
679
680                 kref_init(&priv->dma_ref);
681                 init_completion(&priv->comp);
682         }
683
684         kref_get(&priv->dma_ref);
685         mutex_unlock(&priv->dma_lock);
686         return 0;
687 }
688
689 static void put_dma_channel(struct mport_cdev_priv *priv)
690 {
691         kref_put(&priv->dma_ref, mport_release_dma);
692 }
693
694 /*
695  * DMA transfer functions
696  */
697 static int do_dma_request(struct mport_dma_req *req,
698                           struct rio_transfer_io *xfer,
699                           enum rio_transfer_sync sync, int nents)
700 {
701         struct mport_cdev_priv *priv;
702         struct sg_table *sgt;
703         struct dma_chan *chan;
704         struct dma_async_tx_descriptor *tx;
705         dma_cookie_t cookie;
706         unsigned long tmo = msecs_to_jiffies(dma_timeout);
707         enum dma_transfer_direction dir;
708         long wret;
709         int ret = 0;
710
711         priv = req->priv;
712         sgt = &req->sgt;
713
714         chan = priv->dmach;
715         dir = (req->dir == DMA_FROM_DEVICE) ? DMA_DEV_TO_MEM : DMA_MEM_TO_DEV;
716
717         rmcd_debug(DMA, "%s(%d) uses %s for DMA_%s",
718                    current->comm, task_pid_nr(current),
719                    dev_name(&chan->dev->device),
720                    (dir == DMA_DEV_TO_MEM)?"READ":"WRITE");
721
722         /* Initialize DMA transaction request */
723         tx = prep_dma_xfer(chan, xfer, sgt, nents, dir,
724                            DMA_CTRL_ACK | DMA_PREP_INTERRUPT);
725
726         if (!tx) {
727                 rmcd_debug(DMA, "prep error for %s A:0x%llx L:0x%llx",
728                         (dir == DMA_DEV_TO_MEM)?"READ":"WRITE",
729                         xfer->rio_addr, xfer->length);
730                 ret = -EIO;
731                 goto err_out;
732         } else if (IS_ERR(tx)) {
733                 ret = PTR_ERR(tx);
734                 rmcd_debug(DMA, "prep error %d for %s A:0x%llx L:0x%llx", ret,
735                         (dir == DMA_DEV_TO_MEM)?"READ":"WRITE",
736                         xfer->rio_addr, xfer->length);
737                 goto err_out;
738         }
739
740         tx->callback = dma_xfer_callback;
741         tx->callback_param = req;
742
743         req->status = DMA_IN_PROGRESS;
744         kref_get(&req->refcount);
745
746         cookie = dmaengine_submit(tx);
747         req->cookie = cookie;
748
749         rmcd_debug(DMA, "pid=%d DMA_%s tx_cookie = %d", task_pid_nr(current),
750                    (dir == DMA_DEV_TO_MEM)?"READ":"WRITE", cookie);
751
752         if (dma_submit_error(cookie)) {
753                 rmcd_error("submit err=%d (addr:0x%llx len:0x%llx)",
754                            cookie, xfer->rio_addr, xfer->length);
755                 kref_put(&req->refcount, dma_req_free);
756                 ret = -EIO;
757                 goto err_out;
758         }
759
760         dma_async_issue_pending(chan);
761
762         if (sync == RIO_TRANSFER_ASYNC) {
763                 spin_lock(&priv->req_lock);
764                 list_add_tail(&req->node, &priv->async_list);
765                 spin_unlock(&priv->req_lock);
766                 return cookie;
767         } else if (sync == RIO_TRANSFER_FAF)
768                 return 0;
769
770         wret = wait_for_completion_interruptible_timeout(&req->req_comp, tmo);
771
772         if (wret == 0) {
773                 /* Timeout on wait occurred */
774                 rmcd_error("%s(%d) timed out waiting for DMA_%s %d",
775                        current->comm, task_pid_nr(current),
776                        (dir == DMA_DEV_TO_MEM)?"READ":"WRITE", cookie);
777                 return -ETIMEDOUT;
778         } else if (wret == -ERESTARTSYS) {
779                 /* Wait_for_completion was interrupted by a signal but DMA may
780                  * be in progress
781                  */
782                 rmcd_error("%s(%d) wait for DMA_%s %d was interrupted",
783                         current->comm, task_pid_nr(current),
784                         (dir == DMA_DEV_TO_MEM)?"READ":"WRITE", cookie);
785                 return -EINTR;
786         }
787
788         if (req->status != DMA_COMPLETE) {
789                 /* DMA transaction completion was signaled with error */
790                 rmcd_error("%s(%d) DMA_%s %d completed with status %d (ret=%d)",
791                         current->comm, task_pid_nr(current),
792                         (dir == DMA_DEV_TO_MEM)?"READ":"WRITE",
793                         cookie, req->status, ret);
794                 ret = -EIO;
795         }
796
797 err_out:
798         return ret;
799 }
800
801 /*
802  * rio_dma_transfer() - Perform RapidIO DMA data transfer to/from
803  *                      the remote RapidIO device
804  * @filp: file pointer associated with the call
805  * @transfer_mode: DMA transfer mode
806  * @sync: synchronization mode
807  * @dir: DMA transfer direction (DMA_MEM_TO_DEV = write OR
808  *                               DMA_DEV_TO_MEM = read)
809  * @xfer: data transfer descriptor structure
810  */
811 static int
812 rio_dma_transfer(struct file *filp, u32 transfer_mode,
813                  enum rio_transfer_sync sync, enum dma_data_direction dir,
814                  struct rio_transfer_io *xfer)
815 {
816         struct mport_cdev_priv *priv = filp->private_data;
817         unsigned long nr_pages = 0;
818         struct page **page_list = NULL;
819         struct mport_dma_req *req;
820         struct mport_dev *md = priv->md;
821         struct dma_chan *chan;
822         int i, ret;
823         int nents;
824
825         if (xfer->length == 0)
826                 return -EINVAL;
827         req = kzalloc(sizeof(*req), GFP_KERNEL);
828         if (!req)
829                 return -ENOMEM;
830
831         ret = get_dma_channel(priv);
832         if (ret) {
833                 kfree(req);
834                 return ret;
835         }
836         chan = priv->dmach;
837
838         kref_init(&req->refcount);
839         init_completion(&req->req_comp);
840         req->dir = dir;
841         req->filp = filp;
842         req->priv = priv;
843         req->dmach = chan;
844         req->sync = sync;
845
846         /*
847          * If parameter loc_addr != NULL, we are transferring data from/to
848          * data buffer allocated in user-space: lock in memory user-space
849          * buffer pages and build an SG table for DMA transfer request
850          *
851          * Otherwise (loc_addr == NULL) contiguous kernel-space buffer is
852          * used for DMA data transfers: build single entry SG table using
853          * offset within the internal buffer specified by handle parameter.
854          */
855         if (xfer->loc_addr) {
856                 unsigned int offset;
857                 long pinned;
858
859                 offset = lower_32_bits(offset_in_page(xfer->loc_addr));
860                 nr_pages = PAGE_ALIGN(xfer->length + offset) >> PAGE_SHIFT;
861
862                 page_list = kmalloc_array(nr_pages,
863                                           sizeof(*page_list), GFP_KERNEL);
864                 if (page_list == NULL) {
865                         ret = -ENOMEM;
866                         goto err_req;
867                 }
868
869                 pinned = get_user_pages_fast(
870                                 (unsigned long)xfer->loc_addr & PAGE_MASK,
871                                 nr_pages, dir == DMA_FROM_DEVICE, page_list);
872
873                 if (pinned != nr_pages) {
874                         if (pinned < 0) {
875                                 rmcd_error("get_user_pages_unlocked err=%ld",
876                                            pinned);
877                                 nr_pages = 0;
878                         } else {
879                                 rmcd_error("pinned %ld out of %ld pages",
880                                            pinned, nr_pages);
881                                 /*
882                                  * Set nr_pages up to mean "how many pages to unpin, in
883                                  * the error handler:
884                                  */
885                                 nr_pages = pinned;
886                         }
887                         ret = -EFAULT;
888                         goto err_pg;
889                 }
890
891                 ret = sg_alloc_table_from_pages(&req->sgt, page_list, nr_pages,
892                                         offset, xfer->length, GFP_KERNEL);
893                 if (ret) {
894                         rmcd_error("sg_alloc_table failed with err=%d", ret);
895                         goto err_pg;
896                 }
897
898                 req->page_list = page_list;
899                 req->nr_pages = nr_pages;
900         } else {
901                 dma_addr_t baddr;
902                 struct rio_mport_mapping *map;
903
904                 baddr = (dma_addr_t)xfer->handle;
905
906                 mutex_lock(&md->buf_mutex);
907                 list_for_each_entry(map, &md->mappings, node) {
908                         if (baddr >= map->phys_addr &&
909                             baddr < (map->phys_addr + map->size)) {
910                                 kref_get(&map->ref);
911                                 req->map = map;
912                                 break;
913                         }
914                 }
915                 mutex_unlock(&md->buf_mutex);
916
917                 if (req->map == NULL) {
918                         ret = -ENOMEM;
919                         goto err_req;
920                 }
921
922                 if (xfer->length + xfer->offset > map->size) {
923                         ret = -EINVAL;
924                         goto err_req;
925                 }
926
927                 ret = sg_alloc_table(&req->sgt, 1, GFP_KERNEL);
928                 if (unlikely(ret)) {
929                         rmcd_error("sg_alloc_table failed for internal buf");
930                         goto err_req;
931                 }
932
933                 sg_set_buf(req->sgt.sgl,
934                            map->virt_addr + (baddr - map->phys_addr) +
935                                 xfer->offset, xfer->length);
936         }
937
938         nents = dma_map_sg(chan->device->dev,
939                            req->sgt.sgl, req->sgt.nents, dir);
940         if (nents == 0) {
941                 rmcd_error("Failed to map SG list");
942                 ret = -EFAULT;
943                 goto err_pg;
944         }
945
946         ret = do_dma_request(req, xfer, sync, nents);
947
948         if (ret >= 0) {
949                 if (sync == RIO_TRANSFER_ASYNC)
950                         return ret; /* return ASYNC cookie */
951         } else {
952                 rmcd_debug(DMA, "do_dma_request failed with err=%d", ret);
953         }
954
955 err_pg:
956         if (!req->page_list) {
957                 for (i = 0; i < nr_pages; i++)
958                         put_page(page_list[i]);
959                 kfree(page_list);
960         }
961 err_req:
962         kref_put(&req->refcount, dma_req_free);
963         return ret;
964 }
965
966 static int rio_mport_transfer_ioctl(struct file *filp, void __user *arg)
967 {
968         struct mport_cdev_priv *priv = filp->private_data;
969         struct rio_transaction transaction;
970         struct rio_transfer_io *transfer;
971         enum dma_data_direction dir;
972         int i, ret = 0;
973
974         if (unlikely(copy_from_user(&transaction, arg, sizeof(transaction))))
975                 return -EFAULT;
976
977         if (transaction.count != 1) /* only single transfer for now */
978                 return -EINVAL;
979
980         if ((transaction.transfer_mode &
981              priv->md->properties.transfer_mode) == 0)
982                 return -ENODEV;
983
984         transfer = vmalloc(array_size(sizeof(*transfer), transaction.count));
985         if (!transfer)
986                 return -ENOMEM;
987
988         if (unlikely(copy_from_user(transfer,
989                                     (void __user *)(uintptr_t)transaction.block,
990                                     transaction.count * sizeof(*transfer)))) {
991                 ret = -EFAULT;
992                 goto out_free;
993         }
994
995         dir = (transaction.dir == RIO_TRANSFER_DIR_READ) ?
996                                         DMA_FROM_DEVICE : DMA_TO_DEVICE;
997         for (i = 0; i < transaction.count && ret == 0; i++)
998                 ret = rio_dma_transfer(filp, transaction.transfer_mode,
999                         transaction.sync, dir, &transfer[i]);
1000
1001         if (unlikely(copy_to_user((void __user *)(uintptr_t)transaction.block,
1002                                   transfer,
1003                                   transaction.count * sizeof(*transfer))))
1004                 ret = -EFAULT;
1005
1006 out_free:
1007         vfree(transfer);
1008
1009         return ret;
1010 }
1011
1012 static int rio_mport_wait_for_async_dma(struct file *filp, void __user *arg)
1013 {
1014         struct mport_cdev_priv *priv;
1015         struct rio_async_tx_wait w_param;
1016         struct mport_dma_req *req;
1017         dma_cookie_t cookie;
1018         unsigned long tmo;
1019         long wret;
1020         int found = 0;
1021         int ret;
1022
1023         priv = (struct mport_cdev_priv *)filp->private_data;
1024
1025         if (unlikely(copy_from_user(&w_param, arg, sizeof(w_param))))
1026                 return -EFAULT;
1027
1028         cookie = w_param.token;
1029         if (w_param.timeout)
1030                 tmo = msecs_to_jiffies(w_param.timeout);
1031         else /* Use default DMA timeout */
1032                 tmo = msecs_to_jiffies(dma_timeout);
1033
1034         spin_lock(&priv->req_lock);
1035         list_for_each_entry(req, &priv->async_list, node) {
1036                 if (req->cookie == cookie) {
1037                         list_del(&req->node);
1038                         found = 1;
1039                         break;
1040                 }
1041         }
1042         spin_unlock(&priv->req_lock);
1043
1044         if (!found)
1045                 return -EAGAIN;
1046
1047         wret = wait_for_completion_interruptible_timeout(&req->req_comp, tmo);
1048
1049         if (wret == 0) {
1050                 /* Timeout on wait occurred */
1051                 rmcd_error("%s(%d) timed out waiting for ASYNC DMA_%s",
1052                        current->comm, task_pid_nr(current),
1053                        (req->dir == DMA_FROM_DEVICE)?"READ":"WRITE");
1054                 ret = -ETIMEDOUT;
1055                 goto err_tmo;
1056         } else if (wret == -ERESTARTSYS) {
1057                 /* Wait_for_completion was interrupted by a signal but DMA may
1058                  * be still in progress
1059                  */
1060                 rmcd_error("%s(%d) wait for ASYNC DMA_%s was interrupted",
1061                         current->comm, task_pid_nr(current),
1062                         (req->dir == DMA_FROM_DEVICE)?"READ":"WRITE");
1063                 ret = -EINTR;
1064                 goto err_tmo;
1065         }
1066
1067         if (req->status != DMA_COMPLETE) {
1068                 /* DMA transaction completion signaled with transfer error */
1069                 rmcd_error("%s(%d) ASYNC DMA_%s completion with status %d",
1070                         current->comm, task_pid_nr(current),
1071                         (req->dir == DMA_FROM_DEVICE)?"READ":"WRITE",
1072                         req->status);
1073                 ret = -EIO;
1074         } else
1075                 ret = 0;
1076
1077         if (req->status != DMA_IN_PROGRESS && req->status != DMA_PAUSED)
1078                 kref_put(&req->refcount, dma_req_free);
1079
1080         return ret;
1081
1082 err_tmo:
1083         /* Return request back into async queue */
1084         spin_lock(&priv->req_lock);
1085         list_add_tail(&req->node, &priv->async_list);
1086         spin_unlock(&priv->req_lock);
1087         return ret;
1088 }
1089
1090 static int rio_mport_create_dma_mapping(struct mport_dev *md, struct file *filp,
1091                         u64 size, struct rio_mport_mapping **mapping)
1092 {
1093         struct rio_mport_mapping *map;
1094
1095         map = kzalloc(sizeof(*map), GFP_KERNEL);
1096         if (map == NULL)
1097                 return -ENOMEM;
1098
1099         map->virt_addr = dma_alloc_coherent(md->mport->dev.parent, size,
1100                                             &map->phys_addr, GFP_KERNEL);
1101         if (map->virt_addr == NULL) {
1102                 kfree(map);
1103                 return -ENOMEM;
1104         }
1105
1106         map->dir = MAP_DMA;
1107         map->size = size;
1108         map->filp = filp;
1109         map->md = md;
1110         kref_init(&map->ref);
1111         mutex_lock(&md->buf_mutex);
1112         list_add_tail(&map->node, &md->mappings);
1113         mutex_unlock(&md->buf_mutex);
1114         *mapping = map;
1115
1116         return 0;
1117 }
1118
1119 static int rio_mport_alloc_dma(struct file *filp, void __user *arg)
1120 {
1121         struct mport_cdev_priv *priv = filp->private_data;
1122         struct mport_dev *md = priv->md;
1123         struct rio_dma_mem map;
1124         struct rio_mport_mapping *mapping = NULL;
1125         int ret;
1126
1127         if (unlikely(copy_from_user(&map, arg, sizeof(map))))
1128                 return -EFAULT;
1129
1130         ret = rio_mport_create_dma_mapping(md, filp, map.length, &mapping);
1131         if (ret)
1132                 return ret;
1133
1134         map.dma_handle = mapping->phys_addr;
1135
1136         if (unlikely(copy_to_user(arg, &map, sizeof(map)))) {
1137                 mutex_lock(&md->buf_mutex);
1138                 kref_put(&mapping->ref, mport_release_mapping);
1139                 mutex_unlock(&md->buf_mutex);
1140                 return -EFAULT;
1141         }
1142
1143         return 0;
1144 }
1145
1146 static int rio_mport_free_dma(struct file *filp, void __user *arg)
1147 {
1148         struct mport_cdev_priv *priv = filp->private_data;
1149         struct mport_dev *md = priv->md;
1150         u64 handle;
1151         int ret = -EFAULT;
1152         struct rio_mport_mapping *map, *_map;
1153
1154         if (copy_from_user(&handle, arg, sizeof(handle)))
1155                 return -EFAULT;
1156         rmcd_debug(EXIT, "filp=%p", filp);
1157
1158         mutex_lock(&md->buf_mutex);
1159         list_for_each_entry_safe(map, _map, &md->mappings, node) {
1160                 if (map->dir == MAP_DMA && map->phys_addr == handle &&
1161                     map->filp == filp) {
1162                         kref_put(&map->ref, mport_release_mapping);
1163                         ret = 0;
1164                         break;
1165                 }
1166         }
1167         mutex_unlock(&md->buf_mutex);
1168
1169         if (ret == -EFAULT) {
1170                 rmcd_debug(DMA, "ERR no matching mapping");
1171                 return ret;
1172         }
1173
1174         return 0;
1175 }
1176 #else
1177 static int rio_mport_transfer_ioctl(struct file *filp, void *arg)
1178 {
1179         return -ENODEV;
1180 }
1181
1182 static int rio_mport_wait_for_async_dma(struct file *filp, void __user *arg)
1183 {
1184         return -ENODEV;
1185 }
1186
1187 static int rio_mport_alloc_dma(struct file *filp, void __user *arg)
1188 {
1189         return -ENODEV;
1190 }
1191
1192 static int rio_mport_free_dma(struct file *filp, void __user *arg)
1193 {
1194         return -ENODEV;
1195 }
1196 #endif /* CONFIG_RAPIDIO_DMA_ENGINE */
1197
1198 /*
1199  * Inbound/outbound memory mapping functions
1200  */
1201
1202 static int
1203 rio_mport_create_inbound_mapping(struct mport_dev *md, struct file *filp,
1204                                 u64 raddr, u64 size,
1205                                 struct rio_mport_mapping **mapping)
1206 {
1207         struct rio_mport *mport = md->mport;
1208         struct rio_mport_mapping *map;
1209         int ret;
1210
1211         /* rio_map_inb_region() accepts u32 size */
1212         if (size > 0xffffffff)
1213                 return -EINVAL;
1214
1215         map = kzalloc(sizeof(*map), GFP_KERNEL);
1216         if (map == NULL)
1217                 return -ENOMEM;
1218
1219         map->virt_addr = dma_alloc_coherent(mport->dev.parent, size,
1220                                             &map->phys_addr, GFP_KERNEL);
1221         if (map->virt_addr == NULL) {
1222                 ret = -ENOMEM;
1223                 goto err_dma_alloc;
1224         }
1225
1226         if (raddr == RIO_MAP_ANY_ADDR)
1227                 raddr = map->phys_addr;
1228         ret = rio_map_inb_region(mport, map->phys_addr, raddr, (u32)size, 0);
1229         if (ret < 0)
1230                 goto err_map_inb;
1231
1232         map->dir = MAP_INBOUND;
1233         map->rio_addr = raddr;
1234         map->size = size;
1235         map->filp = filp;
1236         map->md = md;
1237         kref_init(&map->ref);
1238         mutex_lock(&md->buf_mutex);
1239         list_add_tail(&map->node, &md->mappings);
1240         mutex_unlock(&md->buf_mutex);
1241         *mapping = map;
1242         return 0;
1243
1244 err_map_inb:
1245         dma_free_coherent(mport->dev.parent, size,
1246                           map->virt_addr, map->phys_addr);
1247 err_dma_alloc:
1248         kfree(map);
1249         return ret;
1250 }
1251
1252 static int
1253 rio_mport_get_inbound_mapping(struct mport_dev *md, struct file *filp,
1254                               u64 raddr, u64 size,
1255                               struct rio_mport_mapping **mapping)
1256 {
1257         struct rio_mport_mapping *map;
1258         int err = -ENOMEM;
1259
1260         if (raddr == RIO_MAP_ANY_ADDR)
1261                 goto get_new;
1262
1263         mutex_lock(&md->buf_mutex);
1264         list_for_each_entry(map, &md->mappings, node) {
1265                 if (map->dir != MAP_INBOUND)
1266                         continue;
1267                 if (raddr == map->rio_addr && size == map->size) {
1268                         /* allow exact match only */
1269                         *mapping = map;
1270                         err = 0;
1271                         break;
1272                 } else if (raddr < (map->rio_addr + map->size - 1) &&
1273                            (raddr + size) > map->rio_addr) {
1274                         err = -EBUSY;
1275                         break;
1276                 }
1277         }
1278         mutex_unlock(&md->buf_mutex);
1279
1280         if (err != -ENOMEM)
1281                 return err;
1282 get_new:
1283         /* not found, create new */
1284         return rio_mport_create_inbound_mapping(md, filp, raddr, size, mapping);
1285 }
1286
1287 static int rio_mport_map_inbound(struct file *filp, void __user *arg)
1288 {
1289         struct mport_cdev_priv *priv = filp->private_data;
1290         struct mport_dev *md = priv->md;
1291         struct rio_mmap map;
1292         struct rio_mport_mapping *mapping = NULL;
1293         int ret;
1294
1295         if (!md->mport->ops->map_inb)
1296                 return -EPROTONOSUPPORT;
1297         if (unlikely(copy_from_user(&map, arg, sizeof(map))))
1298                 return -EFAULT;
1299
1300         rmcd_debug(IBW, "%s filp=%p", dev_name(&priv->md->dev), filp);
1301
1302         ret = rio_mport_get_inbound_mapping(md, filp, map.rio_addr,
1303                                             map.length, &mapping);
1304         if (ret)
1305                 return ret;
1306
1307         map.handle = mapping->phys_addr;
1308         map.rio_addr = mapping->rio_addr;
1309
1310         if (unlikely(copy_to_user(arg, &map, sizeof(map)))) {
1311                 /* Delete mapping if it was created by this request */
1312                 if (ret == 0 && mapping->filp == filp) {
1313                         mutex_lock(&md->buf_mutex);
1314                         kref_put(&mapping->ref, mport_release_mapping);
1315                         mutex_unlock(&md->buf_mutex);
1316                 }
1317                 return -EFAULT;
1318         }
1319
1320         return 0;
1321 }
1322
1323 /*
1324  * rio_mport_inbound_free() - unmap from RapidIO address space and free
1325  *                    previously allocated inbound DMA coherent buffer
1326  * @priv: driver private data
1327  * @arg:  buffer handle returned by allocation routine
1328  */
1329 static int rio_mport_inbound_free(struct file *filp, void __user *arg)
1330 {
1331         struct mport_cdev_priv *priv = filp->private_data;
1332         struct mport_dev *md = priv->md;
1333         u64 handle;
1334         struct rio_mport_mapping *map, *_map;
1335
1336         rmcd_debug(IBW, "%s filp=%p", dev_name(&priv->md->dev), filp);
1337
1338         if (!md->mport->ops->unmap_inb)
1339                 return -EPROTONOSUPPORT;
1340
1341         if (copy_from_user(&handle, arg, sizeof(handle)))
1342                 return -EFAULT;
1343
1344         mutex_lock(&md->buf_mutex);
1345         list_for_each_entry_safe(map, _map, &md->mappings, node) {
1346                 if (map->dir == MAP_INBOUND && map->phys_addr == handle) {
1347                         if (map->filp == filp) {
1348                                 map->filp = NULL;
1349                                 kref_put(&map->ref, mport_release_mapping);
1350                         }
1351                         break;
1352                 }
1353         }
1354         mutex_unlock(&md->buf_mutex);
1355
1356         return 0;
1357 }
1358
1359 /*
1360  * maint_port_idx_get() - Get the port index of the mport instance
1361  * @priv: driver private data
1362  * @arg:  port index
1363  */
1364 static int maint_port_idx_get(struct mport_cdev_priv *priv, void __user *arg)
1365 {
1366         struct mport_dev *md = priv->md;
1367         u32 port_idx = md->mport->index;
1368
1369         rmcd_debug(MPORT, "port_index=%d", port_idx);
1370
1371         if (copy_to_user(arg, &port_idx, sizeof(port_idx)))
1372                 return -EFAULT;
1373
1374         return 0;
1375 }
1376
1377 static int rio_mport_add_event(struct mport_cdev_priv *priv,
1378                                struct rio_event *event)
1379 {
1380         int overflow;
1381
1382         if (!(priv->event_mask & event->header))
1383                 return -EACCES;
1384
1385         spin_lock(&priv->fifo_lock);
1386         overflow = kfifo_avail(&priv->event_fifo) < sizeof(*event)
1387                 || kfifo_in(&priv->event_fifo, (unsigned char *)event,
1388                         sizeof(*event)) != sizeof(*event);
1389         spin_unlock(&priv->fifo_lock);
1390
1391         wake_up_interruptible(&priv->event_rx_wait);
1392
1393         if (overflow) {
1394                 dev_warn(&priv->md->dev, DRV_NAME ": event fifo overflow\n");
1395                 return -EBUSY;
1396         }
1397
1398         return 0;
1399 }
1400
1401 static void rio_mport_doorbell_handler(struct rio_mport *mport, void *dev_id,
1402                                        u16 src, u16 dst, u16 info)
1403 {
1404         struct mport_dev *data = dev_id;
1405         struct mport_cdev_priv *priv;
1406         struct rio_mport_db_filter *db_filter;
1407         struct rio_event event;
1408         int handled;
1409
1410         event.header = RIO_DOORBELL;
1411         event.u.doorbell.rioid = src;
1412         event.u.doorbell.payload = info;
1413
1414         handled = 0;
1415         spin_lock(&data->db_lock);
1416         list_for_each_entry(db_filter, &data->doorbells, data_node) {
1417                 if (((db_filter->filter.rioid == RIO_INVALID_DESTID ||
1418                       db_filter->filter.rioid == src)) &&
1419                       info >= db_filter->filter.low &&
1420                       info <= db_filter->filter.high) {
1421                         priv = db_filter->priv;
1422                         rio_mport_add_event(priv, &event);
1423                         handled = 1;
1424                 }
1425         }
1426         spin_unlock(&data->db_lock);
1427
1428         if (!handled)
1429                 dev_warn(&data->dev,
1430                         "%s: spurious DB received from 0x%x, info=0x%04x\n",
1431                         __func__, src, info);
1432 }
1433
1434 static int rio_mport_add_db_filter(struct mport_cdev_priv *priv,
1435                                    void __user *arg)
1436 {
1437         struct mport_dev *md = priv->md;
1438         struct rio_mport_db_filter *db_filter;
1439         struct rio_doorbell_filter filter;
1440         unsigned long flags;
1441         int ret;
1442
1443         if (copy_from_user(&filter, arg, sizeof(filter)))
1444                 return -EFAULT;
1445
1446         if (filter.low > filter.high)
1447                 return -EINVAL;
1448
1449         ret = rio_request_inb_dbell(md->mport, md, filter.low, filter.high,
1450                                     rio_mport_doorbell_handler);
1451         if (ret) {
1452                 rmcd_error("%s failed to register IBDB, err=%d",
1453                            dev_name(&md->dev), ret);
1454                 return ret;
1455         }
1456
1457         db_filter = kzalloc(sizeof(*db_filter), GFP_KERNEL);
1458         if (db_filter == NULL) {
1459                 rio_release_inb_dbell(md->mport, filter.low, filter.high);
1460                 return -ENOMEM;
1461         }
1462
1463         db_filter->filter = filter;
1464         db_filter->priv = priv;
1465         spin_lock_irqsave(&md->db_lock, flags);
1466         list_add_tail(&db_filter->priv_node, &priv->db_filters);
1467         list_add_tail(&db_filter->data_node, &md->doorbells);
1468         spin_unlock_irqrestore(&md->db_lock, flags);
1469
1470         return 0;
1471 }
1472
1473 static void rio_mport_delete_db_filter(struct rio_mport_db_filter *db_filter)
1474 {
1475         list_del(&db_filter->data_node);
1476         list_del(&db_filter->priv_node);
1477         kfree(db_filter);
1478 }
1479
1480 static int rio_mport_remove_db_filter(struct mport_cdev_priv *priv,
1481                                       void __user *arg)
1482 {
1483         struct rio_mport_db_filter *db_filter;
1484         struct rio_doorbell_filter filter;
1485         unsigned long flags;
1486         int ret = -EINVAL;
1487
1488         if (copy_from_user(&filter, arg, sizeof(filter)))
1489                 return -EFAULT;
1490
1491         if (filter.low > filter.high)
1492                 return -EINVAL;
1493
1494         spin_lock_irqsave(&priv->md->db_lock, flags);
1495         list_for_each_entry(db_filter, &priv->db_filters, priv_node) {
1496                 if (db_filter->filter.rioid == filter.rioid &&
1497                     db_filter->filter.low == filter.low &&
1498                     db_filter->filter.high == filter.high) {
1499                         rio_mport_delete_db_filter(db_filter);
1500                         ret = 0;
1501                         break;
1502                 }
1503         }
1504         spin_unlock_irqrestore(&priv->md->db_lock, flags);
1505
1506         if (!ret)
1507                 rio_release_inb_dbell(priv->md->mport, filter.low, filter.high);
1508
1509         return ret;
1510 }
1511
1512 static int rio_mport_match_pw(union rio_pw_msg *msg,
1513                               struct rio_pw_filter *filter)
1514 {
1515         if ((msg->em.comptag & filter->mask) < filter->low ||
1516                 (msg->em.comptag & filter->mask) > filter->high)
1517                 return 0;
1518         return 1;
1519 }
1520
1521 static int rio_mport_pw_handler(struct rio_mport *mport, void *context,
1522                                 union rio_pw_msg *msg, int step)
1523 {
1524         struct mport_dev *md = context;
1525         struct mport_cdev_priv *priv;
1526         struct rio_mport_pw_filter *pw_filter;
1527         struct rio_event event;
1528         int handled;
1529
1530         event.header = RIO_PORTWRITE;
1531         memcpy(event.u.portwrite.payload, msg->raw, RIO_PW_MSG_SIZE);
1532
1533         handled = 0;
1534         spin_lock(&md->pw_lock);
1535         list_for_each_entry(pw_filter, &md->portwrites, md_node) {
1536                 if (rio_mport_match_pw(msg, &pw_filter->filter)) {
1537                         priv = pw_filter->priv;
1538                         rio_mport_add_event(priv, &event);
1539                         handled = 1;
1540                 }
1541         }
1542         spin_unlock(&md->pw_lock);
1543
1544         if (!handled) {
1545                 printk_ratelimited(KERN_WARNING DRV_NAME
1546                         ": mport%d received spurious PW from 0x%08x\n",
1547                         mport->id, msg->em.comptag);
1548         }
1549
1550         return 0;
1551 }
1552
1553 static int rio_mport_add_pw_filter(struct mport_cdev_priv *priv,
1554                                    void __user *arg)
1555 {
1556         struct mport_dev *md = priv->md;
1557         struct rio_mport_pw_filter *pw_filter;
1558         struct rio_pw_filter filter;
1559         unsigned long flags;
1560         int hadd = 0;
1561
1562         if (copy_from_user(&filter, arg, sizeof(filter)))
1563                 return -EFAULT;
1564
1565         pw_filter = kzalloc(sizeof(*pw_filter), GFP_KERNEL);
1566         if (pw_filter == NULL)
1567                 return -ENOMEM;
1568
1569         pw_filter->filter = filter;
1570         pw_filter->priv = priv;
1571         spin_lock_irqsave(&md->pw_lock, flags);
1572         if (list_empty(&md->portwrites))
1573                 hadd = 1;
1574         list_add_tail(&pw_filter->priv_node, &priv->pw_filters);
1575         list_add_tail(&pw_filter->md_node, &md->portwrites);
1576         spin_unlock_irqrestore(&md->pw_lock, flags);
1577
1578         if (hadd) {
1579                 int ret;
1580
1581                 ret = rio_add_mport_pw_handler(md->mport, md,
1582                                                rio_mport_pw_handler);
1583                 if (ret) {
1584                         dev_err(&md->dev,
1585                                 "%s: failed to add IB_PW handler, err=%d\n",
1586                                 __func__, ret);
1587                         return ret;
1588                 }
1589                 rio_pw_enable(md->mport, 1);
1590         }
1591
1592         return 0;
1593 }
1594
1595 static void rio_mport_delete_pw_filter(struct rio_mport_pw_filter *pw_filter)
1596 {
1597         list_del(&pw_filter->md_node);
1598         list_del(&pw_filter->priv_node);
1599         kfree(pw_filter);
1600 }
1601
1602 static int rio_mport_match_pw_filter(struct rio_pw_filter *a,
1603                                      struct rio_pw_filter *b)
1604 {
1605         if ((a->mask == b->mask) && (a->low == b->low) && (a->high == b->high))
1606                 return 1;
1607         return 0;
1608 }
1609
1610 static int rio_mport_remove_pw_filter(struct mport_cdev_priv *priv,
1611                                       void __user *arg)
1612 {
1613         struct mport_dev *md = priv->md;
1614         struct rio_mport_pw_filter *pw_filter;
1615         struct rio_pw_filter filter;
1616         unsigned long flags;
1617         int ret = -EINVAL;
1618         int hdel = 0;
1619
1620         if (copy_from_user(&filter, arg, sizeof(filter)))
1621                 return -EFAULT;
1622
1623         spin_lock_irqsave(&md->pw_lock, flags);
1624         list_for_each_entry(pw_filter, &priv->pw_filters, priv_node) {
1625                 if (rio_mport_match_pw_filter(&pw_filter->filter, &filter)) {
1626                         rio_mport_delete_pw_filter(pw_filter);
1627                         ret = 0;
1628                         break;
1629                 }
1630         }
1631
1632         if (list_empty(&md->portwrites))
1633                 hdel = 1;
1634         spin_unlock_irqrestore(&md->pw_lock, flags);
1635
1636         if (hdel) {
1637                 rio_del_mport_pw_handler(md->mport, priv->md,
1638                                          rio_mport_pw_handler);
1639                 rio_pw_enable(md->mport, 0);
1640         }
1641
1642         return ret;
1643 }
1644
1645 /*
1646  * rio_release_dev - release routine for kernel RIO device object
1647  * @dev: kernel device object associated with a RIO device structure
1648  *
1649  * Frees a RIO device struct associated a RIO device struct.
1650  * The RIO device struct is freed.
1651  */
1652 static void rio_release_dev(struct device *dev)
1653 {
1654         struct rio_dev *rdev;
1655
1656         rdev = to_rio_dev(dev);
1657         pr_info(DRV_PREFIX "%s: %s\n", __func__, rio_name(rdev));
1658         kfree(rdev);
1659 }
1660
1661
1662 static void rio_release_net(struct device *dev)
1663 {
1664         struct rio_net *net;
1665
1666         net = to_rio_net(dev);
1667         rmcd_debug(RDEV, "net_%d", net->id);
1668         kfree(net);
1669 }
1670
1671
1672 /*
1673  * rio_mport_add_riodev - creates a kernel RIO device object
1674  *
1675  * Allocates a RIO device data structure and initializes required fields based
1676  * on device's configuration space contents.
1677  * If the device has switch capabilities, then a switch specific portion is
1678  * allocated and configured.
1679  */
1680 static int rio_mport_add_riodev(struct mport_cdev_priv *priv,
1681                                    void __user *arg)
1682 {
1683         struct mport_dev *md = priv->md;
1684         struct rio_rdev_info dev_info;
1685         struct rio_dev *rdev;
1686         struct rio_switch *rswitch = NULL;
1687         struct rio_mport *mport;
1688         struct device *dev;
1689         size_t size;
1690         u32 rval;
1691         u32 swpinfo = 0;
1692         u16 destid;
1693         u8 hopcount;
1694         int err;
1695
1696         if (copy_from_user(&dev_info, arg, sizeof(dev_info)))
1697                 return -EFAULT;
1698         dev_info.name[sizeof(dev_info.name) - 1] = '\0';
1699
1700         rmcd_debug(RDEV, "name:%s ct:0x%x did:0x%x hc:0x%x", dev_info.name,
1701                    dev_info.comptag, dev_info.destid, dev_info.hopcount);
1702
1703         dev = bus_find_device_by_name(&rio_bus_type, NULL, dev_info.name);
1704         if (dev) {
1705                 rmcd_debug(RDEV, "device %s already exists", dev_info.name);
1706                 put_device(dev);
1707                 return -EEXIST;
1708         }
1709
1710         size = sizeof(*rdev);
1711         mport = md->mport;
1712         destid = dev_info.destid;
1713         hopcount = dev_info.hopcount;
1714
1715         if (rio_mport_read_config_32(mport, destid, hopcount,
1716                                      RIO_PEF_CAR, &rval))
1717                 return -EIO;
1718
1719         if (rval & RIO_PEF_SWITCH) {
1720                 rio_mport_read_config_32(mport, destid, hopcount,
1721                                          RIO_SWP_INFO_CAR, &swpinfo);
1722                 size += (RIO_GET_TOTAL_PORTS(swpinfo) *
1723                          sizeof(rswitch->nextdev[0])) + sizeof(*rswitch);
1724         }
1725
1726         rdev = kzalloc(size, GFP_KERNEL);
1727         if (rdev == NULL)
1728                 return -ENOMEM;
1729
1730         if (mport->net == NULL) {
1731                 struct rio_net *net;
1732
1733                 net = rio_alloc_net(mport);
1734                 if (!net) {
1735                         err = -ENOMEM;
1736                         rmcd_debug(RDEV, "failed to allocate net object");
1737                         goto cleanup;
1738                 }
1739
1740                 net->id = mport->id;
1741                 net->hport = mport;
1742                 dev_set_name(&net->dev, "rnet_%d", net->id);
1743                 net->dev.parent = &mport->dev;
1744                 net->dev.release = rio_release_net;
1745                 err = rio_add_net(net);
1746                 if (err) {
1747                         rmcd_debug(RDEV, "failed to register net, err=%d", err);
1748                         kfree(net);
1749                         goto cleanup;
1750                 }
1751         }
1752
1753         rdev->net = mport->net;
1754         rdev->pef = rval;
1755         rdev->swpinfo = swpinfo;
1756         rio_mport_read_config_32(mport, destid, hopcount,
1757                                  RIO_DEV_ID_CAR, &rval);
1758         rdev->did = rval >> 16;
1759         rdev->vid = rval & 0xffff;
1760         rio_mport_read_config_32(mport, destid, hopcount, RIO_DEV_INFO_CAR,
1761                                  &rdev->device_rev);
1762         rio_mport_read_config_32(mport, destid, hopcount, RIO_ASM_ID_CAR,
1763                                  &rval);
1764         rdev->asm_did = rval >> 16;
1765         rdev->asm_vid = rval & 0xffff;
1766         rio_mport_read_config_32(mport, destid, hopcount, RIO_ASM_INFO_CAR,
1767                                  &rval);
1768         rdev->asm_rev = rval >> 16;
1769
1770         if (rdev->pef & RIO_PEF_EXT_FEATURES) {
1771                 rdev->efptr = rval & 0xffff;
1772                 rdev->phys_efptr = rio_mport_get_physefb(mport, 0, destid,
1773                                                 hopcount, &rdev->phys_rmap);
1774
1775                 rdev->em_efptr = rio_mport_get_feature(mport, 0, destid,
1776                                                 hopcount, RIO_EFB_ERR_MGMNT);
1777         }
1778
1779         rio_mport_read_config_32(mport, destid, hopcount, RIO_SRC_OPS_CAR,
1780                                  &rdev->src_ops);
1781         rio_mport_read_config_32(mport, destid, hopcount, RIO_DST_OPS_CAR,
1782                                  &rdev->dst_ops);
1783
1784         rdev->comp_tag = dev_info.comptag;
1785         rdev->destid = destid;
1786         /* hopcount is stored as specified by a caller, regardles of EP or SW */
1787         rdev->hopcount = hopcount;
1788
1789         if (rdev->pef & RIO_PEF_SWITCH) {
1790                 rswitch = rdev->rswitch;
1791                 rswitch->route_table = NULL;
1792         }
1793
1794         if (strlen(dev_info.name))
1795                 dev_set_name(&rdev->dev, "%s", dev_info.name);
1796         else if (rdev->pef & RIO_PEF_SWITCH)
1797                 dev_set_name(&rdev->dev, "%02x:s:%04x", mport->id,
1798                              rdev->comp_tag & RIO_CTAG_UDEVID);
1799         else
1800                 dev_set_name(&rdev->dev, "%02x:e:%04x", mport->id,
1801                              rdev->comp_tag & RIO_CTAG_UDEVID);
1802
1803         INIT_LIST_HEAD(&rdev->net_list);
1804         rdev->dev.parent = &mport->net->dev;
1805         rio_attach_device(rdev);
1806         rdev->dev.release = rio_release_dev;
1807
1808         if (rdev->dst_ops & RIO_DST_OPS_DOORBELL)
1809                 rio_init_dbell_res(&rdev->riores[RIO_DOORBELL_RESOURCE],
1810                                    0, 0xffff);
1811         err = rio_add_device(rdev);
1812         if (err)
1813                 goto cleanup;
1814         rio_dev_get(rdev);
1815
1816         return 0;
1817 cleanup:
1818         kfree(rdev);
1819         return err;
1820 }
1821
1822 static int rio_mport_del_riodev(struct mport_cdev_priv *priv, void __user *arg)
1823 {
1824         struct rio_rdev_info dev_info;
1825         struct rio_dev *rdev = NULL;
1826         struct device  *dev;
1827         struct rio_mport *mport;
1828         struct rio_net *net;
1829
1830         if (copy_from_user(&dev_info, arg, sizeof(dev_info)))
1831                 return -EFAULT;
1832         dev_info.name[sizeof(dev_info.name) - 1] = '\0';
1833
1834         mport = priv->md->mport;
1835
1836         /* If device name is specified, removal by name has priority */
1837         if (strlen(dev_info.name)) {
1838                 dev = bus_find_device_by_name(&rio_bus_type, NULL,
1839                                               dev_info.name);
1840                 if (dev)
1841                         rdev = to_rio_dev(dev);
1842         } else {
1843                 do {
1844                         rdev = rio_get_comptag(dev_info.comptag, rdev);
1845                         if (rdev && rdev->dev.parent == &mport->net->dev &&
1846                             rdev->destid == dev_info.destid &&
1847                             rdev->hopcount == dev_info.hopcount)
1848                                 break;
1849                 } while (rdev);
1850         }
1851
1852         if (!rdev) {
1853                 rmcd_debug(RDEV,
1854                         "device name:%s ct:0x%x did:0x%x hc:0x%x not found",
1855                         dev_info.name, dev_info.comptag, dev_info.destid,
1856                         dev_info.hopcount);
1857                 return -ENODEV;
1858         }
1859
1860         net = rdev->net;
1861         rio_dev_put(rdev);
1862         rio_del_device(rdev, RIO_DEVICE_SHUTDOWN);
1863
1864         if (list_empty(&net->devices)) {
1865                 rio_free_net(net);
1866                 mport->net = NULL;
1867         }
1868
1869         return 0;
1870 }
1871
1872 /*
1873  * Mport cdev management
1874  */
1875
1876 /*
1877  * mport_cdev_open() - Open character device (mport)
1878  */
1879 static int mport_cdev_open(struct inode *inode, struct file *filp)
1880 {
1881         int ret;
1882         int minor = iminor(inode);
1883         struct mport_dev *chdev;
1884         struct mport_cdev_priv *priv;
1885
1886         /* Test for valid device */
1887         if (minor >= RIO_MAX_MPORTS) {
1888                 rmcd_error("Invalid minor device number");
1889                 return -EINVAL;
1890         }
1891
1892         chdev = container_of(inode->i_cdev, struct mport_dev, cdev);
1893
1894         rmcd_debug(INIT, "%s filp=%p", dev_name(&chdev->dev), filp);
1895
1896         if (atomic_read(&chdev->active) == 0)
1897                 return -ENODEV;
1898
1899         get_device(&chdev->dev);
1900
1901         priv = kzalloc(sizeof(*priv), GFP_KERNEL);
1902         if (!priv) {
1903                 put_device(&chdev->dev);
1904                 return -ENOMEM;
1905         }
1906
1907         priv->md = chdev;
1908
1909         mutex_lock(&chdev->file_mutex);
1910         list_add_tail(&priv->list, &chdev->file_list);
1911         mutex_unlock(&chdev->file_mutex);
1912
1913         INIT_LIST_HEAD(&priv->db_filters);
1914         INIT_LIST_HEAD(&priv->pw_filters);
1915         spin_lock_init(&priv->fifo_lock);
1916         init_waitqueue_head(&priv->event_rx_wait);
1917         ret = kfifo_alloc(&priv->event_fifo,
1918                           sizeof(struct rio_event) * MPORT_EVENT_DEPTH,
1919                           GFP_KERNEL);
1920         if (ret < 0) {
1921                 dev_err(&chdev->dev, DRV_NAME ": kfifo_alloc failed\n");
1922                 ret = -ENOMEM;
1923                 goto err_fifo;
1924         }
1925
1926 #ifdef CONFIG_RAPIDIO_DMA_ENGINE
1927         INIT_LIST_HEAD(&priv->async_list);
1928         spin_lock_init(&priv->req_lock);
1929         mutex_init(&priv->dma_lock);
1930 #endif
1931
1932         filp->private_data = priv;
1933         goto out;
1934 err_fifo:
1935         kfree(priv);
1936 out:
1937         return ret;
1938 }
1939
1940 static int mport_cdev_fasync(int fd, struct file *filp, int mode)
1941 {
1942         struct mport_cdev_priv *priv = filp->private_data;
1943
1944         return fasync_helper(fd, filp, mode, &priv->async_queue);
1945 }
1946
1947 #ifdef CONFIG_RAPIDIO_DMA_ENGINE
1948 static void mport_cdev_release_dma(struct file *filp)
1949 {
1950         struct mport_cdev_priv *priv = filp->private_data;
1951         struct mport_dev *md;
1952         struct mport_dma_req *req, *req_next;
1953         unsigned long tmo = msecs_to_jiffies(dma_timeout);
1954         long wret;
1955         LIST_HEAD(list);
1956
1957         rmcd_debug(EXIT, "from filp=%p %s(%d)",
1958                    filp, current->comm, task_pid_nr(current));
1959
1960         if (!priv->dmach) {
1961                 rmcd_debug(EXIT, "No DMA channel for filp=%p", filp);
1962                 return;
1963         }
1964
1965         md = priv->md;
1966
1967         spin_lock(&priv->req_lock);
1968         if (!list_empty(&priv->async_list)) {
1969                 rmcd_debug(EXIT, "async list not empty filp=%p %s(%d)",
1970                            filp, current->comm, task_pid_nr(current));
1971                 list_splice_init(&priv->async_list, &list);
1972         }
1973         spin_unlock(&priv->req_lock);
1974
1975         if (!list_empty(&list)) {
1976                 rmcd_debug(EXIT, "temp list not empty");
1977                 list_for_each_entry_safe(req, req_next, &list, node) {
1978                         rmcd_debug(EXIT, "free req->filp=%p cookie=%d compl=%s",
1979                                    req->filp, req->cookie,
1980                                    completion_done(&req->req_comp)?"yes":"no");
1981                         list_del(&req->node);
1982                         kref_put(&req->refcount, dma_req_free);
1983                 }
1984         }
1985
1986         put_dma_channel(priv);
1987         wret = wait_for_completion_interruptible_timeout(&priv->comp, tmo);
1988
1989         if (wret <= 0) {
1990                 rmcd_error("%s(%d) failed waiting for DMA release err=%ld",
1991                         current->comm, task_pid_nr(current), wret);
1992         }
1993
1994         if (priv->dmach != priv->md->dma_chan) {
1995                 rmcd_debug(EXIT, "Release DMA channel for filp=%p %s(%d)",
1996                            filp, current->comm, task_pid_nr(current));
1997                 rio_release_dma(priv->dmach);
1998         } else {
1999                 rmcd_debug(EXIT, "Adjust default DMA channel refcount");
2000                 kref_put(&md->dma_ref, mport_release_def_dma);
2001         }
2002
2003         priv->dmach = NULL;
2004 }
2005 #else
2006 #define mport_cdev_release_dma(priv) do {} while (0)
2007 #endif
2008
2009 /*
2010  * mport_cdev_release() - Release character device
2011  */
2012 static int mport_cdev_release(struct inode *inode, struct file *filp)
2013 {
2014         struct mport_cdev_priv *priv = filp->private_data;
2015         struct mport_dev *chdev;
2016         struct rio_mport_pw_filter *pw_filter, *pw_filter_next;
2017         struct rio_mport_db_filter *db_filter, *db_filter_next;
2018         struct rio_mport_mapping *map, *_map;
2019         unsigned long flags;
2020
2021         rmcd_debug(EXIT, "%s filp=%p", dev_name(&priv->md->dev), filp);
2022
2023         chdev = priv->md;
2024         mport_cdev_release_dma(filp);
2025
2026         priv->event_mask = 0;
2027
2028         spin_lock_irqsave(&chdev->pw_lock, flags);
2029         if (!list_empty(&priv->pw_filters)) {
2030                 list_for_each_entry_safe(pw_filter, pw_filter_next,
2031                                          &priv->pw_filters, priv_node)
2032                         rio_mport_delete_pw_filter(pw_filter);
2033         }
2034         spin_unlock_irqrestore(&chdev->pw_lock, flags);
2035
2036         spin_lock_irqsave(&chdev->db_lock, flags);
2037         list_for_each_entry_safe(db_filter, db_filter_next,
2038                                  &priv->db_filters, priv_node) {
2039                 rio_mport_delete_db_filter(db_filter);
2040         }
2041         spin_unlock_irqrestore(&chdev->db_lock, flags);
2042
2043         kfifo_free(&priv->event_fifo);
2044
2045         mutex_lock(&chdev->buf_mutex);
2046         list_for_each_entry_safe(map, _map, &chdev->mappings, node) {
2047                 if (map->filp == filp) {
2048                         rmcd_debug(EXIT, "release mapping %p filp=%p",
2049                                    map->virt_addr, filp);
2050                         kref_put(&map->ref, mport_release_mapping);
2051                 }
2052         }
2053         mutex_unlock(&chdev->buf_mutex);
2054
2055         mport_cdev_fasync(-1, filp, 0);
2056         filp->private_data = NULL;
2057         mutex_lock(&chdev->file_mutex);
2058         list_del(&priv->list);
2059         mutex_unlock(&chdev->file_mutex);
2060         put_device(&chdev->dev);
2061         kfree(priv);
2062         return 0;
2063 }
2064
2065 /*
2066  * mport_cdev_ioctl() - IOCTLs for character device
2067  */
2068 static long mport_cdev_ioctl(struct file *filp,
2069                 unsigned int cmd, unsigned long arg)
2070 {
2071         int err = -EINVAL;
2072         struct mport_cdev_priv *data = filp->private_data;
2073         struct mport_dev *md = data->md;
2074
2075         if (atomic_read(&md->active) == 0)
2076                 return -ENODEV;
2077
2078         switch (cmd) {
2079         case RIO_MPORT_MAINT_READ_LOCAL:
2080                 return rio_mport_maint_rd(data, (void __user *)arg, 1);
2081         case RIO_MPORT_MAINT_WRITE_LOCAL:
2082                 return rio_mport_maint_wr(data, (void __user *)arg, 1);
2083         case RIO_MPORT_MAINT_READ_REMOTE:
2084                 return rio_mport_maint_rd(data, (void __user *)arg, 0);
2085         case RIO_MPORT_MAINT_WRITE_REMOTE:
2086                 return rio_mport_maint_wr(data, (void __user *)arg, 0);
2087         case RIO_MPORT_MAINT_HDID_SET:
2088                 return maint_hdid_set(data, (void __user *)arg);
2089         case RIO_MPORT_MAINT_COMPTAG_SET:
2090                 return maint_comptag_set(data, (void __user *)arg);
2091         case RIO_MPORT_MAINT_PORT_IDX_GET:
2092                 return maint_port_idx_get(data, (void __user *)arg);
2093         case RIO_MPORT_GET_PROPERTIES:
2094                 md->properties.hdid = md->mport->host_deviceid;
2095                 if (copy_to_user((void __user *)arg, &(md->properties),
2096                                  sizeof(md->properties)))
2097                         return -EFAULT;
2098                 return 0;
2099         case RIO_ENABLE_DOORBELL_RANGE:
2100                 return rio_mport_add_db_filter(data, (void __user *)arg);
2101         case RIO_DISABLE_DOORBELL_RANGE:
2102                 return rio_mport_remove_db_filter(data, (void __user *)arg);
2103         case RIO_ENABLE_PORTWRITE_RANGE:
2104                 return rio_mport_add_pw_filter(data, (void __user *)arg);
2105         case RIO_DISABLE_PORTWRITE_RANGE:
2106                 return rio_mport_remove_pw_filter(data, (void __user *)arg);
2107         case RIO_SET_EVENT_MASK:
2108                 data->event_mask = (u32)arg;
2109                 return 0;
2110         case RIO_GET_EVENT_MASK:
2111                 if (copy_to_user((void __user *)arg, &data->event_mask,
2112                                     sizeof(u32)))
2113                         return -EFAULT;
2114                 return 0;
2115         case RIO_MAP_OUTBOUND:
2116                 return rio_mport_obw_map(filp, (void __user *)arg);
2117         case RIO_MAP_INBOUND:
2118                 return rio_mport_map_inbound(filp, (void __user *)arg);
2119         case RIO_UNMAP_OUTBOUND:
2120                 return rio_mport_obw_free(filp, (void __user *)arg);
2121         case RIO_UNMAP_INBOUND:
2122                 return rio_mport_inbound_free(filp, (void __user *)arg);
2123         case RIO_ALLOC_DMA:
2124                 return rio_mport_alloc_dma(filp, (void __user *)arg);
2125         case RIO_FREE_DMA:
2126                 return rio_mport_free_dma(filp, (void __user *)arg);
2127         case RIO_WAIT_FOR_ASYNC:
2128                 return rio_mport_wait_for_async_dma(filp, (void __user *)arg);
2129         case RIO_TRANSFER:
2130                 return rio_mport_transfer_ioctl(filp, (void __user *)arg);
2131         case RIO_DEV_ADD:
2132                 return rio_mport_add_riodev(data, (void __user *)arg);
2133         case RIO_DEV_DEL:
2134                 return rio_mport_del_riodev(data, (void __user *)arg);
2135         default:
2136                 break;
2137         }
2138
2139         return err;
2140 }
2141
2142 /*
2143  * mport_release_mapping - free mapping resources and info structure
2144  * @ref: a pointer to the kref within struct rio_mport_mapping
2145  *
2146  * NOTE: Shall be called while holding buf_mutex.
2147  */
2148 static void mport_release_mapping(struct kref *ref)
2149 {
2150         struct rio_mport_mapping *map =
2151                         container_of(ref, struct rio_mport_mapping, ref);
2152         struct rio_mport *mport = map->md->mport;
2153
2154         rmcd_debug(MMAP, "type %d mapping @ %p (phys = %pad) for %s",
2155                    map->dir, map->virt_addr,
2156                    &map->phys_addr, mport->name);
2157
2158         list_del(&map->node);
2159
2160         switch (map->dir) {
2161         case MAP_INBOUND:
2162                 rio_unmap_inb_region(mport, map->phys_addr);
2163         case MAP_DMA:
2164                 dma_free_coherent(mport->dev.parent, map->size,
2165                                   map->virt_addr, map->phys_addr);
2166                 break;
2167         case MAP_OUTBOUND:
2168                 rio_unmap_outb_region(mport, map->rioid, map->rio_addr);
2169                 break;
2170         }
2171         kfree(map);
2172 }
2173
2174 static void mport_mm_open(struct vm_area_struct *vma)
2175 {
2176         struct rio_mport_mapping *map = vma->vm_private_data;
2177
2178         rmcd_debug(MMAP, "%pad", &map->phys_addr);
2179         kref_get(&map->ref);
2180 }
2181
2182 static void mport_mm_close(struct vm_area_struct *vma)
2183 {
2184         struct rio_mport_mapping *map = vma->vm_private_data;
2185
2186         rmcd_debug(MMAP, "%pad", &map->phys_addr);
2187         mutex_lock(&map->md->buf_mutex);
2188         kref_put(&map->ref, mport_release_mapping);
2189         mutex_unlock(&map->md->buf_mutex);
2190 }
2191
2192 static const struct vm_operations_struct vm_ops = {
2193         .open = mport_mm_open,
2194         .close = mport_mm_close,
2195 };
2196
2197 static int mport_cdev_mmap(struct file *filp, struct vm_area_struct *vma)
2198 {
2199         struct mport_cdev_priv *priv = filp->private_data;
2200         struct mport_dev *md;
2201         size_t size = vma->vm_end - vma->vm_start;
2202         dma_addr_t baddr;
2203         unsigned long offset;
2204         int found = 0, ret;
2205         struct rio_mport_mapping *map;
2206
2207         rmcd_debug(MMAP, "0x%x bytes at offset 0x%lx",
2208                    (unsigned int)size, vma->vm_pgoff);
2209
2210         md = priv->md;
2211         baddr = ((dma_addr_t)vma->vm_pgoff << PAGE_SHIFT);
2212
2213         mutex_lock(&md->buf_mutex);
2214         list_for_each_entry(map, &md->mappings, node) {
2215                 if (baddr >= map->phys_addr &&
2216                     baddr < (map->phys_addr + map->size)) {
2217                         found = 1;
2218                         break;
2219                 }
2220         }
2221         mutex_unlock(&md->buf_mutex);
2222
2223         if (!found)
2224                 return -ENOMEM;
2225
2226         offset = baddr - map->phys_addr;
2227
2228         if (size + offset > map->size)
2229                 return -EINVAL;
2230
2231         vma->vm_pgoff = offset >> PAGE_SHIFT;
2232         rmcd_debug(MMAP, "MMAP adjusted offset = 0x%lx", vma->vm_pgoff);
2233
2234         if (map->dir == MAP_INBOUND || map->dir == MAP_DMA)
2235                 ret = dma_mmap_coherent(md->mport->dev.parent, vma,
2236                                 map->virt_addr, map->phys_addr, map->size);
2237         else if (map->dir == MAP_OUTBOUND) {
2238                 vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
2239                 ret = vm_iomap_memory(vma, map->phys_addr, map->size);
2240         } else {
2241                 rmcd_error("Attempt to mmap unsupported mapping type");
2242                 ret = -EIO;
2243         }
2244
2245         if (!ret) {
2246                 vma->vm_private_data = map;
2247                 vma->vm_ops = &vm_ops;
2248                 mport_mm_open(vma);
2249         } else {
2250                 rmcd_error("MMAP exit with err=%d", ret);
2251         }
2252
2253         return ret;
2254 }
2255
2256 static __poll_t mport_cdev_poll(struct file *filp, poll_table *wait)
2257 {
2258         struct mport_cdev_priv *priv = filp->private_data;
2259
2260         poll_wait(filp, &priv->event_rx_wait, wait);
2261         if (kfifo_len(&priv->event_fifo))
2262                 return EPOLLIN | EPOLLRDNORM;
2263
2264         return 0;
2265 }
2266
2267 static ssize_t mport_read(struct file *filp, char __user *buf, size_t count,
2268                         loff_t *ppos)
2269 {
2270         struct mport_cdev_priv *priv = filp->private_data;
2271         int copied;
2272         ssize_t ret;
2273
2274         if (!count)
2275                 return 0;
2276
2277         if (kfifo_is_empty(&priv->event_fifo) &&
2278             (filp->f_flags & O_NONBLOCK))
2279                 return -EAGAIN;
2280
2281         if (count % sizeof(struct rio_event))
2282                 return -EINVAL;
2283
2284         ret = wait_event_interruptible(priv->event_rx_wait,
2285                                         kfifo_len(&priv->event_fifo) != 0);
2286         if (ret)
2287                 return ret;
2288
2289         while (ret < count) {
2290                 if (kfifo_to_user(&priv->event_fifo, buf,
2291                       sizeof(struct rio_event), &copied))
2292                         return -EFAULT;
2293                 ret += copied;
2294                 buf += copied;
2295         }
2296
2297         return ret;
2298 }
2299
2300 static ssize_t mport_write(struct file *filp, const char __user *buf,
2301                          size_t count, loff_t *ppos)
2302 {
2303         struct mport_cdev_priv *priv = filp->private_data;
2304         struct rio_mport *mport = priv->md->mport;
2305         struct rio_event event;
2306         int len, ret;
2307
2308         if (!count)
2309                 return 0;
2310
2311         if (count % sizeof(event))
2312                 return -EINVAL;
2313
2314         len = 0;
2315         while ((count - len) >= (int)sizeof(event)) {
2316                 if (copy_from_user(&event, buf, sizeof(event)))
2317                         return -EFAULT;
2318
2319                 if (event.header != RIO_DOORBELL)
2320                         return -EINVAL;
2321
2322                 ret = rio_mport_send_doorbell(mport,
2323                                               event.u.doorbell.rioid,
2324                                               event.u.doorbell.payload);
2325                 if (ret < 0)
2326                         return ret;
2327
2328                 len += sizeof(event);
2329                 buf += sizeof(event);
2330         }
2331
2332         return len;
2333 }
2334
2335 static const struct file_operations mport_fops = {
2336         .owner          = THIS_MODULE,
2337         .open           = mport_cdev_open,
2338         .release        = mport_cdev_release,
2339         .poll           = mport_cdev_poll,
2340         .read           = mport_read,
2341         .write          = mport_write,
2342         .mmap           = mport_cdev_mmap,
2343         .fasync         = mport_cdev_fasync,
2344         .unlocked_ioctl = mport_cdev_ioctl
2345 };
2346
2347 /*
2348  * Character device management
2349  */
2350
2351 static void mport_device_release(struct device *dev)
2352 {
2353         struct mport_dev *md;
2354
2355         rmcd_debug(EXIT, "%s", dev_name(dev));
2356         md = container_of(dev, struct mport_dev, dev);
2357         kfree(md);
2358 }
2359
2360 /*
2361  * mport_cdev_add() - Create mport_dev from rio_mport
2362  * @mport:      RapidIO master port
2363  */
2364 static struct mport_dev *mport_cdev_add(struct rio_mport *mport)
2365 {
2366         int ret = 0;
2367         struct mport_dev *md;
2368         struct rio_mport_attr attr;
2369
2370         md = kzalloc(sizeof(*md), GFP_KERNEL);
2371         if (!md) {
2372                 rmcd_error("Unable allocate a device object");
2373                 return NULL;
2374         }
2375
2376         md->mport = mport;
2377         mutex_init(&md->buf_mutex);
2378         mutex_init(&md->file_mutex);
2379         INIT_LIST_HEAD(&md->file_list);
2380
2381         device_initialize(&md->dev);
2382         md->dev.devt = MKDEV(MAJOR(dev_number), mport->id);
2383         md->dev.class = dev_class;
2384         md->dev.parent = &mport->dev;
2385         md->dev.release = mport_device_release;
2386         dev_set_name(&md->dev, DEV_NAME "%d", mport->id);
2387         atomic_set(&md->active, 1);
2388
2389         cdev_init(&md->cdev, &mport_fops);
2390         md->cdev.owner = THIS_MODULE;
2391
2392         INIT_LIST_HEAD(&md->doorbells);
2393         spin_lock_init(&md->db_lock);
2394         INIT_LIST_HEAD(&md->portwrites);
2395         spin_lock_init(&md->pw_lock);
2396         INIT_LIST_HEAD(&md->mappings);
2397
2398         md->properties.id = mport->id;
2399         md->properties.sys_size = mport->sys_size;
2400         md->properties.hdid = mport->host_deviceid;
2401         md->properties.index = mport->index;
2402
2403         /* The transfer_mode property will be returned through mport query
2404          * interface
2405          */
2406 #ifdef CONFIG_FSL_RIO /* for now: only on Freescale's SoCs */
2407         md->properties.transfer_mode |= RIO_TRANSFER_MODE_MAPPED;
2408 #else
2409         md->properties.transfer_mode |= RIO_TRANSFER_MODE_TRANSFER;
2410 #endif
2411
2412         ret = cdev_device_add(&md->cdev, &md->dev);
2413         if (ret) {
2414                 rmcd_error("Failed to register mport %d (err=%d)",
2415                        mport->id, ret);
2416                 goto err_cdev;
2417         }
2418         ret = rio_query_mport(mport, &attr);
2419         if (!ret) {
2420                 md->properties.flags = attr.flags;
2421                 md->properties.link_speed = attr.link_speed;
2422                 md->properties.link_width = attr.link_width;
2423                 md->properties.dma_max_sge = attr.dma_max_sge;
2424                 md->properties.dma_max_size = attr.dma_max_size;
2425                 md->properties.dma_align = attr.dma_align;
2426                 md->properties.cap_sys_size = 0;
2427                 md->properties.cap_transfer_mode = 0;
2428                 md->properties.cap_addr_size = 0;
2429         } else
2430                 pr_info(DRV_PREFIX "Failed to obtain info for %s cdev(%d:%d)\n",
2431                         mport->name, MAJOR(dev_number), mport->id);
2432
2433         mutex_lock(&mport_devs_lock);
2434         list_add_tail(&md->node, &mport_devs);
2435         mutex_unlock(&mport_devs_lock);
2436
2437         pr_info(DRV_PREFIX "Added %s cdev(%d:%d)\n",
2438                 mport->name, MAJOR(dev_number), mport->id);
2439
2440         return md;
2441
2442 err_cdev:
2443         put_device(&md->dev);
2444         return NULL;
2445 }
2446
2447 /*
2448  * mport_cdev_terminate_dma() - Stop all active DMA data transfers and release
2449  *                              associated DMA channels.
2450  */
2451 static void mport_cdev_terminate_dma(struct mport_dev *md)
2452 {
2453 #ifdef CONFIG_RAPIDIO_DMA_ENGINE
2454         struct mport_cdev_priv *client;
2455
2456         rmcd_debug(DMA, "%s", dev_name(&md->dev));
2457
2458         mutex_lock(&md->file_mutex);
2459         list_for_each_entry(client, &md->file_list, list) {
2460                 if (client->dmach) {
2461                         dmaengine_terminate_all(client->dmach);
2462                         rio_release_dma(client->dmach);
2463                 }
2464         }
2465         mutex_unlock(&md->file_mutex);
2466
2467         if (md->dma_chan) {
2468                 dmaengine_terminate_all(md->dma_chan);
2469                 rio_release_dma(md->dma_chan);
2470                 md->dma_chan = NULL;
2471         }
2472 #endif
2473 }
2474
2475
2476 /*
2477  * mport_cdev_kill_fasync() - Send SIGIO signal to all processes with open
2478  *                            mport_cdev files.
2479  */
2480 static int mport_cdev_kill_fasync(struct mport_dev *md)
2481 {
2482         unsigned int files = 0;
2483         struct mport_cdev_priv *client;
2484
2485         mutex_lock(&md->file_mutex);
2486         list_for_each_entry(client, &md->file_list, list) {
2487                 if (client->async_queue)
2488                         kill_fasync(&client->async_queue, SIGIO, POLL_HUP);
2489                 files++;
2490         }
2491         mutex_unlock(&md->file_mutex);
2492         return files;
2493 }
2494
2495 /*
2496  * mport_cdev_remove() - Remove mport character device
2497  * @dev:        Mport device to remove
2498  */
2499 static void mport_cdev_remove(struct mport_dev *md)
2500 {
2501         struct rio_mport_mapping *map, *_map;
2502
2503         rmcd_debug(EXIT, "Remove %s cdev", md->mport->name);
2504         atomic_set(&md->active, 0);
2505         mport_cdev_terminate_dma(md);
2506         rio_del_mport_pw_handler(md->mport, md, rio_mport_pw_handler);
2507         cdev_device_del(&md->cdev, &md->dev);
2508         mport_cdev_kill_fasync(md);
2509
2510         /* TODO: do we need to give clients some time to close file
2511          * descriptors? Simple wait for XX, or kref?
2512          */
2513
2514         /*
2515          * Release DMA buffers allocated for the mport device.
2516          * Disable associated inbound Rapidio requests mapping if applicable.
2517          */
2518         mutex_lock(&md->buf_mutex);
2519         list_for_each_entry_safe(map, _map, &md->mappings, node) {
2520                 kref_put(&map->ref, mport_release_mapping);
2521         }
2522         mutex_unlock(&md->buf_mutex);
2523
2524         if (!list_empty(&md->mappings))
2525                 rmcd_warn("WARNING: %s pending mappings on removal",
2526                           md->mport->name);
2527
2528         rio_release_inb_dbell(md->mport, 0, 0x0fff);
2529
2530         put_device(&md->dev);
2531 }
2532
2533 /*
2534  * RIO rio_mport_interface driver
2535  */
2536
2537 /*
2538  * mport_add_mport() - Add rio_mport from LDM device struct
2539  * @dev:                Linux device model struct
2540  * @class_intf: Linux class_interface
2541  */
2542 static int mport_add_mport(struct device *dev,
2543                 struct class_interface *class_intf)
2544 {
2545         struct rio_mport *mport = NULL;
2546         struct mport_dev *chdev = NULL;
2547
2548         mport = to_rio_mport(dev);
2549         if (!mport)
2550                 return -ENODEV;
2551
2552         chdev = mport_cdev_add(mport);
2553         if (!chdev)
2554                 return -ENODEV;
2555
2556         return 0;
2557 }
2558
2559 /*
2560  * mport_remove_mport() - Remove rio_mport from global list
2561  * TODO remove device from global mport_dev list
2562  */
2563 static void mport_remove_mport(struct device *dev,
2564                 struct class_interface *class_intf)
2565 {
2566         struct rio_mport *mport = NULL;
2567         struct mport_dev *chdev;
2568         int found = 0;
2569
2570         mport = to_rio_mport(dev);
2571         rmcd_debug(EXIT, "Remove %s", mport->name);
2572
2573         mutex_lock(&mport_devs_lock);
2574         list_for_each_entry(chdev, &mport_devs, node) {
2575                 if (chdev->mport->id == mport->id) {
2576                         atomic_set(&chdev->active, 0);
2577                         list_del(&chdev->node);
2578                         found = 1;
2579                         break;
2580                 }
2581         }
2582         mutex_unlock(&mport_devs_lock);
2583
2584         if (found)
2585                 mport_cdev_remove(chdev);
2586 }
2587
2588 /* the rio_mport_interface is used to handle local mport devices */
2589 static struct class_interface rio_mport_interface __refdata = {
2590         .class          = &rio_mport_class,
2591         .add_dev        = mport_add_mport,
2592         .remove_dev     = mport_remove_mport,
2593 };
2594
2595 /*
2596  * Linux kernel module
2597  */
2598
2599 /*
2600  * mport_init - Driver module loading
2601  */
2602 static int __init mport_init(void)
2603 {
2604         int ret;
2605
2606         /* Create device class needed by udev */
2607         dev_class = class_create(THIS_MODULE, DRV_NAME);
2608         if (IS_ERR(dev_class)) {
2609                 rmcd_error("Unable to create " DRV_NAME " class");
2610                 return PTR_ERR(dev_class);
2611         }
2612
2613         ret = alloc_chrdev_region(&dev_number, 0, RIO_MAX_MPORTS, DRV_NAME);
2614         if (ret < 0)
2615                 goto err_chr;
2616
2617         rmcd_debug(INIT, "Registered class with major=%d", MAJOR(dev_number));
2618
2619         /* Register to rio_mport_interface */
2620         ret = class_interface_register(&rio_mport_interface);
2621         if (ret) {
2622                 rmcd_error("class_interface_register() failed, err=%d", ret);
2623                 goto err_cli;
2624         }
2625
2626         return 0;
2627
2628 err_cli:
2629         unregister_chrdev_region(dev_number, RIO_MAX_MPORTS);
2630 err_chr:
2631         class_destroy(dev_class);
2632         return ret;
2633 }
2634
2635 /**
2636  * mport_exit - Driver module unloading
2637  */
2638 static void __exit mport_exit(void)
2639 {
2640         class_interface_unregister(&rio_mport_interface);
2641         class_destroy(dev_class);
2642         unregister_chrdev_region(dev_number, RIO_MAX_MPORTS);
2643 }
2644
2645 module_init(mport_init);
2646 module_exit(mport_exit);