095801c4d239ac2648474063f6fe3670c8f3f43b
[cascardo/linux.git] / drivers / rapidio / rio.c
1 /*
2  * RapidIO interconnect services
3  * (RapidIO Interconnect Specification, http://www.rapidio.org)
4  *
5  * Copyright 2005 MontaVista Software, Inc.
6  * Matt Porter <mporter@kernel.crashing.org>
7  *
8  * Copyright 2009 - 2013 Integrated Device Technology, Inc.
9  * Alex Bounine <alexandre.bounine@idt.com>
10  *
11  * This program is free software; you can redistribute  it and/or modify it
12  * under  the terms of  the GNU General  Public License as published by the
13  * Free Software Foundation;  either version 2 of the  License, or (at your
14  * option) any later version.
15  */
16
17 #include <linux/types.h>
18 #include <linux/kernel.h>
19
20 #include <linux/delay.h>
21 #include <linux/init.h>
22 #include <linux/rio.h>
23 #include <linux/rio_drv.h>
24 #include <linux/rio_ids.h>
25 #include <linux/rio_regs.h>
26 #include <linux/module.h>
27 #include <linux/spinlock.h>
28 #include <linux/slab.h>
29 #include <linux/interrupt.h>
30
31 #include "rio.h"
32
33 MODULE_DESCRIPTION("RapidIO Subsystem Core");
34 MODULE_AUTHOR("Matt Porter <mporter@kernel.crashing.org>");
35 MODULE_AUTHOR("Alexandre Bounine <alexandre.bounine@idt.com>");
36 MODULE_LICENSE("GPL");
37
38 static int hdid[RIO_MAX_MPORTS];
39 static int ids_num;
40 module_param_array(hdid, int, &ids_num, 0);
41 MODULE_PARM_DESC(hdid,
42         "Destination ID assignment to local RapidIO controllers");
43
44 static LIST_HEAD(rio_devices);
45 static LIST_HEAD(rio_nets);
46 static DEFINE_SPINLOCK(rio_global_list_lock);
47
48 static LIST_HEAD(rio_mports);
49 static LIST_HEAD(rio_scans);
50 static DEFINE_MUTEX(rio_mport_list_lock);
51 static unsigned char next_portid;
52 static DEFINE_SPINLOCK(rio_mmap_lock);
53
54 /**
55  * rio_local_get_device_id - Get the base/extended device id for a port
56  * @port: RIO master port from which to get the deviceid
57  *
58  * Reads the base/extended device id from the local device
59  * implementing the master port. Returns the 8/16-bit device
60  * id.
61  */
62 u16 rio_local_get_device_id(struct rio_mport *port)
63 {
64         u32 result;
65
66         rio_local_read_config_32(port, RIO_DID_CSR, &result);
67
68         return (RIO_GET_DID(port->sys_size, result));
69 }
70
71 /**
72  * rio_query_mport - Query mport device attributes
73  * @port: mport device to query
74  * @mport_attr: mport attributes data structure
75  *
76  * Returns attributes of specified mport through the
77  * pointer to attributes data structure.
78  */
79 int rio_query_mport(struct rio_mport *port,
80                     struct rio_mport_attr *mport_attr)
81 {
82         if (!port->ops->query_mport)
83                 return -ENODATA;
84         return port->ops->query_mport(port, mport_attr);
85 }
86 EXPORT_SYMBOL(rio_query_mport);
87
88 /**
89  * rio_alloc_net- Allocate and initialize a new RIO network data structure
90  * @mport: Master port associated with the RIO network
91  *
92  * Allocates a RIO network structure, initializes per-network
93  * list heads, and adds the associated master port to the
94  * network list of associated master ports. Returns a
95  * RIO network pointer on success or %NULL on failure.
96  */
97 struct rio_net *rio_alloc_net(struct rio_mport *mport)
98 {
99         struct rio_net *net;
100
101         net = kzalloc(sizeof(struct rio_net), GFP_KERNEL);
102         if (net) {
103                 INIT_LIST_HEAD(&net->node);
104                 INIT_LIST_HEAD(&net->devices);
105                 INIT_LIST_HEAD(&net->switches);
106                 INIT_LIST_HEAD(&net->mports);
107                 mport->net = net;
108         }
109         return net;
110 }
111 EXPORT_SYMBOL_GPL(rio_alloc_net);
112
113 int rio_add_net(struct rio_net *net)
114 {
115         int err;
116
117         err = device_register(&net->dev);
118         if (err)
119                 return err;
120         spin_lock(&rio_global_list_lock);
121         list_add_tail(&net->node, &rio_nets);
122         spin_unlock(&rio_global_list_lock);
123
124         return 0;
125 }
126 EXPORT_SYMBOL_GPL(rio_add_net);
127
128 void rio_free_net(struct rio_net *net)
129 {
130         spin_lock(&rio_global_list_lock);
131         if (!list_empty(&net->node))
132                 list_del(&net->node);
133         spin_unlock(&rio_global_list_lock);
134         if (net->release)
135                 net->release(net);
136         device_unregister(&net->dev);
137 }
138 EXPORT_SYMBOL_GPL(rio_free_net);
139
140 /**
141  * rio_local_set_device_id - Set the base/extended device id for a port
142  * @port: RIO master port
143  * @did: Device ID value to be written
144  *
145  * Writes the base/extended device id from a device.
146  */
147 void rio_local_set_device_id(struct rio_mport *port, u16 did)
148 {
149         rio_local_write_config_32(port, RIO_DID_CSR,
150                                   RIO_SET_DID(port->sys_size, did));
151 }
152 EXPORT_SYMBOL_GPL(rio_local_set_device_id);
153
154 /**
155  * rio_add_device- Adds a RIO device to the device model
156  * @rdev: RIO device
157  *
158  * Adds the RIO device to the global device list and adds the RIO
159  * device to the RIO device list.  Creates the generic sysfs nodes
160  * for an RIO device.
161  */
162 int rio_add_device(struct rio_dev *rdev)
163 {
164         int err;
165
166         atomic_set(&rdev->state, RIO_DEVICE_RUNNING);
167         err = device_register(&rdev->dev);
168         if (err)
169                 return err;
170
171         spin_lock(&rio_global_list_lock);
172         list_add_tail(&rdev->global_list, &rio_devices);
173         if (rdev->net) {
174                 list_add_tail(&rdev->net_list, &rdev->net->devices);
175                 if (rdev->pef & RIO_PEF_SWITCH)
176                         list_add_tail(&rdev->rswitch->node,
177                                       &rdev->net->switches);
178         }
179         spin_unlock(&rio_global_list_lock);
180
181         rio_create_sysfs_dev_files(rdev);
182
183         return 0;
184 }
185 EXPORT_SYMBOL_GPL(rio_add_device);
186
187 /*
188  * rio_del_device - removes a RIO device from the device model
189  * @rdev: RIO device
190  * @state: device state to set during removal process
191  *
192  * Removes the RIO device to the kernel device list and subsystem's device list.
193  * Clears sysfs entries for the removed device.
194  */
195 void rio_del_device(struct rio_dev *rdev, enum rio_device_state state)
196 {
197         pr_debug("RIO: %s: removing %s\n", __func__, rio_name(rdev));
198         atomic_set(&rdev->state, state);
199         spin_lock(&rio_global_list_lock);
200         list_del(&rdev->global_list);
201         if (rdev->net) {
202                 list_del(&rdev->net_list);
203                 if (rdev->pef & RIO_PEF_SWITCH) {
204                         list_del(&rdev->rswitch->node);
205                         kfree(rdev->rswitch->route_table);
206                 }
207         }
208         spin_unlock(&rio_global_list_lock);
209         rio_remove_sysfs_dev_files(rdev);
210         device_unregister(&rdev->dev);
211 }
212 EXPORT_SYMBOL_GPL(rio_del_device);
213
214 /**
215  * rio_request_inb_mbox - request inbound mailbox service
216  * @mport: RIO master port from which to allocate the mailbox resource
217  * @dev_id: Device specific pointer to pass on event
218  * @mbox: Mailbox number to claim
219  * @entries: Number of entries in inbound mailbox queue
220  * @minb: Callback to execute when inbound message is received
221  *
222  * Requests ownership of an inbound mailbox resource and binds
223  * a callback function to the resource. Returns %0 on success.
224  */
225 int rio_request_inb_mbox(struct rio_mport *mport,
226                          void *dev_id,
227                          int mbox,
228                          int entries,
229                          void (*minb) (struct rio_mport * mport, void *dev_id, int mbox,
230                                        int slot))
231 {
232         int rc = -ENOSYS;
233         struct resource *res;
234
235         if (mport->ops->open_inb_mbox == NULL)
236                 goto out;
237
238         res = kzalloc(sizeof(struct resource), GFP_KERNEL);
239
240         if (res) {
241                 rio_init_mbox_res(res, mbox, mbox);
242
243                 /* Make sure this mailbox isn't in use */
244                 if ((rc =
245                      request_resource(&mport->riores[RIO_INB_MBOX_RESOURCE],
246                                       res)) < 0) {
247                         kfree(res);
248                         goto out;
249                 }
250
251                 mport->inb_msg[mbox].res = res;
252
253                 /* Hook the inbound message callback */
254                 mport->inb_msg[mbox].mcback = minb;
255
256                 rc = mport->ops->open_inb_mbox(mport, dev_id, mbox, entries);
257         } else
258                 rc = -ENOMEM;
259
260       out:
261         return rc;
262 }
263
264 /**
265  * rio_release_inb_mbox - release inbound mailbox message service
266  * @mport: RIO master port from which to release the mailbox resource
267  * @mbox: Mailbox number to release
268  *
269  * Releases ownership of an inbound mailbox resource. Returns 0
270  * if the request has been satisfied.
271  */
272 int rio_release_inb_mbox(struct rio_mport *mport, int mbox)
273 {
274         if (mport->ops->close_inb_mbox) {
275                 mport->ops->close_inb_mbox(mport, mbox);
276
277                 /* Release the mailbox resource */
278                 return release_resource(mport->inb_msg[mbox].res);
279         } else
280                 return -ENOSYS;
281 }
282
283 /**
284  * rio_request_outb_mbox - request outbound mailbox service
285  * @mport: RIO master port from which to allocate the mailbox resource
286  * @dev_id: Device specific pointer to pass on event
287  * @mbox: Mailbox number to claim
288  * @entries: Number of entries in outbound mailbox queue
289  * @moutb: Callback to execute when outbound message is sent
290  *
291  * Requests ownership of an outbound mailbox resource and binds
292  * a callback function to the resource. Returns 0 on success.
293  */
294 int rio_request_outb_mbox(struct rio_mport *mport,
295                           void *dev_id,
296                           int mbox,
297                           int entries,
298                           void (*moutb) (struct rio_mport * mport, void *dev_id, int mbox, int slot))
299 {
300         int rc = -ENOSYS;
301         struct resource *res;
302
303         if (mport->ops->open_outb_mbox == NULL)
304                 goto out;
305
306         res = kzalloc(sizeof(struct resource), GFP_KERNEL);
307
308         if (res) {
309                 rio_init_mbox_res(res, mbox, mbox);
310
311                 /* Make sure this outbound mailbox isn't in use */
312                 if ((rc =
313                      request_resource(&mport->riores[RIO_OUTB_MBOX_RESOURCE],
314                                       res)) < 0) {
315                         kfree(res);
316                         goto out;
317                 }
318
319                 mport->outb_msg[mbox].res = res;
320
321                 /* Hook the inbound message callback */
322                 mport->outb_msg[mbox].mcback = moutb;
323
324                 rc = mport->ops->open_outb_mbox(mport, dev_id, mbox, entries);
325         } else
326                 rc = -ENOMEM;
327
328       out:
329         return rc;
330 }
331
332 /**
333  * rio_release_outb_mbox - release outbound mailbox message service
334  * @mport: RIO master port from which to release the mailbox resource
335  * @mbox: Mailbox number to release
336  *
337  * Releases ownership of an inbound mailbox resource. Returns 0
338  * if the request has been satisfied.
339  */
340 int rio_release_outb_mbox(struct rio_mport *mport, int mbox)
341 {
342         if (mport->ops->close_outb_mbox) {
343                 mport->ops->close_outb_mbox(mport, mbox);
344
345                 /* Release the mailbox resource */
346                 return release_resource(mport->outb_msg[mbox].res);
347         } else
348                 return -ENOSYS;
349 }
350
351 /**
352  * rio_setup_inb_dbell - bind inbound doorbell callback
353  * @mport: RIO master port to bind the doorbell callback
354  * @dev_id: Device specific pointer to pass on event
355  * @res: Doorbell message resource
356  * @dinb: Callback to execute when doorbell is received
357  *
358  * Adds a doorbell resource/callback pair into a port's
359  * doorbell event list. Returns 0 if the request has been
360  * satisfied.
361  */
362 static int
363 rio_setup_inb_dbell(struct rio_mport *mport, void *dev_id, struct resource *res,
364                     void (*dinb) (struct rio_mport * mport, void *dev_id, u16 src, u16 dst,
365                                   u16 info))
366 {
367         int rc = 0;
368         struct rio_dbell *dbell;
369
370         if (!(dbell = kmalloc(sizeof(struct rio_dbell), GFP_KERNEL))) {
371                 rc = -ENOMEM;
372                 goto out;
373         }
374
375         dbell->res = res;
376         dbell->dinb = dinb;
377         dbell->dev_id = dev_id;
378
379         mutex_lock(&mport->lock);
380         list_add_tail(&dbell->node, &mport->dbells);
381         mutex_unlock(&mport->lock);
382
383       out:
384         return rc;
385 }
386
387 /**
388  * rio_request_inb_dbell - request inbound doorbell message service
389  * @mport: RIO master port from which to allocate the doorbell resource
390  * @dev_id: Device specific pointer to pass on event
391  * @start: Doorbell info range start
392  * @end: Doorbell info range end
393  * @dinb: Callback to execute when doorbell is received
394  *
395  * Requests ownership of an inbound doorbell resource and binds
396  * a callback function to the resource. Returns 0 if the request
397  * has been satisfied.
398  */
399 int rio_request_inb_dbell(struct rio_mport *mport,
400                           void *dev_id,
401                           u16 start,
402                           u16 end,
403                           void (*dinb) (struct rio_mport * mport, void *dev_id, u16 src,
404                                         u16 dst, u16 info))
405 {
406         int rc = 0;
407
408         struct resource *res = kzalloc(sizeof(struct resource), GFP_KERNEL);
409
410         if (res) {
411                 rio_init_dbell_res(res, start, end);
412
413                 /* Make sure these doorbells aren't in use */
414                 if ((rc =
415                      request_resource(&mport->riores[RIO_DOORBELL_RESOURCE],
416                                       res)) < 0) {
417                         kfree(res);
418                         goto out;
419                 }
420
421                 /* Hook the doorbell callback */
422                 rc = rio_setup_inb_dbell(mport, dev_id, res, dinb);
423         } else
424                 rc = -ENOMEM;
425
426       out:
427         return rc;
428 }
429
430 /**
431  * rio_release_inb_dbell - release inbound doorbell message service
432  * @mport: RIO master port from which to release the doorbell resource
433  * @start: Doorbell info range start
434  * @end: Doorbell info range end
435  *
436  * Releases ownership of an inbound doorbell resource and removes
437  * callback from the doorbell event list. Returns 0 if the request
438  * has been satisfied.
439  */
440 int rio_release_inb_dbell(struct rio_mport *mport, u16 start, u16 end)
441 {
442         int rc = 0, found = 0;
443         struct rio_dbell *dbell;
444
445         mutex_lock(&mport->lock);
446         list_for_each_entry(dbell, &mport->dbells, node) {
447                 if ((dbell->res->start == start) && (dbell->res->end == end)) {
448                         list_del(&dbell->node);
449                         found = 1;
450                         break;
451                 }
452         }
453         mutex_unlock(&mport->lock);
454
455         /* If we can't find an exact match, fail */
456         if (!found) {
457                 rc = -EINVAL;
458                 goto out;
459         }
460
461         /* Release the doorbell resource */
462         rc = release_resource(dbell->res);
463
464         /* Free the doorbell event */
465         kfree(dbell);
466
467       out:
468         return rc;
469 }
470
471 /**
472  * rio_request_outb_dbell - request outbound doorbell message range
473  * @rdev: RIO device from which to allocate the doorbell resource
474  * @start: Doorbell message range start
475  * @end: Doorbell message range end
476  *
477  * Requests ownership of a doorbell message range. Returns a resource
478  * if the request has been satisfied or %NULL on failure.
479  */
480 struct resource *rio_request_outb_dbell(struct rio_dev *rdev, u16 start,
481                                         u16 end)
482 {
483         struct resource *res = kzalloc(sizeof(struct resource), GFP_KERNEL);
484
485         if (res) {
486                 rio_init_dbell_res(res, start, end);
487
488                 /* Make sure these doorbells aren't in use */
489                 if (request_resource(&rdev->riores[RIO_DOORBELL_RESOURCE], res)
490                     < 0) {
491                         kfree(res);
492                         res = NULL;
493                 }
494         }
495
496         return res;
497 }
498
499 /**
500  * rio_release_outb_dbell - release outbound doorbell message range
501  * @rdev: RIO device from which to release the doorbell resource
502  * @res: Doorbell resource to be freed
503  *
504  * Releases ownership of a doorbell message range. Returns 0 if the
505  * request has been satisfied.
506  */
507 int rio_release_outb_dbell(struct rio_dev *rdev, struct resource *res)
508 {
509         int rc = release_resource(res);
510
511         kfree(res);
512
513         return rc;
514 }
515
516 /**
517  * rio_request_inb_pwrite - request inbound port-write message service
518  * @rdev: RIO device to which register inbound port-write callback routine
519  * @pwcback: Callback routine to execute when port-write is received
520  *
521  * Binds a port-write callback function to the RapidIO device.
522  * Returns 0 if the request has been satisfied.
523  */
524 int rio_request_inb_pwrite(struct rio_dev *rdev,
525         int (*pwcback)(struct rio_dev *rdev, union rio_pw_msg *msg, int step))
526 {
527         int rc = 0;
528
529         spin_lock(&rio_global_list_lock);
530         if (rdev->pwcback != NULL)
531                 rc = -ENOMEM;
532         else
533                 rdev->pwcback = pwcback;
534
535         spin_unlock(&rio_global_list_lock);
536         return rc;
537 }
538 EXPORT_SYMBOL_GPL(rio_request_inb_pwrite);
539
540 /**
541  * rio_release_inb_pwrite - release inbound port-write message service
542  * @rdev: RIO device which registered for inbound port-write callback
543  *
544  * Removes callback from the rio_dev structure. Returns 0 if the request
545  * has been satisfied.
546  */
547 int rio_release_inb_pwrite(struct rio_dev *rdev)
548 {
549         int rc = -ENOMEM;
550
551         spin_lock(&rio_global_list_lock);
552         if (rdev->pwcback) {
553                 rdev->pwcback = NULL;
554                 rc = 0;
555         }
556
557         spin_unlock(&rio_global_list_lock);
558         return rc;
559 }
560 EXPORT_SYMBOL_GPL(rio_release_inb_pwrite);
561
562 /**
563  * rio_map_inb_region -- Map inbound memory region.
564  * @mport: Master port.
565  * @local: physical address of memory region to be mapped
566  * @rbase: RIO base address assigned to this window
567  * @size: Size of the memory region
568  * @rflags: Flags for mapping.
569  *
570  * Return: 0 -- Success.
571  *
572  * This function will create the mapping from RIO space to local memory.
573  */
574 int rio_map_inb_region(struct rio_mport *mport, dma_addr_t local,
575                         u64 rbase, u32 size, u32 rflags)
576 {
577         int rc = 0;
578         unsigned long flags;
579
580         if (!mport->ops->map_inb)
581                 return -1;
582         spin_lock_irqsave(&rio_mmap_lock, flags);
583         rc = mport->ops->map_inb(mport, local, rbase, size, rflags);
584         spin_unlock_irqrestore(&rio_mmap_lock, flags);
585         return rc;
586 }
587 EXPORT_SYMBOL_GPL(rio_map_inb_region);
588
589 /**
590  * rio_unmap_inb_region -- Unmap the inbound memory region
591  * @mport: Master port
592  * @lstart: physical address of memory region to be unmapped
593  */
594 void rio_unmap_inb_region(struct rio_mport *mport, dma_addr_t lstart)
595 {
596         unsigned long flags;
597         if (!mport->ops->unmap_inb)
598                 return;
599         spin_lock_irqsave(&rio_mmap_lock, flags);
600         mport->ops->unmap_inb(mport, lstart);
601         spin_unlock_irqrestore(&rio_mmap_lock, flags);
602 }
603 EXPORT_SYMBOL_GPL(rio_unmap_inb_region);
604
605 /**
606  * rio_mport_get_physefb - Helper function that returns register offset
607  *                      for Physical Layer Extended Features Block.
608  * @port: Master port to issue transaction
609  * @local: Indicate a local master port or remote device access
610  * @destid: Destination ID of the device
611  * @hopcount: Number of switch hops to the device
612  */
613 u32
614 rio_mport_get_physefb(struct rio_mport *port, int local,
615                       u16 destid, u8 hopcount)
616 {
617         u32 ext_ftr_ptr;
618         u32 ftr_header;
619
620         ext_ftr_ptr = rio_mport_get_efb(port, local, destid, hopcount, 0);
621
622         while (ext_ftr_ptr)  {
623                 if (local)
624                         rio_local_read_config_32(port, ext_ftr_ptr,
625                                                  &ftr_header);
626                 else
627                         rio_mport_read_config_32(port, destid, hopcount,
628                                                  ext_ftr_ptr, &ftr_header);
629
630                 ftr_header = RIO_GET_BLOCK_ID(ftr_header);
631                 switch (ftr_header) {
632
633                 case RIO_EFB_SER_EP_ID_V13P:
634                 case RIO_EFB_SER_EP_REC_ID_V13P:
635                 case RIO_EFB_SER_EP_FREE_ID_V13P:
636                 case RIO_EFB_SER_EP_ID:
637                 case RIO_EFB_SER_EP_REC_ID:
638                 case RIO_EFB_SER_EP_FREE_ID:
639                 case RIO_EFB_SER_EP_FREC_ID:
640
641                         return ext_ftr_ptr;
642
643                 default:
644                         break;
645                 }
646
647                 ext_ftr_ptr = rio_mport_get_efb(port, local, destid,
648                                                 hopcount, ext_ftr_ptr);
649         }
650
651         return ext_ftr_ptr;
652 }
653 EXPORT_SYMBOL_GPL(rio_mport_get_physefb);
654
655 /**
656  * rio_get_comptag - Begin or continue searching for a RIO device by component tag
657  * @comp_tag: RIO component tag to match
658  * @from: Previous RIO device found in search, or %NULL for new search
659  *
660  * Iterates through the list of known RIO devices. If a RIO device is
661  * found with a matching @comp_tag, a pointer to its device
662  * structure is returned. Otherwise, %NULL is returned. A new search
663  * is initiated by passing %NULL to the @from argument. Otherwise, if
664  * @from is not %NULL, searches continue from next device on the global
665  * list.
666  */
667 struct rio_dev *rio_get_comptag(u32 comp_tag, struct rio_dev *from)
668 {
669         struct list_head *n;
670         struct rio_dev *rdev;
671
672         spin_lock(&rio_global_list_lock);
673         n = from ? from->global_list.next : rio_devices.next;
674
675         while (n && (n != &rio_devices)) {
676                 rdev = rio_dev_g(n);
677                 if (rdev->comp_tag == comp_tag)
678                         goto exit;
679                 n = n->next;
680         }
681         rdev = NULL;
682 exit:
683         spin_unlock(&rio_global_list_lock);
684         return rdev;
685 }
686 EXPORT_SYMBOL_GPL(rio_get_comptag);
687
688 /**
689  * rio_set_port_lockout - Sets/clears LOCKOUT bit (RIO EM 1.3) for a switch port.
690  * @rdev: Pointer to RIO device control structure
691  * @pnum: Switch port number to set LOCKOUT bit
692  * @lock: Operation : set (=1) or clear (=0)
693  */
694 int rio_set_port_lockout(struct rio_dev *rdev, u32 pnum, int lock)
695 {
696         u32 regval;
697
698         rio_read_config_32(rdev,
699                                  rdev->phys_efptr + RIO_PORT_N_CTL_CSR(pnum),
700                                  &regval);
701         if (lock)
702                 regval |= RIO_PORT_N_CTL_LOCKOUT;
703         else
704                 regval &= ~RIO_PORT_N_CTL_LOCKOUT;
705
706         rio_write_config_32(rdev,
707                                   rdev->phys_efptr + RIO_PORT_N_CTL_CSR(pnum),
708                                   regval);
709         return 0;
710 }
711 EXPORT_SYMBOL_GPL(rio_set_port_lockout);
712
713 /**
714  * rio_enable_rx_tx_port - enable input receiver and output transmitter of
715  * given port
716  * @port: Master port associated with the RIO network
717  * @local: local=1 select local port otherwise a far device is reached
718  * @destid: Destination ID of the device to check host bit
719  * @hopcount: Number of hops to reach the target
720  * @port_num: Port (-number on switch) to enable on a far end device
721  *
722  * Returns 0 or 1 from on General Control Command and Status Register
723  * (EXT_PTR+0x3C)
724  */
725 int rio_enable_rx_tx_port(struct rio_mport *port,
726                           int local, u16 destid,
727                           u8 hopcount, u8 port_num)
728 {
729 #ifdef CONFIG_RAPIDIO_ENABLE_RX_TX_PORTS
730         u32 regval;
731         u32 ext_ftr_ptr;
732
733         /*
734         * enable rx input tx output port
735         */
736         pr_debug("rio_enable_rx_tx_port(local = %d, destid = %d, hopcount = "
737                  "%d, port_num = %d)\n", local, destid, hopcount, port_num);
738
739         ext_ftr_ptr = rio_mport_get_physefb(port, local, destid, hopcount);
740
741         if (local) {
742                 rio_local_read_config_32(port, ext_ftr_ptr +
743                                 RIO_PORT_N_CTL_CSR(0),
744                                 &regval);
745         } else {
746                 if (rio_mport_read_config_32(port, destid, hopcount,
747                 ext_ftr_ptr + RIO_PORT_N_CTL_CSR(port_num), &regval) < 0)
748                         return -EIO;
749         }
750
751         if (regval & RIO_PORT_N_CTL_P_TYP_SER) {
752                 /* serial */
753                 regval = regval | RIO_PORT_N_CTL_EN_RX_SER
754                                 | RIO_PORT_N_CTL_EN_TX_SER;
755         } else {
756                 /* parallel */
757                 regval = regval | RIO_PORT_N_CTL_EN_RX_PAR
758                                 | RIO_PORT_N_CTL_EN_TX_PAR;
759         }
760
761         if (local) {
762                 rio_local_write_config_32(port, ext_ftr_ptr +
763                                           RIO_PORT_N_CTL_CSR(0), regval);
764         } else {
765                 if (rio_mport_write_config_32(port, destid, hopcount,
766                     ext_ftr_ptr + RIO_PORT_N_CTL_CSR(port_num), regval) < 0)
767                         return -EIO;
768         }
769 #endif
770         return 0;
771 }
772 EXPORT_SYMBOL_GPL(rio_enable_rx_tx_port);
773
774
775 /**
776  * rio_chk_dev_route - Validate route to the specified device.
777  * @rdev:  RIO device failed to respond
778  * @nrdev: Last active device on the route to rdev
779  * @npnum: nrdev's port number on the route to rdev
780  *
781  * Follows a route to the specified RIO device to determine the last available
782  * device (and corresponding RIO port) on the route.
783  */
784 static int
785 rio_chk_dev_route(struct rio_dev *rdev, struct rio_dev **nrdev, int *npnum)
786 {
787         u32 result;
788         int p_port, rc = -EIO;
789         struct rio_dev *prev = NULL;
790
791         /* Find switch with failed RIO link */
792         while (rdev->prev && (rdev->prev->pef & RIO_PEF_SWITCH)) {
793                 if (!rio_read_config_32(rdev->prev, RIO_DEV_ID_CAR, &result)) {
794                         prev = rdev->prev;
795                         break;
796                 }
797                 rdev = rdev->prev;
798         }
799
800         if (prev == NULL)
801                 goto err_out;
802
803         p_port = prev->rswitch->route_table[rdev->destid];
804
805         if (p_port != RIO_INVALID_ROUTE) {
806                 pr_debug("RIO: link failed on [%s]-P%d\n",
807                          rio_name(prev), p_port);
808                 *nrdev = prev;
809                 *npnum = p_port;
810                 rc = 0;
811         } else
812                 pr_debug("RIO: failed to trace route to %s\n", rio_name(rdev));
813 err_out:
814         return rc;
815 }
816
817 /**
818  * rio_mport_chk_dev_access - Validate access to the specified device.
819  * @mport: Master port to send transactions
820  * @destid: Device destination ID in network
821  * @hopcount: Number of hops into the network
822  */
823 int
824 rio_mport_chk_dev_access(struct rio_mport *mport, u16 destid, u8 hopcount)
825 {
826         int i = 0;
827         u32 tmp;
828
829         while (rio_mport_read_config_32(mport, destid, hopcount,
830                                         RIO_DEV_ID_CAR, &tmp)) {
831                 i++;
832                 if (i == RIO_MAX_CHK_RETRY)
833                         return -EIO;
834                 mdelay(1);
835         }
836
837         return 0;
838 }
839 EXPORT_SYMBOL_GPL(rio_mport_chk_dev_access);
840
841 /**
842  * rio_chk_dev_access - Validate access to the specified device.
843  * @rdev: Pointer to RIO device control structure
844  */
845 static int rio_chk_dev_access(struct rio_dev *rdev)
846 {
847         return rio_mport_chk_dev_access(rdev->net->hport,
848                                         rdev->destid, rdev->hopcount);
849 }
850
851 /**
852  * rio_get_input_status - Sends a Link-Request/Input-Status control symbol and
853  *                        returns link-response (if requested).
854  * @rdev: RIO devive to issue Input-status command
855  * @pnum: Device port number to issue the command
856  * @lnkresp: Response from a link partner
857  */
858 static int
859 rio_get_input_status(struct rio_dev *rdev, int pnum, u32 *lnkresp)
860 {
861         u32 regval;
862         int checkcount;
863
864         if (lnkresp) {
865                 /* Read from link maintenance response register
866                  * to clear valid bit */
867                 rio_read_config_32(rdev,
868                         rdev->phys_efptr + RIO_PORT_N_MNT_RSP_CSR(pnum),
869                         &regval);
870                 udelay(50);
871         }
872
873         /* Issue Input-status command */
874         rio_write_config_32(rdev,
875                 rdev->phys_efptr + RIO_PORT_N_MNT_REQ_CSR(pnum),
876                 RIO_MNT_REQ_CMD_IS);
877
878         /* Exit if the response is not expected */
879         if (lnkresp == NULL)
880                 return 0;
881
882         checkcount = 3;
883         while (checkcount--) {
884                 udelay(50);
885                 rio_read_config_32(rdev,
886                         rdev->phys_efptr + RIO_PORT_N_MNT_RSP_CSR(pnum),
887                         &regval);
888                 if (regval & RIO_PORT_N_MNT_RSP_RVAL) {
889                         *lnkresp = regval;
890                         return 0;
891                 }
892         }
893
894         return -EIO;
895 }
896
897 /**
898  * rio_clr_err_stopped - Clears port Error-stopped states.
899  * @rdev: Pointer to RIO device control structure
900  * @pnum: Switch port number to clear errors
901  * @err_status: port error status (if 0 reads register from device)
902  */
903 static int rio_clr_err_stopped(struct rio_dev *rdev, u32 pnum, u32 err_status)
904 {
905         struct rio_dev *nextdev = rdev->rswitch->nextdev[pnum];
906         u32 regval;
907         u32 far_ackid, far_linkstat, near_ackid;
908
909         if (err_status == 0)
910                 rio_read_config_32(rdev,
911                         rdev->phys_efptr + RIO_PORT_N_ERR_STS_CSR(pnum),
912                         &err_status);
913
914         if (err_status & RIO_PORT_N_ERR_STS_PW_OUT_ES) {
915                 pr_debug("RIO_EM: servicing Output Error-Stopped state\n");
916                 /*
917                  * Send a Link-Request/Input-Status control symbol
918                  */
919                 if (rio_get_input_status(rdev, pnum, &regval)) {
920                         pr_debug("RIO_EM: Input-status response timeout\n");
921                         goto rd_err;
922                 }
923
924                 pr_debug("RIO_EM: SP%d Input-status response=0x%08x\n",
925                          pnum, regval);
926                 far_ackid = (regval & RIO_PORT_N_MNT_RSP_ASTAT) >> 5;
927                 far_linkstat = regval & RIO_PORT_N_MNT_RSP_LSTAT;
928                 rio_read_config_32(rdev,
929                         rdev->phys_efptr + RIO_PORT_N_ACK_STS_CSR(pnum),
930                         &regval);
931                 pr_debug("RIO_EM: SP%d_ACK_STS_CSR=0x%08x\n", pnum, regval);
932                 near_ackid = (regval & RIO_PORT_N_ACK_INBOUND) >> 24;
933                 pr_debug("RIO_EM: SP%d far_ackID=0x%02x far_linkstat=0x%02x" \
934                          " near_ackID=0x%02x\n",
935                         pnum, far_ackid, far_linkstat, near_ackid);
936
937                 /*
938                  * If required, synchronize ackIDs of near and
939                  * far sides.
940                  */
941                 if ((far_ackid != ((regval & RIO_PORT_N_ACK_OUTSTAND) >> 8)) ||
942                     (far_ackid != (regval & RIO_PORT_N_ACK_OUTBOUND))) {
943                         /* Align near outstanding/outbound ackIDs with
944                          * far inbound.
945                          */
946                         rio_write_config_32(rdev,
947                                 rdev->phys_efptr + RIO_PORT_N_ACK_STS_CSR(pnum),
948                                 (near_ackid << 24) |
949                                         (far_ackid << 8) | far_ackid);
950                         /* Align far outstanding/outbound ackIDs with
951                          * near inbound.
952                          */
953                         far_ackid++;
954                         if (nextdev)
955                                 rio_write_config_32(nextdev,
956                                         nextdev->phys_efptr +
957                                         RIO_PORT_N_ACK_STS_CSR(RIO_GET_PORT_NUM(nextdev->swpinfo)),
958                                         (far_ackid << 24) |
959                                         (near_ackid << 8) | near_ackid);
960                         else
961                                 pr_debug("RIO_EM: Invalid nextdev pointer (NULL)\n");
962                 }
963 rd_err:
964                 rio_read_config_32(rdev,
965                         rdev->phys_efptr + RIO_PORT_N_ERR_STS_CSR(pnum),
966                         &err_status);
967                 pr_debug("RIO_EM: SP%d_ERR_STS_CSR=0x%08x\n", pnum, err_status);
968         }
969
970         if ((err_status & RIO_PORT_N_ERR_STS_PW_INP_ES) && nextdev) {
971                 pr_debug("RIO_EM: servicing Input Error-Stopped state\n");
972                 rio_get_input_status(nextdev,
973                                      RIO_GET_PORT_NUM(nextdev->swpinfo), NULL);
974                 udelay(50);
975
976                 rio_read_config_32(rdev,
977                         rdev->phys_efptr + RIO_PORT_N_ERR_STS_CSR(pnum),
978                         &err_status);
979                 pr_debug("RIO_EM: SP%d_ERR_STS_CSR=0x%08x\n", pnum, err_status);
980         }
981
982         return (err_status & (RIO_PORT_N_ERR_STS_PW_OUT_ES |
983                               RIO_PORT_N_ERR_STS_PW_INP_ES)) ? 1 : 0;
984 }
985
986 /**
987  * rio_inb_pwrite_handler - process inbound port-write message
988  * @pw_msg: pointer to inbound port-write message
989  *
990  * Processes an inbound port-write message. Returns 0 if the request
991  * has been satisfied.
992  */
993 int rio_inb_pwrite_handler(union rio_pw_msg *pw_msg)
994 {
995         struct rio_dev *rdev;
996         u32 err_status, em_perrdet, em_ltlerrdet;
997         int rc, portnum;
998
999         rdev = rio_get_comptag((pw_msg->em.comptag & RIO_CTAG_UDEVID), NULL);
1000         if (rdev == NULL) {
1001                 /* Device removed or enumeration error */
1002                 pr_debug("RIO: %s No matching device for CTag 0x%08x\n",
1003                         __func__, pw_msg->em.comptag);
1004                 return -EIO;
1005         }
1006
1007         pr_debug("RIO: Port-Write message from %s\n", rio_name(rdev));
1008
1009 #ifdef DEBUG_PW
1010         {
1011         u32 i;
1012         for (i = 0; i < RIO_PW_MSG_SIZE/sizeof(u32);) {
1013                         pr_debug("0x%02x: %08x %08x %08x %08x\n",
1014                                  i*4, pw_msg->raw[i], pw_msg->raw[i + 1],
1015                                  pw_msg->raw[i + 2], pw_msg->raw[i + 3]);
1016                         i += 4;
1017         }
1018         }
1019 #endif
1020
1021         /* Call an external service function (if such is registered
1022          * for this device). This may be the service for endpoints that send
1023          * device-specific port-write messages. End-point messages expected
1024          * to be handled completely by EP specific device driver.
1025          * For switches rc==0 signals that no standard processing required.
1026          */
1027         if (rdev->pwcback != NULL) {
1028                 rc = rdev->pwcback(rdev, pw_msg, 0);
1029                 if (rc == 0)
1030                         return 0;
1031         }
1032
1033         portnum = pw_msg->em.is_port & 0xFF;
1034
1035         /* Check if device and route to it are functional:
1036          * Sometimes devices may send PW message(s) just before being
1037          * powered down (or link being lost).
1038          */
1039         if (rio_chk_dev_access(rdev)) {
1040                 pr_debug("RIO: device access failed - get link partner\n");
1041                 /* Scan route to the device and identify failed link.
1042                  * This will replace device and port reported in PW message.
1043                  * PW message should not be used after this point.
1044                  */
1045                 if (rio_chk_dev_route(rdev, &rdev, &portnum)) {
1046                         pr_err("RIO: Route trace for %s failed\n",
1047                                 rio_name(rdev));
1048                         return -EIO;
1049                 }
1050                 pw_msg = NULL;
1051         }
1052
1053         /* For End-point devices processing stops here */
1054         if (!(rdev->pef & RIO_PEF_SWITCH))
1055                 return 0;
1056
1057         if (rdev->phys_efptr == 0) {
1058                 pr_err("RIO_PW: Bad switch initialization for %s\n",
1059                         rio_name(rdev));
1060                 return 0;
1061         }
1062
1063         /*
1064          * Process the port-write notification from switch
1065          */
1066         if (rdev->rswitch->ops && rdev->rswitch->ops->em_handle)
1067                 rdev->rswitch->ops->em_handle(rdev, portnum);
1068
1069         rio_read_config_32(rdev,
1070                         rdev->phys_efptr + RIO_PORT_N_ERR_STS_CSR(portnum),
1071                         &err_status);
1072         pr_debug("RIO_PW: SP%d_ERR_STS_CSR=0x%08x\n", portnum, err_status);
1073
1074         if (err_status & RIO_PORT_N_ERR_STS_PORT_OK) {
1075
1076                 if (!(rdev->rswitch->port_ok & (1 << portnum))) {
1077                         rdev->rswitch->port_ok |= (1 << portnum);
1078                         rio_set_port_lockout(rdev, portnum, 0);
1079                         /* Schedule Insertion Service */
1080                         pr_debug("RIO_PW: Device Insertion on [%s]-P%d\n",
1081                                rio_name(rdev), portnum);
1082                 }
1083
1084                 /* Clear error-stopped states (if reported).
1085                  * Depending on the link partner state, two attempts
1086                  * may be needed for successful recovery.
1087                  */
1088                 if (err_status & (RIO_PORT_N_ERR_STS_PW_OUT_ES |
1089                                   RIO_PORT_N_ERR_STS_PW_INP_ES)) {
1090                         if (rio_clr_err_stopped(rdev, portnum, err_status))
1091                                 rio_clr_err_stopped(rdev, portnum, 0);
1092                 }
1093         }  else { /* if (err_status & RIO_PORT_N_ERR_STS_PORT_UNINIT) */
1094
1095                 if (rdev->rswitch->port_ok & (1 << portnum)) {
1096                         rdev->rswitch->port_ok &= ~(1 << portnum);
1097                         rio_set_port_lockout(rdev, portnum, 1);
1098
1099                         rio_write_config_32(rdev,
1100                                 rdev->phys_efptr +
1101                                         RIO_PORT_N_ACK_STS_CSR(portnum),
1102                                 RIO_PORT_N_ACK_CLEAR);
1103
1104                         /* Schedule Extraction Service */
1105                         pr_debug("RIO_PW: Device Extraction on [%s]-P%d\n",
1106                                rio_name(rdev), portnum);
1107                 }
1108         }
1109
1110         rio_read_config_32(rdev,
1111                 rdev->em_efptr + RIO_EM_PN_ERR_DETECT(portnum), &em_perrdet);
1112         if (em_perrdet) {
1113                 pr_debug("RIO_PW: RIO_EM_P%d_ERR_DETECT=0x%08x\n",
1114                          portnum, em_perrdet);
1115                 /* Clear EM Port N Error Detect CSR */
1116                 rio_write_config_32(rdev,
1117                         rdev->em_efptr + RIO_EM_PN_ERR_DETECT(portnum), 0);
1118         }
1119
1120         rio_read_config_32(rdev,
1121                 rdev->em_efptr + RIO_EM_LTL_ERR_DETECT, &em_ltlerrdet);
1122         if (em_ltlerrdet) {
1123                 pr_debug("RIO_PW: RIO_EM_LTL_ERR_DETECT=0x%08x\n",
1124                          em_ltlerrdet);
1125                 /* Clear EM L/T Layer Error Detect CSR */
1126                 rio_write_config_32(rdev,
1127                         rdev->em_efptr + RIO_EM_LTL_ERR_DETECT, 0);
1128         }
1129
1130         /* Clear remaining error bits and Port-Write Pending bit */
1131         rio_write_config_32(rdev,
1132                         rdev->phys_efptr + RIO_PORT_N_ERR_STS_CSR(portnum),
1133                         err_status);
1134
1135         return 0;
1136 }
1137 EXPORT_SYMBOL_GPL(rio_inb_pwrite_handler);
1138
1139 /**
1140  * rio_mport_get_efb - get pointer to next extended features block
1141  * @port: Master port to issue transaction
1142  * @local: Indicate a local master port or remote device access
1143  * @destid: Destination ID of the device
1144  * @hopcount: Number of switch hops to the device
1145  * @from: Offset of  current Extended Feature block header (if 0 starts
1146  * from ExtFeaturePtr)
1147  */
1148 u32
1149 rio_mport_get_efb(struct rio_mport *port, int local, u16 destid,
1150                       u8 hopcount, u32 from)
1151 {
1152         u32 reg_val;
1153
1154         if (from == 0) {
1155                 if (local)
1156                         rio_local_read_config_32(port, RIO_ASM_INFO_CAR,
1157                                                  &reg_val);
1158                 else
1159                         rio_mport_read_config_32(port, destid, hopcount,
1160                                                  RIO_ASM_INFO_CAR, &reg_val);
1161                 return reg_val & RIO_EXT_FTR_PTR_MASK;
1162         } else {
1163                 if (local)
1164                         rio_local_read_config_32(port, from, &reg_val);
1165                 else
1166                         rio_mport_read_config_32(port, destid, hopcount,
1167                                                  from, &reg_val);
1168                 return RIO_GET_BLOCK_ID(reg_val);
1169         }
1170 }
1171 EXPORT_SYMBOL_GPL(rio_mport_get_efb);
1172
1173 /**
1174  * rio_mport_get_feature - query for devices' extended features
1175  * @port: Master port to issue transaction
1176  * @local: Indicate a local master port or remote device access
1177  * @destid: Destination ID of the device
1178  * @hopcount: Number of switch hops to the device
1179  * @ftr: Extended feature code
1180  *
1181  * Tell if a device supports a given RapidIO capability.
1182  * Returns the offset of the requested extended feature
1183  * block within the device's RIO configuration space or
1184  * 0 in case the device does not support it.  Possible
1185  * values for @ftr:
1186  *
1187  * %RIO_EFB_PAR_EP_ID           LP/LVDS EP Devices
1188  *
1189  * %RIO_EFB_PAR_EP_REC_ID       LP/LVDS EP Recovery Devices
1190  *
1191  * %RIO_EFB_PAR_EP_FREE_ID      LP/LVDS EP Free Devices
1192  *
1193  * %RIO_EFB_SER_EP_ID           LP/Serial EP Devices
1194  *
1195  * %RIO_EFB_SER_EP_REC_ID       LP/Serial EP Recovery Devices
1196  *
1197  * %RIO_EFB_SER_EP_FREE_ID      LP/Serial EP Free Devices
1198  */
1199 u32
1200 rio_mport_get_feature(struct rio_mport * port, int local, u16 destid,
1201                       u8 hopcount, int ftr)
1202 {
1203         u32 asm_info, ext_ftr_ptr, ftr_header;
1204
1205         if (local)
1206                 rio_local_read_config_32(port, RIO_ASM_INFO_CAR, &asm_info);
1207         else
1208                 rio_mport_read_config_32(port, destid, hopcount,
1209                                          RIO_ASM_INFO_CAR, &asm_info);
1210
1211         ext_ftr_ptr = asm_info & RIO_EXT_FTR_PTR_MASK;
1212
1213         while (ext_ftr_ptr) {
1214                 if (local)
1215                         rio_local_read_config_32(port, ext_ftr_ptr,
1216                                                  &ftr_header);
1217                 else
1218                         rio_mport_read_config_32(port, destid, hopcount,
1219                                                  ext_ftr_ptr, &ftr_header);
1220                 if (RIO_GET_BLOCK_ID(ftr_header) == ftr)
1221                         return ext_ftr_ptr;
1222                 if (!(ext_ftr_ptr = RIO_GET_BLOCK_PTR(ftr_header)))
1223                         break;
1224         }
1225
1226         return 0;
1227 }
1228 EXPORT_SYMBOL_GPL(rio_mport_get_feature);
1229
1230 /**
1231  * rio_get_asm - Begin or continue searching for a RIO device by vid/did/asm_vid/asm_did
1232  * @vid: RIO vid to match or %RIO_ANY_ID to match all vids
1233  * @did: RIO did to match or %RIO_ANY_ID to match all dids
1234  * @asm_vid: RIO asm_vid to match or %RIO_ANY_ID to match all asm_vids
1235  * @asm_did: RIO asm_did to match or %RIO_ANY_ID to match all asm_dids
1236  * @from: Previous RIO device found in search, or %NULL for new search
1237  *
1238  * Iterates through the list of known RIO devices. If a RIO device is
1239  * found with a matching @vid, @did, @asm_vid, @asm_did, the reference
1240  * count to the device is incrememted and a pointer to its device
1241  * structure is returned. Otherwise, %NULL is returned. A new search
1242  * is initiated by passing %NULL to the @from argument. Otherwise, if
1243  * @from is not %NULL, searches continue from next device on the global
1244  * list. The reference count for @from is always decremented if it is
1245  * not %NULL.
1246  */
1247 struct rio_dev *rio_get_asm(u16 vid, u16 did,
1248                             u16 asm_vid, u16 asm_did, struct rio_dev *from)
1249 {
1250         struct list_head *n;
1251         struct rio_dev *rdev;
1252
1253         WARN_ON(in_interrupt());
1254         spin_lock(&rio_global_list_lock);
1255         n = from ? from->global_list.next : rio_devices.next;
1256
1257         while (n && (n != &rio_devices)) {
1258                 rdev = rio_dev_g(n);
1259                 if ((vid == RIO_ANY_ID || rdev->vid == vid) &&
1260                     (did == RIO_ANY_ID || rdev->did == did) &&
1261                     (asm_vid == RIO_ANY_ID || rdev->asm_vid == asm_vid) &&
1262                     (asm_did == RIO_ANY_ID || rdev->asm_did == asm_did))
1263                         goto exit;
1264                 n = n->next;
1265         }
1266         rdev = NULL;
1267       exit:
1268         rio_dev_put(from);
1269         rdev = rio_dev_get(rdev);
1270         spin_unlock(&rio_global_list_lock);
1271         return rdev;
1272 }
1273
1274 /**
1275  * rio_get_device - Begin or continue searching for a RIO device by vid/did
1276  * @vid: RIO vid to match or %RIO_ANY_ID to match all vids
1277  * @did: RIO did to match or %RIO_ANY_ID to match all dids
1278  * @from: Previous RIO device found in search, or %NULL for new search
1279  *
1280  * Iterates through the list of known RIO devices. If a RIO device is
1281  * found with a matching @vid and @did, the reference count to the
1282  * device is incrememted and a pointer to its device structure is returned.
1283  * Otherwise, %NULL is returned. A new search is initiated by passing %NULL
1284  * to the @from argument. Otherwise, if @from is not %NULL, searches
1285  * continue from next device on the global list. The reference count for
1286  * @from is always decremented if it is not %NULL.
1287  */
1288 struct rio_dev *rio_get_device(u16 vid, u16 did, struct rio_dev *from)
1289 {
1290         return rio_get_asm(vid, did, RIO_ANY_ID, RIO_ANY_ID, from);
1291 }
1292
1293 /**
1294  * rio_std_route_add_entry - Add switch route table entry using standard
1295  *   registers defined in RIO specification rev.1.3
1296  * @mport: Master port to issue transaction
1297  * @destid: Destination ID of the device
1298  * @hopcount: Number of switch hops to the device
1299  * @table: routing table ID (global or port-specific)
1300  * @route_destid: destID entry in the RT
1301  * @route_port: destination port for specified destID
1302  */
1303 static int
1304 rio_std_route_add_entry(struct rio_mport *mport, u16 destid, u8 hopcount,
1305                         u16 table, u16 route_destid, u8 route_port)
1306 {
1307         if (table == RIO_GLOBAL_TABLE) {
1308                 rio_mport_write_config_32(mport, destid, hopcount,
1309                                 RIO_STD_RTE_CONF_DESTID_SEL_CSR,
1310                                 (u32)route_destid);
1311                 rio_mport_write_config_32(mport, destid, hopcount,
1312                                 RIO_STD_RTE_CONF_PORT_SEL_CSR,
1313                                 (u32)route_port);
1314         }
1315
1316         udelay(10);
1317         return 0;
1318 }
1319
1320 /**
1321  * rio_std_route_get_entry - Read switch route table entry (port number)
1322  *   associated with specified destID using standard registers defined in RIO
1323  *   specification rev.1.3
1324  * @mport: Master port to issue transaction
1325  * @destid: Destination ID of the device
1326  * @hopcount: Number of switch hops to the device
1327  * @table: routing table ID (global or port-specific)
1328  * @route_destid: destID entry in the RT
1329  * @route_port: returned destination port for specified destID
1330  */
1331 static int
1332 rio_std_route_get_entry(struct rio_mport *mport, u16 destid, u8 hopcount,
1333                         u16 table, u16 route_destid, u8 *route_port)
1334 {
1335         u32 result;
1336
1337         if (table == RIO_GLOBAL_TABLE) {
1338                 rio_mport_write_config_32(mport, destid, hopcount,
1339                                 RIO_STD_RTE_CONF_DESTID_SEL_CSR, route_destid);
1340                 rio_mport_read_config_32(mport, destid, hopcount,
1341                                 RIO_STD_RTE_CONF_PORT_SEL_CSR, &result);
1342
1343                 *route_port = (u8)result;
1344         }
1345
1346         return 0;
1347 }
1348
1349 /**
1350  * rio_std_route_clr_table - Clear swotch route table using standard registers
1351  *   defined in RIO specification rev.1.3.
1352  * @mport: Master port to issue transaction
1353  * @destid: Destination ID of the device
1354  * @hopcount: Number of switch hops to the device
1355  * @table: routing table ID (global or port-specific)
1356  */
1357 static int
1358 rio_std_route_clr_table(struct rio_mport *mport, u16 destid, u8 hopcount,
1359                         u16 table)
1360 {
1361         u32 max_destid = 0xff;
1362         u32 i, pef, id_inc = 1, ext_cfg = 0;
1363         u32 port_sel = RIO_INVALID_ROUTE;
1364
1365         if (table == RIO_GLOBAL_TABLE) {
1366                 rio_mport_read_config_32(mport, destid, hopcount,
1367                                          RIO_PEF_CAR, &pef);
1368
1369                 if (mport->sys_size) {
1370                         rio_mport_read_config_32(mport, destid, hopcount,
1371                                                  RIO_SWITCH_RT_LIMIT,
1372                                                  &max_destid);
1373                         max_destid &= RIO_RT_MAX_DESTID;
1374                 }
1375
1376                 if (pef & RIO_PEF_EXT_RT) {
1377                         ext_cfg = 0x80000000;
1378                         id_inc = 4;
1379                         port_sel = (RIO_INVALID_ROUTE << 24) |
1380                                    (RIO_INVALID_ROUTE << 16) |
1381                                    (RIO_INVALID_ROUTE << 8) |
1382                                    RIO_INVALID_ROUTE;
1383                 }
1384
1385                 for (i = 0; i <= max_destid;) {
1386                         rio_mport_write_config_32(mport, destid, hopcount,
1387                                         RIO_STD_RTE_CONF_DESTID_SEL_CSR,
1388                                         ext_cfg | i);
1389                         rio_mport_write_config_32(mport, destid, hopcount,
1390                                         RIO_STD_RTE_CONF_PORT_SEL_CSR,
1391                                         port_sel);
1392                         i += id_inc;
1393                 }
1394         }
1395
1396         udelay(10);
1397         return 0;
1398 }
1399
1400 /**
1401  * rio_lock_device - Acquires host device lock for specified device
1402  * @port: Master port to send transaction
1403  * @destid: Destination ID for device/switch
1404  * @hopcount: Hopcount to reach switch
1405  * @wait_ms: Max wait time in msec (0 = no timeout)
1406  *
1407  * Attepts to acquire host device lock for specified device
1408  * Returns 0 if device lock acquired or EINVAL if timeout expires.
1409  */
1410 int rio_lock_device(struct rio_mport *port, u16 destid,
1411                     u8 hopcount, int wait_ms)
1412 {
1413         u32 result;
1414         int tcnt = 0;
1415
1416         /* Attempt to acquire device lock */
1417         rio_mport_write_config_32(port, destid, hopcount,
1418                                   RIO_HOST_DID_LOCK_CSR, port->host_deviceid);
1419         rio_mport_read_config_32(port, destid, hopcount,
1420                                  RIO_HOST_DID_LOCK_CSR, &result);
1421
1422         while (result != port->host_deviceid) {
1423                 if (wait_ms != 0 && tcnt == wait_ms) {
1424                         pr_debug("RIO: timeout when locking device %x:%x\n",
1425                                 destid, hopcount);
1426                         return -EINVAL;
1427                 }
1428
1429                 /* Delay a bit */
1430                 mdelay(1);
1431                 tcnt++;
1432                 /* Try to acquire device lock again */
1433                 rio_mport_write_config_32(port, destid,
1434                         hopcount,
1435                         RIO_HOST_DID_LOCK_CSR,
1436                         port->host_deviceid);
1437                 rio_mport_read_config_32(port, destid,
1438                         hopcount,
1439                         RIO_HOST_DID_LOCK_CSR, &result);
1440         }
1441
1442         return 0;
1443 }
1444 EXPORT_SYMBOL_GPL(rio_lock_device);
1445
1446 /**
1447  * rio_unlock_device - Releases host device lock for specified device
1448  * @port: Master port to send transaction
1449  * @destid: Destination ID for device/switch
1450  * @hopcount: Hopcount to reach switch
1451  *
1452  * Returns 0 if device lock released or EINVAL if fails.
1453  */
1454 int rio_unlock_device(struct rio_mport *port, u16 destid, u8 hopcount)
1455 {
1456         u32 result;
1457
1458         /* Release device lock */
1459         rio_mport_write_config_32(port, destid,
1460                                   hopcount,
1461                                   RIO_HOST_DID_LOCK_CSR,
1462                                   port->host_deviceid);
1463         rio_mport_read_config_32(port, destid, hopcount,
1464                 RIO_HOST_DID_LOCK_CSR, &result);
1465         if ((result & 0xffff) != 0xffff) {
1466                 pr_debug("RIO: badness when releasing device lock %x:%x\n",
1467                          destid, hopcount);
1468                 return -EINVAL;
1469         }
1470
1471         return 0;
1472 }
1473 EXPORT_SYMBOL_GPL(rio_unlock_device);
1474
1475 /**
1476  * rio_route_add_entry- Add a route entry to a switch routing table
1477  * @rdev: RIO device
1478  * @table: Routing table ID
1479  * @route_destid: Destination ID to be routed
1480  * @route_port: Port number to be routed
1481  * @lock: apply a hardware lock on switch device flag (1=lock, 0=no_lock)
1482  *
1483  * If available calls the switch specific add_entry() method to add a route
1484  * entry into a switch routing table. Otherwise uses standard RT update method
1485  * as defined by RapidIO specification. A specific routing table can be selected
1486  * using the @table argument if a switch has per port routing tables or
1487  * the standard (or global) table may be used by passing
1488  * %RIO_GLOBAL_TABLE in @table.
1489  *
1490  * Returns %0 on success or %-EINVAL on failure.
1491  */
1492 int rio_route_add_entry(struct rio_dev *rdev,
1493                         u16 table, u16 route_destid, u8 route_port, int lock)
1494 {
1495         int rc = -EINVAL;
1496         struct rio_switch_ops *ops = rdev->rswitch->ops;
1497
1498         if (lock) {
1499                 rc = rio_lock_device(rdev->net->hport, rdev->destid,
1500                                      rdev->hopcount, 1000);
1501                 if (rc)
1502                         return rc;
1503         }
1504
1505         spin_lock(&rdev->rswitch->lock);
1506
1507         if (ops == NULL || ops->add_entry == NULL) {
1508                 rc = rio_std_route_add_entry(rdev->net->hport, rdev->destid,
1509                                              rdev->hopcount, table,
1510                                              route_destid, route_port);
1511         } else if (try_module_get(ops->owner)) {
1512                 rc = ops->add_entry(rdev->net->hport, rdev->destid,
1513                                     rdev->hopcount, table, route_destid,
1514                                     route_port);
1515                 module_put(ops->owner);
1516         }
1517
1518         spin_unlock(&rdev->rswitch->lock);
1519
1520         if (lock)
1521                 rio_unlock_device(rdev->net->hport, rdev->destid,
1522                                   rdev->hopcount);
1523
1524         return rc;
1525 }
1526 EXPORT_SYMBOL_GPL(rio_route_add_entry);
1527
1528 /**
1529  * rio_route_get_entry- Read an entry from a switch routing table
1530  * @rdev: RIO device
1531  * @table: Routing table ID
1532  * @route_destid: Destination ID to be routed
1533  * @route_port: Pointer to read port number into
1534  * @lock: apply a hardware lock on switch device flag (1=lock, 0=no_lock)
1535  *
1536  * If available calls the switch specific get_entry() method to fetch a route
1537  * entry from a switch routing table. Otherwise uses standard RT read method
1538  * as defined by RapidIO specification. A specific routing table can be selected
1539  * using the @table argument if a switch has per port routing tables or
1540  * the standard (or global) table may be used by passing
1541  * %RIO_GLOBAL_TABLE in @table.
1542  *
1543  * Returns %0 on success or %-EINVAL on failure.
1544  */
1545 int rio_route_get_entry(struct rio_dev *rdev, u16 table,
1546                         u16 route_destid, u8 *route_port, int lock)
1547 {
1548         int rc = -EINVAL;
1549         struct rio_switch_ops *ops = rdev->rswitch->ops;
1550
1551         if (lock) {
1552                 rc = rio_lock_device(rdev->net->hport, rdev->destid,
1553                                      rdev->hopcount, 1000);
1554                 if (rc)
1555                         return rc;
1556         }
1557
1558         spin_lock(&rdev->rswitch->lock);
1559
1560         if (ops == NULL || ops->get_entry == NULL) {
1561                 rc = rio_std_route_get_entry(rdev->net->hport, rdev->destid,
1562                                              rdev->hopcount, table,
1563                                              route_destid, route_port);
1564         } else if (try_module_get(ops->owner)) {
1565                 rc = ops->get_entry(rdev->net->hport, rdev->destid,
1566                                     rdev->hopcount, table, route_destid,
1567                                     route_port);
1568                 module_put(ops->owner);
1569         }
1570
1571         spin_unlock(&rdev->rswitch->lock);
1572
1573         if (lock)
1574                 rio_unlock_device(rdev->net->hport, rdev->destid,
1575                                   rdev->hopcount);
1576         return rc;
1577 }
1578 EXPORT_SYMBOL_GPL(rio_route_get_entry);
1579
1580 /**
1581  * rio_route_clr_table - Clear a switch routing table
1582  * @rdev: RIO device
1583  * @table: Routing table ID
1584  * @lock: apply a hardware lock on switch device flag (1=lock, 0=no_lock)
1585  *
1586  * If available calls the switch specific clr_table() method to clear a switch
1587  * routing table. Otherwise uses standard RT write method as defined by RapidIO
1588  * specification. A specific routing table can be selected using the @table
1589  * argument if a switch has per port routing tables or the standard (or global)
1590  * table may be used by passing %RIO_GLOBAL_TABLE in @table.
1591  *
1592  * Returns %0 on success or %-EINVAL on failure.
1593  */
1594 int rio_route_clr_table(struct rio_dev *rdev, u16 table, int lock)
1595 {
1596         int rc = -EINVAL;
1597         struct rio_switch_ops *ops = rdev->rswitch->ops;
1598
1599         if (lock) {
1600                 rc = rio_lock_device(rdev->net->hport, rdev->destid,
1601                                      rdev->hopcount, 1000);
1602                 if (rc)
1603                         return rc;
1604         }
1605
1606         spin_lock(&rdev->rswitch->lock);
1607
1608         if (ops == NULL || ops->clr_table == NULL) {
1609                 rc = rio_std_route_clr_table(rdev->net->hport, rdev->destid,
1610                                              rdev->hopcount, table);
1611         } else if (try_module_get(ops->owner)) {
1612                 rc = ops->clr_table(rdev->net->hport, rdev->destid,
1613                                     rdev->hopcount, table);
1614
1615                 module_put(ops->owner);
1616         }
1617
1618         spin_unlock(&rdev->rswitch->lock);
1619
1620         if (lock)
1621                 rio_unlock_device(rdev->net->hport, rdev->destid,
1622                                   rdev->hopcount);
1623
1624         return rc;
1625 }
1626 EXPORT_SYMBOL_GPL(rio_route_clr_table);
1627
1628 #ifdef CONFIG_RAPIDIO_DMA_ENGINE
1629
1630 static bool rio_chan_filter(struct dma_chan *chan, void *arg)
1631 {
1632         struct rio_mport *mport = arg;
1633
1634         /* Check that DMA device belongs to the right MPORT */
1635         return mport == container_of(chan->device, struct rio_mport, dma);
1636 }
1637
1638 /**
1639  * rio_request_mport_dma - request RapidIO capable DMA channel associated
1640  *   with specified local RapidIO mport device.
1641  * @mport: RIO mport to perform DMA data transfers
1642  *
1643  * Returns pointer to allocated DMA channel or NULL if failed.
1644  */
1645 struct dma_chan *rio_request_mport_dma(struct rio_mport *mport)
1646 {
1647         dma_cap_mask_t mask;
1648
1649         dma_cap_zero(mask);
1650         dma_cap_set(DMA_SLAVE, mask);
1651         return dma_request_channel(mask, rio_chan_filter, mport);
1652 }
1653 EXPORT_SYMBOL_GPL(rio_request_mport_dma);
1654
1655 /**
1656  * rio_request_dma - request RapidIO capable DMA channel that supports
1657  *   specified target RapidIO device.
1658  * @rdev: RIO device associated with DMA transfer
1659  *
1660  * Returns pointer to allocated DMA channel or NULL if failed.
1661  */
1662 struct dma_chan *rio_request_dma(struct rio_dev *rdev)
1663 {
1664         return rio_request_mport_dma(rdev->net->hport);
1665 }
1666 EXPORT_SYMBOL_GPL(rio_request_dma);
1667
1668 /**
1669  * rio_release_dma - release specified DMA channel
1670  * @dchan: DMA channel to release
1671  */
1672 void rio_release_dma(struct dma_chan *dchan)
1673 {
1674         dma_release_channel(dchan);
1675 }
1676 EXPORT_SYMBOL_GPL(rio_release_dma);
1677
1678 /**
1679  * rio_dma_prep_xfer - RapidIO specific wrapper
1680  *   for device_prep_slave_sg callback defined by DMAENGINE.
1681  * @dchan: DMA channel to configure
1682  * @destid: target RapidIO device destination ID
1683  * @data: RIO specific data descriptor
1684  * @direction: DMA data transfer direction (TO or FROM the device)
1685  * @flags: dmaengine defined flags
1686  *
1687  * Initializes RapidIO capable DMA channel for the specified data transfer.
1688  * Uses DMA channel private extension to pass information related to remote
1689  * target RIO device.
1690  * Returns pointer to DMA transaction descriptor or NULL if failed.
1691  */
1692 struct dma_async_tx_descriptor *rio_dma_prep_xfer(struct dma_chan *dchan,
1693         u16 destid, struct rio_dma_data *data,
1694         enum dma_transfer_direction direction, unsigned long flags)
1695 {
1696         struct rio_dma_ext rio_ext;
1697
1698         if (dchan->device->device_prep_slave_sg == NULL) {
1699                 pr_err("%s: prep_rio_sg == NULL\n", __func__);
1700                 return NULL;
1701         }
1702
1703         rio_ext.destid = destid;
1704         rio_ext.rio_addr_u = data->rio_addr_u;
1705         rio_ext.rio_addr = data->rio_addr;
1706         rio_ext.wr_type = data->wr_type;
1707
1708         return dmaengine_prep_rio_sg(dchan, data->sg, data->sg_len,
1709                                      direction, flags, &rio_ext);
1710 }
1711 EXPORT_SYMBOL_GPL(rio_dma_prep_xfer);
1712
1713 /**
1714  * rio_dma_prep_slave_sg - RapidIO specific wrapper
1715  *   for device_prep_slave_sg callback defined by DMAENGINE.
1716  * @rdev: RIO device control structure
1717  * @dchan: DMA channel to configure
1718  * @data: RIO specific data descriptor
1719  * @direction: DMA data transfer direction (TO or FROM the device)
1720  * @flags: dmaengine defined flags
1721  *
1722  * Initializes RapidIO capable DMA channel for the specified data transfer.
1723  * Uses DMA channel private extension to pass information related to remote
1724  * target RIO device.
1725  * Returns pointer to DMA transaction descriptor or NULL if failed.
1726  */
1727 struct dma_async_tx_descriptor *rio_dma_prep_slave_sg(struct rio_dev *rdev,
1728         struct dma_chan *dchan, struct rio_dma_data *data,
1729         enum dma_transfer_direction direction, unsigned long flags)
1730 {
1731         return rio_dma_prep_xfer(dchan, rdev->destid, data, direction, flags);
1732 }
1733 EXPORT_SYMBOL_GPL(rio_dma_prep_slave_sg);
1734
1735 #endif /* CONFIG_RAPIDIO_DMA_ENGINE */
1736
1737 /**
1738  * rio_find_mport - find RIO mport by its ID
1739  * @mport_id: number (ID) of mport device
1740  *
1741  * Given a RIO mport number, the desired mport is located
1742  * in the global list of mports. If the mport is found, a pointer to its
1743  * data structure is returned.  If no mport is found, %NULL is returned.
1744  */
1745 struct rio_mport *rio_find_mport(int mport_id)
1746 {
1747         struct rio_mport *port;
1748
1749         mutex_lock(&rio_mport_list_lock);
1750         list_for_each_entry(port, &rio_mports, node) {
1751                 if (port->id == mport_id)
1752                         goto found;
1753         }
1754         port = NULL;
1755 found:
1756         mutex_unlock(&rio_mport_list_lock);
1757
1758         return port;
1759 }
1760
1761 /**
1762  * rio_register_scan - enumeration/discovery method registration interface
1763  * @mport_id: mport device ID for which fabric scan routine has to be set
1764  *            (RIO_MPORT_ANY = set for all available mports)
1765  * @scan_ops: enumeration/discovery operations structure
1766  *
1767  * Registers enumeration/discovery operations with RapidIO subsystem and
1768  * attaches it to the specified mport device (or all available mports
1769  * if RIO_MPORT_ANY is specified).
1770  *
1771  * Returns error if the mport already has an enumerator attached to it.
1772  * In case of RIO_MPORT_ANY skips mports with valid scan routines (no error).
1773  */
1774 int rio_register_scan(int mport_id, struct rio_scan *scan_ops)
1775 {
1776         struct rio_mport *port;
1777         struct rio_scan_node *scan;
1778         int rc = 0;
1779
1780         pr_debug("RIO: %s for mport_id=%d\n", __func__, mport_id);
1781
1782         if ((mport_id != RIO_MPORT_ANY && mport_id >= RIO_MAX_MPORTS) ||
1783             !scan_ops)
1784                 return -EINVAL;
1785
1786         mutex_lock(&rio_mport_list_lock);
1787
1788         /*
1789          * Check if there is another enumerator already registered for
1790          * the same mport ID (including RIO_MPORT_ANY). Multiple enumerators
1791          * for the same mport ID are not supported.
1792          */
1793         list_for_each_entry(scan, &rio_scans, node) {
1794                 if (scan->mport_id == mport_id) {
1795                         rc = -EBUSY;
1796                         goto err_out;
1797                 }
1798         }
1799
1800         /*
1801          * Allocate and initialize new scan registration node.
1802          */
1803         scan = kzalloc(sizeof(*scan), GFP_KERNEL);
1804         if (!scan) {
1805                 rc = -ENOMEM;
1806                 goto err_out;
1807         }
1808
1809         scan->mport_id = mport_id;
1810         scan->ops = scan_ops;
1811
1812         /*
1813          * Traverse the list of registered mports to attach this new scan.
1814          *
1815          * The new scan with matching mport ID overrides any previously attached
1816          * scan assuming that old scan (if any) is the default one (based on the
1817          * enumerator registration check above).
1818          * If the new scan is the global one, it will be attached only to mports
1819          * that do not have their own individual operations already attached.
1820          */
1821         list_for_each_entry(port, &rio_mports, node) {
1822                 if (port->id == mport_id) {
1823                         port->nscan = scan_ops;
1824                         break;
1825                 } else if (mport_id == RIO_MPORT_ANY && !port->nscan)
1826                         port->nscan = scan_ops;
1827         }
1828
1829         list_add_tail(&scan->node, &rio_scans);
1830
1831 err_out:
1832         mutex_unlock(&rio_mport_list_lock);
1833
1834         return rc;
1835 }
1836 EXPORT_SYMBOL_GPL(rio_register_scan);
1837
1838 /**
1839  * rio_unregister_scan - removes enumeration/discovery method from mport
1840  * @mport_id: mport device ID for which fabric scan routine has to be
1841  *            unregistered (RIO_MPORT_ANY = apply to all mports that use
1842  *            the specified scan_ops)
1843  * @scan_ops: enumeration/discovery operations structure
1844  *
1845  * Removes enumeration or discovery method assigned to the specified mport
1846  * device. If RIO_MPORT_ANY is specified, removes the specified operations from
1847  * all mports that have them attached.
1848  */
1849 int rio_unregister_scan(int mport_id, struct rio_scan *scan_ops)
1850 {
1851         struct rio_mport *port;
1852         struct rio_scan_node *scan;
1853
1854         pr_debug("RIO: %s for mport_id=%d\n", __func__, mport_id);
1855
1856         if (mport_id != RIO_MPORT_ANY && mport_id >= RIO_MAX_MPORTS)
1857                 return -EINVAL;
1858
1859         mutex_lock(&rio_mport_list_lock);
1860
1861         list_for_each_entry(port, &rio_mports, node)
1862                 if (port->id == mport_id ||
1863                     (mport_id == RIO_MPORT_ANY && port->nscan == scan_ops))
1864                         port->nscan = NULL;
1865
1866         list_for_each_entry(scan, &rio_scans, node) {
1867                 if (scan->mport_id == mport_id) {
1868                         list_del(&scan->node);
1869                         kfree(scan);
1870                         break;
1871                 }
1872         }
1873
1874         mutex_unlock(&rio_mport_list_lock);
1875
1876         return 0;
1877 }
1878 EXPORT_SYMBOL_GPL(rio_unregister_scan);
1879
1880 /**
1881  * rio_mport_scan - execute enumeration/discovery on the specified mport
1882  * @mport_id: number (ID) of mport device
1883  */
1884 int rio_mport_scan(int mport_id)
1885 {
1886         struct rio_mport *port = NULL;
1887         int rc;
1888
1889         mutex_lock(&rio_mport_list_lock);
1890         list_for_each_entry(port, &rio_mports, node) {
1891                 if (port->id == mport_id)
1892                         goto found;
1893         }
1894         mutex_unlock(&rio_mport_list_lock);
1895         return -ENODEV;
1896 found:
1897         if (!port->nscan) {
1898                 mutex_unlock(&rio_mport_list_lock);
1899                 return -EINVAL;
1900         }
1901
1902         if (!try_module_get(port->nscan->owner)) {
1903                 mutex_unlock(&rio_mport_list_lock);
1904                 return -ENODEV;
1905         }
1906
1907         mutex_unlock(&rio_mport_list_lock);
1908
1909         if (port->host_deviceid >= 0)
1910                 rc = port->nscan->enumerate(port, 0);
1911         else
1912                 rc = port->nscan->discover(port, RIO_SCAN_ENUM_NO_WAIT);
1913
1914         module_put(port->nscan->owner);
1915         return rc;
1916 }
1917
1918 static void rio_fixup_device(struct rio_dev *dev)
1919 {
1920 }
1921
1922 static int rio_init(void)
1923 {
1924         struct rio_dev *dev = NULL;
1925
1926         while ((dev = rio_get_device(RIO_ANY_ID, RIO_ANY_ID, dev)) != NULL) {
1927                 rio_fixup_device(dev);
1928         }
1929         return 0;
1930 }
1931
1932 static struct workqueue_struct *rio_wq;
1933
1934 struct rio_disc_work {
1935         struct work_struct      work;
1936         struct rio_mport        *mport;
1937 };
1938
1939 static void disc_work_handler(struct work_struct *_work)
1940 {
1941         struct rio_disc_work *work;
1942
1943         work = container_of(_work, struct rio_disc_work, work);
1944         pr_debug("RIO: discovery work for mport %d %s\n",
1945                  work->mport->id, work->mport->name);
1946         if (try_module_get(work->mport->nscan->owner)) {
1947                 work->mport->nscan->discover(work->mport, 0);
1948                 module_put(work->mport->nscan->owner);
1949         }
1950 }
1951
1952 int rio_init_mports(void)
1953 {
1954         struct rio_mport *port;
1955         struct rio_disc_work *work;
1956         int n = 0;
1957
1958         if (!next_portid)
1959                 return -ENODEV;
1960
1961         /*
1962          * First, run enumerations and check if we need to perform discovery
1963          * on any of the registered mports.
1964          */
1965         mutex_lock(&rio_mport_list_lock);
1966         list_for_each_entry(port, &rio_mports, node) {
1967                 if (port->host_deviceid >= 0) {
1968                         if (port->nscan && try_module_get(port->nscan->owner)) {
1969                                 port->nscan->enumerate(port, 0);
1970                                 module_put(port->nscan->owner);
1971                         }
1972                 } else
1973                         n++;
1974         }
1975         mutex_unlock(&rio_mport_list_lock);
1976
1977         if (!n)
1978                 goto no_disc;
1979
1980         /*
1981          * If we have mports that require discovery schedule a discovery work
1982          * for each of them. If the code below fails to allocate needed
1983          * resources, exit without error to keep results of enumeration
1984          * process (if any).
1985          * TODO: Implement restart of discovery process for all or
1986          * individual discovering mports.
1987          */
1988         rio_wq = alloc_workqueue("riodisc", 0, 0);
1989         if (!rio_wq) {
1990                 pr_err("RIO: unable allocate rio_wq\n");
1991                 goto no_disc;
1992         }
1993
1994         work = kcalloc(n, sizeof *work, GFP_KERNEL);
1995         if (!work) {
1996                 pr_err("RIO: no memory for work struct\n");
1997                 destroy_workqueue(rio_wq);
1998                 goto no_disc;
1999         }
2000
2001         n = 0;
2002         mutex_lock(&rio_mport_list_lock);
2003         list_for_each_entry(port, &rio_mports, node) {
2004                 if (port->host_deviceid < 0 && port->nscan) {
2005                         work[n].mport = port;
2006                         INIT_WORK(&work[n].work, disc_work_handler);
2007                         queue_work(rio_wq, &work[n].work);
2008                         n++;
2009                 }
2010         }
2011
2012         flush_workqueue(rio_wq);
2013         mutex_unlock(&rio_mport_list_lock);
2014         pr_debug("RIO: destroy discovery workqueue\n");
2015         destroy_workqueue(rio_wq);
2016         kfree(work);
2017
2018 no_disc:
2019         rio_init();
2020
2021         return 0;
2022 }
2023
2024 static int rio_get_hdid(int index)
2025 {
2026         if (ids_num == 0 || ids_num <= index || index >= RIO_MAX_MPORTS)
2027                 return -1;
2028
2029         return hdid[index];
2030 }
2031
2032 int rio_mport_initialize(struct rio_mport *mport)
2033 {
2034         if (next_portid >= RIO_MAX_MPORTS) {
2035                 pr_err("RIO: reached specified max number of mports\n");
2036                 return -ENODEV;
2037         }
2038
2039         atomic_set(&mport->state, RIO_DEVICE_INITIALIZING);
2040         mport->id = next_portid++;
2041         mport->host_deviceid = rio_get_hdid(mport->id);
2042         mport->nscan = NULL;
2043         mutex_init(&mport->lock);
2044
2045         return 0;
2046 }
2047 EXPORT_SYMBOL_GPL(rio_mport_initialize);
2048
2049 int rio_register_mport(struct rio_mport *port)
2050 {
2051         struct rio_scan_node *scan = NULL;
2052         int res = 0;
2053
2054         mutex_lock(&rio_mport_list_lock);
2055
2056         /*
2057          * Check if there are any registered enumeration/discovery operations
2058          * that have to be attached to the added mport.
2059          */
2060         list_for_each_entry(scan, &rio_scans, node) {
2061                 if (port->id == scan->mport_id ||
2062                     scan->mport_id == RIO_MPORT_ANY) {
2063                         port->nscan = scan->ops;
2064                         if (port->id == scan->mport_id)
2065                                 break;
2066                 }
2067         }
2068
2069         list_add_tail(&port->node, &rio_mports);
2070         mutex_unlock(&rio_mport_list_lock);
2071
2072         dev_set_name(&port->dev, "rapidio%d", port->id);
2073         port->dev.class = &rio_mport_class;
2074         atomic_set(&port->state, RIO_DEVICE_RUNNING);
2075
2076         res = device_register(&port->dev);
2077         if (res)
2078                 dev_err(&port->dev, "RIO: mport%d registration failed ERR=%d\n",
2079                         port->id, res);
2080         else
2081                 dev_dbg(&port->dev, "RIO: registered mport%d\n", port->id);
2082
2083         return res;
2084 }
2085 EXPORT_SYMBOL_GPL(rio_register_mport);
2086
2087 static int rio_mport_cleanup_callback(struct device *dev, void *data)
2088 {
2089         struct rio_dev *rdev = to_rio_dev(dev);
2090
2091         if (dev->bus == &rio_bus_type)
2092                 rio_del_device(rdev, RIO_DEVICE_SHUTDOWN);
2093         return 0;
2094 }
2095
2096 static int rio_net_remove_children(struct rio_net *net)
2097 {
2098         /*
2099          * Unregister all RapidIO devices residing on this net (this will
2100          * invoke notification of registered subsystem interfaces as well).
2101          */
2102         device_for_each_child(&net->dev, NULL, rio_mport_cleanup_callback);
2103         return 0;
2104 }
2105
2106 int rio_unregister_mport(struct rio_mport *port)
2107 {
2108         pr_debug("RIO: %s %s id=%d\n", __func__, port->name, port->id);
2109
2110         /* Transition mport to the SHUTDOWN state */
2111         if (atomic_cmpxchg(&port->state,
2112                            RIO_DEVICE_RUNNING,
2113                            RIO_DEVICE_SHUTDOWN) != RIO_DEVICE_RUNNING) {
2114                 pr_err("RIO: %s unexpected state transition for mport %s\n",
2115                         __func__, port->name);
2116         }
2117
2118         if (port->net && port->net->hport == port) {
2119                 rio_net_remove_children(port->net);
2120                 rio_free_net(port->net);
2121         }
2122
2123         /*
2124          * Unregister all RapidIO devices attached to this mport (this will
2125          * invoke notification of registered subsystem interfaces as well).
2126          */
2127         mutex_lock(&rio_mport_list_lock);
2128         list_del(&port->node);
2129         mutex_unlock(&rio_mport_list_lock);
2130         device_unregister(&port->dev);
2131
2132         return 0;
2133 }
2134 EXPORT_SYMBOL_GPL(rio_unregister_mport);
2135
2136 EXPORT_SYMBOL_GPL(rio_local_get_device_id);
2137 EXPORT_SYMBOL_GPL(rio_get_device);
2138 EXPORT_SYMBOL_GPL(rio_get_asm);
2139 EXPORT_SYMBOL_GPL(rio_request_inb_dbell);
2140 EXPORT_SYMBOL_GPL(rio_release_inb_dbell);
2141 EXPORT_SYMBOL_GPL(rio_request_outb_dbell);
2142 EXPORT_SYMBOL_GPL(rio_release_outb_dbell);
2143 EXPORT_SYMBOL_GPL(rio_request_inb_mbox);
2144 EXPORT_SYMBOL_GPL(rio_release_inb_mbox);
2145 EXPORT_SYMBOL_GPL(rio_request_outb_mbox);
2146 EXPORT_SYMBOL_GPL(rio_release_outb_mbox);
2147 EXPORT_SYMBOL_GPL(rio_init_mports);