IB/umad: Add P_Key index support
[safe/jmp/linux-2.6] / drivers / infiniband / core / user_mad.c
1 /*
2  * Copyright (c) 2004 Topspin Communications.  All rights reserved.
3  * Copyright (c) 2005 Voltaire, Inc. All rights reserved.
4  * Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
5  *
6  * This software is available to you under a choice of one of two
7  * licenses.  You may choose to be licensed under the terms of the GNU
8  * General Public License (GPL) Version 2, available from the file
9  * COPYING in the main directory of this source tree, or the
10  * OpenIB.org BSD license below:
11  *
12  *     Redistribution and use in source and binary forms, with or
13  *     without modification, are permitted provided that the following
14  *     conditions are met:
15  *
16  *      - Redistributions of source code must retain the above
17  *        copyright notice, this list of conditions and the following
18  *        disclaimer.
19  *
20  *      - Redistributions in binary form must reproduce the above
21  *        copyright notice, this list of conditions and the following
22  *        disclaimer in the documentation and/or other materials
23  *        provided with the distribution.
24  *
25  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
29  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
30  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
31  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32  * SOFTWARE.
33  *
34  * $Id: user_mad.c 5596 2006-03-03 01:00:07Z sean.hefty $
35  */
36
37 #include <linux/module.h>
38 #include <linux/init.h>
39 #include <linux/device.h>
40 #include <linux/err.h>
41 #include <linux/fs.h>
42 #include <linux/cdev.h>
43 #include <linux/dma-mapping.h>
44 #include <linux/poll.h>
45 #include <linux/rwsem.h>
46 #include <linux/kref.h>
47
48 #include <asm/uaccess.h>
49 #include <asm/semaphore.h>
50
51 #include <rdma/ib_mad.h>
52 #include <rdma/ib_user_mad.h>
53
54 MODULE_AUTHOR("Roland Dreier");
55 MODULE_DESCRIPTION("InfiniBand userspace MAD packet access");
56 MODULE_LICENSE("Dual BSD/GPL");
57
58 enum {
59         IB_UMAD_MAX_PORTS  = 64,
60         IB_UMAD_MAX_AGENTS = 32,
61
62         IB_UMAD_MAJOR      = 231,
63         IB_UMAD_MINOR_BASE = 0
64 };
65
66 /*
67  * Our lifetime rules for these structs are the following: each time a
68  * device special file is opened, we look up the corresponding struct
69  * ib_umad_port by minor in the umad_port[] table while holding the
70  * port_lock.  If this lookup succeeds, we take a reference on the
71  * ib_umad_port's struct ib_umad_device while still holding the
72  * port_lock; if the lookup fails, we fail the open().  We drop these
73  * references in the corresponding close().
74  *
75  * In addition to references coming from open character devices, there
76  * is one more reference to each ib_umad_device representing the
77  * module's reference taken when allocating the ib_umad_device in
78  * ib_umad_add_one().
79  *
80  * When destroying an ib_umad_device, we clear all of its
81  * ib_umad_ports from umad_port[] while holding port_lock before
82  * dropping the module's reference to the ib_umad_device.  This is
83  * always safe because any open() calls will either succeed and obtain
84  * a reference before we clear the umad_port[] entries, or fail after
85  * we clear the umad_port[] entries.
86  */
87
88 struct ib_umad_port {
89         struct cdev           *dev;
90         struct class_device   *class_dev;
91
92         struct cdev           *sm_dev;
93         struct class_device   *sm_class_dev;
94         struct semaphore       sm_sem;
95
96         struct rw_semaphore    mutex;
97         struct list_head       file_list;
98
99         struct ib_device      *ib_dev;
100         struct ib_umad_device *umad_dev;
101         int                    dev_num;
102         u8                     port_num;
103 };
104
105 struct ib_umad_device {
106         int                  start_port, end_port;
107         struct kref          ref;
108         struct ib_umad_port  port[0];
109 };
110
111 struct ib_umad_file {
112         struct ib_umad_port    *port;
113         struct list_head        recv_list;
114         struct list_head        send_list;
115         struct list_head        port_list;
116         spinlock_t              recv_lock;
117         spinlock_t              send_lock;
118         wait_queue_head_t       recv_wait;
119         struct ib_mad_agent    *agent[IB_UMAD_MAX_AGENTS];
120         int                     agents_dead;
121         u8                      use_pkey_index;
122         u8                      already_used;
123 };
124
125 struct ib_umad_packet {
126         struct ib_mad_send_buf *msg;
127         struct ib_mad_recv_wc  *recv_wc;
128         struct list_head   list;
129         int                length;
130         struct ib_user_mad mad;
131 };
132
133 static struct class *umad_class;
134
135 static const dev_t base_dev = MKDEV(IB_UMAD_MAJOR, IB_UMAD_MINOR_BASE);
136
137 static DEFINE_SPINLOCK(port_lock);
138 static struct ib_umad_port *umad_port[IB_UMAD_MAX_PORTS];
139 static DECLARE_BITMAP(dev_map, IB_UMAD_MAX_PORTS);
140
141 static void ib_umad_add_one(struct ib_device *device);
142 static void ib_umad_remove_one(struct ib_device *device);
143
144 static void ib_umad_release_dev(struct kref *ref)
145 {
146         struct ib_umad_device *dev =
147                 container_of(ref, struct ib_umad_device, ref);
148
149         kfree(dev);
150 }
151
152 static int hdr_size(struct ib_umad_file *file)
153 {
154         return file->use_pkey_index ? sizeof (struct ib_user_mad_hdr) :
155                 sizeof (struct ib_user_mad_hdr_old);
156 }
157
158 /* caller must hold port->mutex at least for reading */
159 static struct ib_mad_agent *__get_agent(struct ib_umad_file *file, int id)
160 {
161         return file->agents_dead ? NULL : file->agent[id];
162 }
163
164 static int queue_packet(struct ib_umad_file *file,
165                         struct ib_mad_agent *agent,
166                         struct ib_umad_packet *packet)
167 {
168         int ret = 1;
169
170         down_read(&file->port->mutex);
171
172         for (packet->mad.hdr.id = 0;
173              packet->mad.hdr.id < IB_UMAD_MAX_AGENTS;
174              packet->mad.hdr.id++)
175                 if (agent == __get_agent(file, packet->mad.hdr.id)) {
176                         spin_lock_irq(&file->recv_lock);
177                         list_add_tail(&packet->list, &file->recv_list);
178                         spin_unlock_irq(&file->recv_lock);
179                         wake_up_interruptible(&file->recv_wait);
180                         ret = 0;
181                         break;
182                 }
183
184         up_read(&file->port->mutex);
185
186         return ret;
187 }
188
189 static void dequeue_send(struct ib_umad_file *file,
190                          struct ib_umad_packet *packet)
191  {
192         spin_lock_irq(&file->send_lock);
193         list_del(&packet->list);
194         spin_unlock_irq(&file->send_lock);
195  }
196
197 static void send_handler(struct ib_mad_agent *agent,
198                          struct ib_mad_send_wc *send_wc)
199 {
200         struct ib_umad_file *file = agent->context;
201         struct ib_umad_packet *packet = send_wc->send_buf->context[0];
202
203         dequeue_send(file, packet);
204         ib_destroy_ah(packet->msg->ah);
205         ib_free_send_mad(packet->msg);
206
207         if (send_wc->status == IB_WC_RESP_TIMEOUT_ERR) {
208                 packet->length = IB_MGMT_MAD_HDR;
209                 packet->mad.hdr.status = ETIMEDOUT;
210                 if (!queue_packet(file, agent, packet))
211                         return;
212         }
213         kfree(packet);
214 }
215
216 static void recv_handler(struct ib_mad_agent *agent,
217                          struct ib_mad_recv_wc *mad_recv_wc)
218 {
219         struct ib_umad_file *file = agent->context;
220         struct ib_umad_packet *packet;
221
222         if (mad_recv_wc->wc->status != IB_WC_SUCCESS)
223                 goto err1;
224
225         packet = kzalloc(sizeof *packet, GFP_KERNEL);
226         if (!packet)
227                 goto err1;
228
229         packet->length = mad_recv_wc->mad_len;
230         packet->recv_wc = mad_recv_wc;
231
232         packet->mad.hdr.status     = 0;
233         packet->mad.hdr.length     = hdr_size(file) + mad_recv_wc->mad_len;
234         packet->mad.hdr.qpn        = cpu_to_be32(mad_recv_wc->wc->src_qp);
235         packet->mad.hdr.lid        = cpu_to_be16(mad_recv_wc->wc->slid);
236         packet->mad.hdr.sl         = mad_recv_wc->wc->sl;
237         packet->mad.hdr.path_bits  = mad_recv_wc->wc->dlid_path_bits;
238         packet->mad.hdr.pkey_index = mad_recv_wc->wc->pkey_index;
239         packet->mad.hdr.grh_present = !!(mad_recv_wc->wc->wc_flags & IB_WC_GRH);
240         if (packet->mad.hdr.grh_present) {
241                 struct ib_ah_attr ah_attr;
242
243                 ib_init_ah_from_wc(agent->device, agent->port_num,
244                                    mad_recv_wc->wc, mad_recv_wc->recv_buf.grh,
245                                    &ah_attr);
246
247                 packet->mad.hdr.gid_index = ah_attr.grh.sgid_index;
248                 packet->mad.hdr.hop_limit = ah_attr.grh.hop_limit;
249                 packet->mad.hdr.traffic_class = ah_attr.grh.traffic_class;
250                 memcpy(packet->mad.hdr.gid, &ah_attr.grh.dgid, 16);
251                 packet->mad.hdr.flow_label = cpu_to_be32(ah_attr.grh.flow_label);
252         }
253
254         if (queue_packet(file, agent, packet))
255                 goto err2;
256         return;
257
258 err2:
259         kfree(packet);
260 err1:
261         ib_free_recv_mad(mad_recv_wc);
262 }
263
264 static ssize_t copy_recv_mad(struct ib_umad_file *file, char __user *buf,
265                              struct ib_umad_packet *packet, size_t count)
266 {
267         struct ib_mad_recv_buf *recv_buf;
268         int left, seg_payload, offset, max_seg_payload;
269
270         /* We need enough room to copy the first (or only) MAD segment. */
271         recv_buf = &packet->recv_wc->recv_buf;
272         if ((packet->length <= sizeof (*recv_buf->mad) &&
273              count < hdr_size(file) + packet->length) ||
274             (packet->length > sizeof (*recv_buf->mad) &&
275              count < hdr_size(file) + sizeof (*recv_buf->mad)))
276                 return -EINVAL;
277
278         if (copy_to_user(buf, &packet->mad, hdr_size(file)))
279                 return -EFAULT;
280
281         buf += hdr_size(file);
282         seg_payload = min_t(int, packet->length, sizeof (*recv_buf->mad));
283         if (copy_to_user(buf, recv_buf->mad, seg_payload))
284                 return -EFAULT;
285
286         if (seg_payload < packet->length) {
287                 /*
288                  * Multipacket RMPP MAD message. Copy remainder of message.
289                  * Note that last segment may have a shorter payload.
290                  */
291                 if (count < hdr_size(file) + packet->length) {
292                         /*
293                          * The buffer is too small, return the first RMPP segment,
294                          * which includes the RMPP message length.
295                          */
296                         return -ENOSPC;
297                 }
298                 offset = ib_get_mad_data_offset(recv_buf->mad->mad_hdr.mgmt_class);
299                 max_seg_payload = sizeof (struct ib_mad) - offset;
300
301                 for (left = packet->length - seg_payload, buf += seg_payload;
302                      left; left -= seg_payload, buf += seg_payload) {
303                         recv_buf = container_of(recv_buf->list.next,
304                                                 struct ib_mad_recv_buf, list);
305                         seg_payload = min(left, max_seg_payload);
306                         if (copy_to_user(buf, ((void *) recv_buf->mad) + offset,
307                                          seg_payload))
308                                 return -EFAULT;
309                 }
310         }
311         return hdr_size(file) + packet->length;
312 }
313
314 static ssize_t copy_send_mad(struct ib_umad_file *file, char __user *buf,
315                              struct ib_umad_packet *packet, size_t count)
316 {
317         ssize_t size = hdr_size(file) + packet->length;
318
319         if (count < size)
320                 return -EINVAL;
321
322         if (copy_to_user(buf, &packet->mad, hdr_size(file)))
323                 return -EFAULT;
324
325         buf += hdr_size(file);
326
327         if (copy_to_user(buf, packet->mad.data, packet->length))
328                 return -EFAULT;
329
330         return size;
331 }
332
333 static ssize_t ib_umad_read(struct file *filp, char __user *buf,
334                             size_t count, loff_t *pos)
335 {
336         struct ib_umad_file *file = filp->private_data;
337         struct ib_umad_packet *packet;
338         ssize_t ret;
339
340         if (count < hdr_size(file))
341                 return -EINVAL;
342
343         spin_lock_irq(&file->recv_lock);
344
345         while (list_empty(&file->recv_list)) {
346                 spin_unlock_irq(&file->recv_lock);
347
348                 if (filp->f_flags & O_NONBLOCK)
349                         return -EAGAIN;
350
351                 if (wait_event_interruptible(file->recv_wait,
352                                              !list_empty(&file->recv_list)))
353                         return -ERESTARTSYS;
354
355                 spin_lock_irq(&file->recv_lock);
356         }
357
358         packet = list_entry(file->recv_list.next, struct ib_umad_packet, list);
359         list_del(&packet->list);
360
361         spin_unlock_irq(&file->recv_lock);
362
363         if (packet->recv_wc)
364                 ret = copy_recv_mad(file, buf, packet, count);
365         else
366                 ret = copy_send_mad(file, buf, packet, count);
367
368         if (ret < 0) {
369                 /* Requeue packet */
370                 spin_lock_irq(&file->recv_lock);
371                 list_add(&packet->list, &file->recv_list);
372                 spin_unlock_irq(&file->recv_lock);
373         } else {
374                 if (packet->recv_wc)
375                         ib_free_recv_mad(packet->recv_wc);
376                 kfree(packet);
377         }
378         return ret;
379 }
380
381 static int copy_rmpp_mad(struct ib_mad_send_buf *msg, const char __user *buf)
382 {
383         int left, seg;
384
385         /* Copy class specific header */
386         if ((msg->hdr_len > IB_MGMT_RMPP_HDR) &&
387             copy_from_user(msg->mad + IB_MGMT_RMPP_HDR, buf + IB_MGMT_RMPP_HDR,
388                            msg->hdr_len - IB_MGMT_RMPP_HDR))
389                 return -EFAULT;
390
391         /* All headers are in place.  Copy data segments. */
392         for (seg = 1, left = msg->data_len, buf += msg->hdr_len; left > 0;
393              seg++, left -= msg->seg_size, buf += msg->seg_size) {
394                 if (copy_from_user(ib_get_rmpp_segment(msg, seg), buf,
395                                    min(left, msg->seg_size)))
396                         return -EFAULT;
397         }
398         return 0;
399 }
400
401 static int same_destination(struct ib_user_mad_hdr *hdr1,
402                             struct ib_user_mad_hdr *hdr2)
403 {
404         if (!hdr1->grh_present && !hdr2->grh_present)
405            return (hdr1->lid == hdr2->lid);
406
407         if (hdr1->grh_present && hdr2->grh_present)
408            return !memcmp(hdr1->gid, hdr2->gid, 16);
409
410         return 0;
411 }
412
413 static int is_duplicate(struct ib_umad_file *file,
414                         struct ib_umad_packet *packet)
415 {
416         struct ib_umad_packet *sent_packet;
417         struct ib_mad_hdr *sent_hdr, *hdr;
418
419         hdr = (struct ib_mad_hdr *) packet->mad.data;
420         list_for_each_entry(sent_packet, &file->send_list, list) {
421                 sent_hdr = (struct ib_mad_hdr *) sent_packet->mad.data;
422
423                 if ((hdr->tid != sent_hdr->tid) ||
424                     (hdr->mgmt_class != sent_hdr->mgmt_class))
425                         continue;
426
427                 /*
428                  * No need to be overly clever here.  If two new operations have
429                  * the same TID, reject the second as a duplicate.  This is more
430                  * restrictive than required by the spec.
431                  */
432                 if (!ib_response_mad((struct ib_mad *) hdr)) {
433                         if (!ib_response_mad((struct ib_mad *) sent_hdr))
434                                 return 1;
435                         continue;
436                 } else if (!ib_response_mad((struct ib_mad *) sent_hdr))
437                         continue;
438
439                 if (same_destination(&packet->mad.hdr, &sent_packet->mad.hdr))
440                         return 1;
441         }
442
443         return 0;
444 }
445
446 static ssize_t ib_umad_write(struct file *filp, const char __user *buf,
447                              size_t count, loff_t *pos)
448 {
449         struct ib_umad_file *file = filp->private_data;
450         struct ib_umad_packet *packet;
451         struct ib_mad_agent *agent;
452         struct ib_ah_attr ah_attr;
453         struct ib_ah *ah;
454         struct ib_rmpp_mad *rmpp_mad;
455         __be64 *tid;
456         int ret, data_len, hdr_len, copy_offset, rmpp_active;
457
458         if (count < hdr_size(file) + IB_MGMT_RMPP_HDR)
459                 return -EINVAL;
460
461         packet = kzalloc(sizeof *packet + IB_MGMT_RMPP_HDR, GFP_KERNEL);
462         if (!packet)
463                 return -ENOMEM;
464
465         if (copy_from_user(&packet->mad, buf, hdr_size(file))) {
466                 ret = -EFAULT;
467                 goto err;
468         }
469
470         if (packet->mad.hdr.id < 0 ||
471             packet->mad.hdr.id >= IB_UMAD_MAX_AGENTS) {
472                 ret = -EINVAL;
473                 goto err;
474         }
475
476         buf += hdr_size(file);
477
478         if (copy_from_user(packet->mad.data, buf, IB_MGMT_RMPP_HDR)) {
479                 ret = -EFAULT;
480                 goto err;
481         }
482
483         down_read(&file->port->mutex);
484
485         agent = __get_agent(file, packet->mad.hdr.id);
486         if (!agent) {
487                 ret = -EINVAL;
488                 goto err_up;
489         }
490
491         memset(&ah_attr, 0, sizeof ah_attr);
492         ah_attr.dlid          = be16_to_cpu(packet->mad.hdr.lid);
493         ah_attr.sl            = packet->mad.hdr.sl;
494         ah_attr.src_path_bits = packet->mad.hdr.path_bits;
495         ah_attr.port_num      = file->port->port_num;
496         if (packet->mad.hdr.grh_present) {
497                 ah_attr.ah_flags = IB_AH_GRH;
498                 memcpy(ah_attr.grh.dgid.raw, packet->mad.hdr.gid, 16);
499                 ah_attr.grh.sgid_index     = packet->mad.hdr.gid_index;
500                 ah_attr.grh.flow_label     = be32_to_cpu(packet->mad.hdr.flow_label);
501                 ah_attr.grh.hop_limit      = packet->mad.hdr.hop_limit;
502                 ah_attr.grh.traffic_class  = packet->mad.hdr.traffic_class;
503         }
504
505         ah = ib_create_ah(agent->qp->pd, &ah_attr);
506         if (IS_ERR(ah)) {
507                 ret = PTR_ERR(ah);
508                 goto err_up;
509         }
510
511         rmpp_mad = (struct ib_rmpp_mad *) packet->mad.data;
512         hdr_len = ib_get_mad_data_offset(rmpp_mad->mad_hdr.mgmt_class);
513         if (!ib_is_mad_class_rmpp(rmpp_mad->mad_hdr.mgmt_class)) {
514                 copy_offset = IB_MGMT_MAD_HDR;
515                 rmpp_active = 0;
516         } else {
517                 copy_offset = IB_MGMT_RMPP_HDR;
518                 rmpp_active = ib_get_rmpp_flags(&rmpp_mad->rmpp_hdr) &
519                               IB_MGMT_RMPP_FLAG_ACTIVE;
520         }
521
522         data_len = count - hdr_size(file) - hdr_len;
523         packet->msg = ib_create_send_mad(agent,
524                                          be32_to_cpu(packet->mad.hdr.qpn),
525                                          packet->mad.hdr.pkey_index, rmpp_active,
526                                          hdr_len, data_len, GFP_KERNEL);
527         if (IS_ERR(packet->msg)) {
528                 ret = PTR_ERR(packet->msg);
529                 goto err_ah;
530         }
531
532         packet->msg->ah         = ah;
533         packet->msg->timeout_ms = packet->mad.hdr.timeout_ms;
534         packet->msg->retries    = packet->mad.hdr.retries;
535         packet->msg->context[0] = packet;
536
537         /* Copy MAD header.  Any RMPP header is already in place. */
538         memcpy(packet->msg->mad, packet->mad.data, IB_MGMT_MAD_HDR);
539
540         if (!rmpp_active) {
541                 if (copy_from_user(packet->msg->mad + copy_offset,
542                                    buf + copy_offset,
543                                    hdr_len + data_len - copy_offset)) {
544                         ret = -EFAULT;
545                         goto err_msg;
546                 }
547         } else {
548                 ret = copy_rmpp_mad(packet->msg, buf);
549                 if (ret)
550                         goto err_msg;
551         }
552
553         /*
554          * Set the high-order part of the transaction ID to make MADs from
555          * different agents unique, and allow routing responses back to the
556          * original requestor.
557          */
558         if (!ib_response_mad(packet->msg->mad)) {
559                 tid = &((struct ib_mad_hdr *) packet->msg->mad)->tid;
560                 *tid = cpu_to_be64(((u64) agent->hi_tid) << 32 |
561                                    (be64_to_cpup(tid) & 0xffffffff));
562                 rmpp_mad->mad_hdr.tid = *tid;
563         }
564
565         spin_lock_irq(&file->send_lock);
566         ret = is_duplicate(file, packet);
567         if (!ret)
568                 list_add_tail(&packet->list, &file->send_list);
569         spin_unlock_irq(&file->send_lock);
570         if (ret) {
571                 ret = -EINVAL;
572                 goto err_msg;
573         }
574
575         ret = ib_post_send_mad(packet->msg, NULL);
576         if (ret)
577                 goto err_send;
578
579         up_read(&file->port->mutex);
580         return count;
581
582 err_send:
583         dequeue_send(file, packet);
584 err_msg:
585         ib_free_send_mad(packet->msg);
586 err_ah:
587         ib_destroy_ah(ah);
588 err_up:
589         up_read(&file->port->mutex);
590 err:
591         kfree(packet);
592         return ret;
593 }
594
595 static unsigned int ib_umad_poll(struct file *filp, struct poll_table_struct *wait)
596 {
597         struct ib_umad_file *file = filp->private_data;
598
599         /* we will always be able to post a MAD send */
600         unsigned int mask = POLLOUT | POLLWRNORM;
601
602         poll_wait(filp, &file->recv_wait, wait);
603
604         if (!list_empty(&file->recv_list))
605                 mask |= POLLIN | POLLRDNORM;
606
607         return mask;
608 }
609
610 static int ib_umad_reg_agent(struct ib_umad_file *file, unsigned long arg)
611 {
612         struct ib_user_mad_reg_req ureq;
613         struct ib_mad_reg_req req;
614         struct ib_mad_agent *agent;
615         int agent_id;
616         int ret;
617
618         down_write(&file->port->mutex);
619
620         if (!file->port->ib_dev) {
621                 ret = -EPIPE;
622                 goto out;
623         }
624
625         if (copy_from_user(&ureq, (void __user *) arg, sizeof ureq)) {
626                 ret = -EFAULT;
627                 goto out;
628         }
629
630         if (ureq.qpn != 0 && ureq.qpn != 1) {
631                 ret = -EINVAL;
632                 goto out;
633         }
634
635         for (agent_id = 0; agent_id < IB_UMAD_MAX_AGENTS; ++agent_id)
636                 if (!__get_agent(file, agent_id))
637                         goto found;
638
639         ret = -ENOMEM;
640         goto out;
641
642 found:
643         if (ureq.mgmt_class) {
644                 req.mgmt_class         = ureq.mgmt_class;
645                 req.mgmt_class_version = ureq.mgmt_class_version;
646                 memcpy(req.method_mask, ureq.method_mask, sizeof req.method_mask);
647                 memcpy(req.oui,         ureq.oui,         sizeof req.oui);
648         }
649
650         agent = ib_register_mad_agent(file->port->ib_dev, file->port->port_num,
651                                       ureq.qpn ? IB_QPT_GSI : IB_QPT_SMI,
652                                       ureq.mgmt_class ? &req : NULL,
653                                       ureq.rmpp_version,
654                                       send_handler, recv_handler, file);
655         if (IS_ERR(agent)) {
656                 ret = PTR_ERR(agent);
657                 goto out;
658         }
659
660         if (put_user(agent_id,
661                      (u32 __user *) (arg + offsetof(struct ib_user_mad_reg_req, id)))) {
662                 ret = -EFAULT;
663                 ib_unregister_mad_agent(agent);
664                 goto out;
665         }
666
667         if (!file->already_used) {
668                 file->already_used = 1;
669                 if (!file->use_pkey_index) {
670                         printk(KERN_WARNING "user_mad: process %s did not enable "
671                                "P_Key index support.\n", current->comm);
672                         printk(KERN_WARNING "user_mad:   Documentation/infiniband/user_mad.txt "
673                                "has info on the new ABI.\n");
674                 }
675         }
676
677         file->agent[agent_id] = agent;
678         ret = 0;
679
680 out:
681         up_write(&file->port->mutex);
682         return ret;
683 }
684
685 static int ib_umad_unreg_agent(struct ib_umad_file *file, unsigned long arg)
686 {
687         struct ib_mad_agent *agent = NULL;
688         u32 id;
689         int ret = 0;
690
691         if (get_user(id, (u32 __user *) arg))
692                 return -EFAULT;
693
694         down_write(&file->port->mutex);
695
696         if (id < 0 || id >= IB_UMAD_MAX_AGENTS || !__get_agent(file, id)) {
697                 ret = -EINVAL;
698                 goto out;
699         }
700
701         agent = file->agent[id];
702         file->agent[id] = NULL;
703
704 out:
705         up_write(&file->port->mutex);
706
707         if (agent)
708                 ib_unregister_mad_agent(agent);
709
710         return ret;
711 }
712
713 static long ib_umad_enable_pkey(struct ib_umad_file *file)
714 {
715         int ret = 0;
716
717         down_write(&file->port->mutex);
718         if (file->already_used)
719                 ret = -EINVAL;
720         else
721                 file->use_pkey_index = 1;
722         up_write(&file->port->mutex);
723
724         return ret;
725 }
726
727 static long ib_umad_ioctl(struct file *filp, unsigned int cmd,
728                           unsigned long arg)
729 {
730         switch (cmd) {
731         case IB_USER_MAD_REGISTER_AGENT:
732                 return ib_umad_reg_agent(filp->private_data, arg);
733         case IB_USER_MAD_UNREGISTER_AGENT:
734                 return ib_umad_unreg_agent(filp->private_data, arg);
735         case IB_USER_MAD_ENABLE_PKEY:
736                 return ib_umad_enable_pkey(filp->private_data);
737         default:
738                 return -ENOIOCTLCMD;
739         }
740 }
741
742 static int ib_umad_open(struct inode *inode, struct file *filp)
743 {
744         struct ib_umad_port *port;
745         struct ib_umad_file *file;
746         int ret = 0;
747
748         spin_lock(&port_lock);
749         port = umad_port[iminor(inode) - IB_UMAD_MINOR_BASE];
750         if (port)
751                 kref_get(&port->umad_dev->ref);
752         spin_unlock(&port_lock);
753
754         if (!port)
755                 return -ENXIO;
756
757         down_write(&port->mutex);
758
759         if (!port->ib_dev) {
760                 ret = -ENXIO;
761                 goto out;
762         }
763
764         file = kzalloc(sizeof *file, GFP_KERNEL);
765         if (!file) {
766                 kref_put(&port->umad_dev->ref, ib_umad_release_dev);
767                 ret = -ENOMEM;
768                 goto out;
769         }
770
771         spin_lock_init(&file->recv_lock);
772         spin_lock_init(&file->send_lock);
773         INIT_LIST_HEAD(&file->recv_list);
774         INIT_LIST_HEAD(&file->send_list);
775         init_waitqueue_head(&file->recv_wait);
776
777         file->port = port;
778         filp->private_data = file;
779
780         list_add_tail(&file->port_list, &port->file_list);
781
782 out:
783         up_write(&port->mutex);
784         return ret;
785 }
786
787 static int ib_umad_close(struct inode *inode, struct file *filp)
788 {
789         struct ib_umad_file *file = filp->private_data;
790         struct ib_umad_device *dev = file->port->umad_dev;
791         struct ib_umad_packet *packet, *tmp;
792         int already_dead;
793         int i;
794
795         down_write(&file->port->mutex);
796
797         already_dead = file->agents_dead;
798         file->agents_dead = 1;
799
800         list_for_each_entry_safe(packet, tmp, &file->recv_list, list) {
801                 if (packet->recv_wc)
802                         ib_free_recv_mad(packet->recv_wc);
803                 kfree(packet);
804         }
805
806         list_del(&file->port_list);
807
808         downgrade_write(&file->port->mutex);
809
810         if (!already_dead)
811                 for (i = 0; i < IB_UMAD_MAX_AGENTS; ++i)
812                         if (file->agent[i])
813                                 ib_unregister_mad_agent(file->agent[i]);
814
815         up_read(&file->port->mutex);
816
817         kfree(file);
818         kref_put(&dev->ref, ib_umad_release_dev);
819
820         return 0;
821 }
822
823 static const struct file_operations umad_fops = {
824         .owner          = THIS_MODULE,
825         .read           = ib_umad_read,
826         .write          = ib_umad_write,
827         .poll           = ib_umad_poll,
828         .unlocked_ioctl = ib_umad_ioctl,
829         .compat_ioctl   = ib_umad_ioctl,
830         .open           = ib_umad_open,
831         .release        = ib_umad_close
832 };
833
834 static int ib_umad_sm_open(struct inode *inode, struct file *filp)
835 {
836         struct ib_umad_port *port;
837         struct ib_port_modify props = {
838                 .set_port_cap_mask = IB_PORT_SM
839         };
840         int ret;
841
842         spin_lock(&port_lock);
843         port = umad_port[iminor(inode) - IB_UMAD_MINOR_BASE - IB_UMAD_MAX_PORTS];
844         if (port)
845                 kref_get(&port->umad_dev->ref);
846         spin_unlock(&port_lock);
847
848         if (!port)
849                 return -ENXIO;
850
851         if (filp->f_flags & O_NONBLOCK) {
852                 if (down_trylock(&port->sm_sem)) {
853                         ret = -EAGAIN;
854                         goto fail;
855                 }
856         } else {
857                 if (down_interruptible(&port->sm_sem)) {
858                         ret = -ERESTARTSYS;
859                         goto fail;
860                 }
861         }
862
863         ret = ib_modify_port(port->ib_dev, port->port_num, 0, &props);
864         if (ret) {
865                 up(&port->sm_sem);
866                 goto fail;
867         }
868
869         filp->private_data = port;
870
871         return 0;
872
873 fail:
874         kref_put(&port->umad_dev->ref, ib_umad_release_dev);
875         return ret;
876 }
877
878 static int ib_umad_sm_close(struct inode *inode, struct file *filp)
879 {
880         struct ib_umad_port *port = filp->private_data;
881         struct ib_port_modify props = {
882                 .clr_port_cap_mask = IB_PORT_SM
883         };
884         int ret = 0;
885
886         down_write(&port->mutex);
887         if (port->ib_dev)
888                 ret = ib_modify_port(port->ib_dev, port->port_num, 0, &props);
889         up_write(&port->mutex);
890
891         up(&port->sm_sem);
892
893         kref_put(&port->umad_dev->ref, ib_umad_release_dev);
894
895         return ret;
896 }
897
898 static const struct file_operations umad_sm_fops = {
899         .owner   = THIS_MODULE,
900         .open    = ib_umad_sm_open,
901         .release = ib_umad_sm_close
902 };
903
904 static struct ib_client umad_client = {
905         .name   = "umad",
906         .add    = ib_umad_add_one,
907         .remove = ib_umad_remove_one
908 };
909
910 static ssize_t show_ibdev(struct class_device *class_dev, char *buf)
911 {
912         struct ib_umad_port *port = class_get_devdata(class_dev);
913
914         if (!port)
915                 return -ENODEV;
916
917         return sprintf(buf, "%s\n", port->ib_dev->name);
918 }
919 static CLASS_DEVICE_ATTR(ibdev, S_IRUGO, show_ibdev, NULL);
920
921 static ssize_t show_port(struct class_device *class_dev, char *buf)
922 {
923         struct ib_umad_port *port = class_get_devdata(class_dev);
924
925         if (!port)
926                 return -ENODEV;
927
928         return sprintf(buf, "%d\n", port->port_num);
929 }
930 static CLASS_DEVICE_ATTR(port, S_IRUGO, show_port, NULL);
931
932 static ssize_t show_abi_version(struct class *class, char *buf)
933 {
934         return sprintf(buf, "%d\n", IB_USER_MAD_ABI_VERSION);
935 }
936 static CLASS_ATTR(abi_version, S_IRUGO, show_abi_version, NULL);
937
938 static int ib_umad_init_port(struct ib_device *device, int port_num,
939                              struct ib_umad_port *port)
940 {
941         spin_lock(&port_lock);
942         port->dev_num = find_first_zero_bit(dev_map, IB_UMAD_MAX_PORTS);
943         if (port->dev_num >= IB_UMAD_MAX_PORTS) {
944                 spin_unlock(&port_lock);
945                 return -1;
946         }
947         set_bit(port->dev_num, dev_map);
948         spin_unlock(&port_lock);
949
950         port->ib_dev   = device;
951         port->port_num = port_num;
952         init_MUTEX(&port->sm_sem);
953         init_rwsem(&port->mutex);
954         INIT_LIST_HEAD(&port->file_list);
955
956         port->dev = cdev_alloc();
957         if (!port->dev)
958                 return -1;
959         port->dev->owner = THIS_MODULE;
960         port->dev->ops   = &umad_fops;
961         kobject_set_name(&port->dev->kobj, "umad%d", port->dev_num);
962         if (cdev_add(port->dev, base_dev + port->dev_num, 1))
963                 goto err_cdev;
964
965         port->class_dev = class_device_create(umad_class, NULL, port->dev->dev,
966                                               device->dma_device,
967                                               "umad%d", port->dev_num);
968         if (IS_ERR(port->class_dev))
969                 goto err_cdev;
970
971         if (class_device_create_file(port->class_dev, &class_device_attr_ibdev))
972                 goto err_class;
973         if (class_device_create_file(port->class_dev, &class_device_attr_port))
974                 goto err_class;
975
976         port->sm_dev = cdev_alloc();
977         if (!port->sm_dev)
978                 goto err_class;
979         port->sm_dev->owner = THIS_MODULE;
980         port->sm_dev->ops   = &umad_sm_fops;
981         kobject_set_name(&port->sm_dev->kobj, "issm%d", port->dev_num);
982         if (cdev_add(port->sm_dev, base_dev + port->dev_num + IB_UMAD_MAX_PORTS, 1))
983                 goto err_sm_cdev;
984
985         port->sm_class_dev = class_device_create(umad_class, NULL, port->sm_dev->dev,
986                                                  device->dma_device,
987                                                  "issm%d", port->dev_num);
988         if (IS_ERR(port->sm_class_dev))
989                 goto err_sm_cdev;
990
991         class_set_devdata(port->class_dev,    port);
992         class_set_devdata(port->sm_class_dev, port);
993
994         if (class_device_create_file(port->sm_class_dev, &class_device_attr_ibdev))
995                 goto err_sm_class;
996         if (class_device_create_file(port->sm_class_dev, &class_device_attr_port))
997                 goto err_sm_class;
998
999         spin_lock(&port_lock);
1000         umad_port[port->dev_num] = port;
1001         spin_unlock(&port_lock);
1002
1003         return 0;
1004
1005 err_sm_class:
1006         class_device_destroy(umad_class, port->sm_dev->dev);
1007
1008 err_sm_cdev:
1009         cdev_del(port->sm_dev);
1010
1011 err_class:
1012         class_device_destroy(umad_class, port->dev->dev);
1013
1014 err_cdev:
1015         cdev_del(port->dev);
1016         clear_bit(port->dev_num, dev_map);
1017
1018         return -1;
1019 }
1020
1021 static void ib_umad_kill_port(struct ib_umad_port *port)
1022 {
1023         struct ib_umad_file *file;
1024         int id;
1025
1026         class_set_devdata(port->class_dev,    NULL);
1027         class_set_devdata(port->sm_class_dev, NULL);
1028
1029         class_device_destroy(umad_class, port->dev->dev);
1030         class_device_destroy(umad_class, port->sm_dev->dev);
1031
1032         cdev_del(port->dev);
1033         cdev_del(port->sm_dev);
1034
1035         spin_lock(&port_lock);
1036         umad_port[port->dev_num] = NULL;
1037         spin_unlock(&port_lock);
1038
1039         down_write(&port->mutex);
1040
1041         port->ib_dev = NULL;
1042
1043         /*
1044          * Now go through the list of files attached to this port and
1045          * unregister all of their MAD agents.  We need to hold
1046          * port->mutex while doing this to avoid racing with
1047          * ib_umad_close(), but we can't hold the mutex for writing
1048          * while calling ib_unregister_mad_agent(), since that might
1049          * deadlock by calling back into queue_packet().  So we
1050          * downgrade our lock to a read lock, and then drop and
1051          * reacquire the write lock for the next iteration.
1052          *
1053          * We do list_del_init() on the file's list_head so that the
1054          * list_del in ib_umad_close() is still OK, even after the
1055          * file is removed from the list.
1056          */
1057         while (!list_empty(&port->file_list)) {
1058                 file = list_entry(port->file_list.next, struct ib_umad_file,
1059                                   port_list);
1060
1061                 file->agents_dead = 1;
1062                 list_del_init(&file->port_list);
1063
1064                 downgrade_write(&port->mutex);
1065
1066                 for (id = 0; id < IB_UMAD_MAX_AGENTS; ++id)
1067                         if (file->agent[id])
1068                                 ib_unregister_mad_agent(file->agent[id]);
1069
1070                 up_read(&port->mutex);
1071                 down_write(&port->mutex);
1072         }
1073
1074         up_write(&port->mutex);
1075
1076         clear_bit(port->dev_num, dev_map);
1077 }
1078
1079 static void ib_umad_add_one(struct ib_device *device)
1080 {
1081         struct ib_umad_device *umad_dev;
1082         int s, e, i;
1083
1084         if (rdma_node_get_transport(device->node_type) != RDMA_TRANSPORT_IB)
1085                 return;
1086
1087         if (device->node_type == RDMA_NODE_IB_SWITCH)
1088                 s = e = 0;
1089         else {
1090                 s = 1;
1091                 e = device->phys_port_cnt;
1092         }
1093
1094         umad_dev = kzalloc(sizeof *umad_dev +
1095                            (e - s + 1) * sizeof (struct ib_umad_port),
1096                            GFP_KERNEL);
1097         if (!umad_dev)
1098                 return;
1099
1100         kref_init(&umad_dev->ref);
1101
1102         umad_dev->start_port = s;
1103         umad_dev->end_port   = e;
1104
1105         for (i = s; i <= e; ++i) {
1106                 umad_dev->port[i - s].umad_dev = umad_dev;
1107
1108                 if (ib_umad_init_port(device, i, &umad_dev->port[i - s]))
1109                         goto err;
1110         }
1111
1112         ib_set_client_data(device, &umad_client, umad_dev);
1113
1114         return;
1115
1116 err:
1117         while (--i >= s)
1118                 ib_umad_kill_port(&umad_dev->port[i - s]);
1119
1120         kref_put(&umad_dev->ref, ib_umad_release_dev);
1121 }
1122
1123 static void ib_umad_remove_one(struct ib_device *device)
1124 {
1125         struct ib_umad_device *umad_dev = ib_get_client_data(device, &umad_client);
1126         int i;
1127
1128         if (!umad_dev)
1129                 return;
1130
1131         for (i = 0; i <= umad_dev->end_port - umad_dev->start_port; ++i)
1132                 ib_umad_kill_port(&umad_dev->port[i]);
1133
1134         kref_put(&umad_dev->ref, ib_umad_release_dev);
1135 }
1136
1137 static int __init ib_umad_init(void)
1138 {
1139         int ret;
1140
1141         ret = register_chrdev_region(base_dev, IB_UMAD_MAX_PORTS * 2,
1142                                      "infiniband_mad");
1143         if (ret) {
1144                 printk(KERN_ERR "user_mad: couldn't register device number\n");
1145                 goto out;
1146         }
1147
1148         umad_class = class_create(THIS_MODULE, "infiniband_mad");
1149         if (IS_ERR(umad_class)) {
1150                 ret = PTR_ERR(umad_class);
1151                 printk(KERN_ERR "user_mad: couldn't create class infiniband_mad\n");
1152                 goto out_chrdev;
1153         }
1154
1155         ret = class_create_file(umad_class, &class_attr_abi_version);
1156         if (ret) {
1157                 printk(KERN_ERR "user_mad: couldn't create abi_version attribute\n");
1158                 goto out_class;
1159         }
1160
1161         ret = ib_register_client(&umad_client);
1162         if (ret) {
1163                 printk(KERN_ERR "user_mad: couldn't register ib_umad client\n");
1164                 goto out_class;
1165         }
1166
1167         return 0;
1168
1169 out_class:
1170         class_destroy(umad_class);
1171
1172 out_chrdev:
1173         unregister_chrdev_region(base_dev, IB_UMAD_MAX_PORTS * 2);
1174
1175 out:
1176         return ret;
1177 }
1178
1179 static void __exit ib_umad_cleanup(void)
1180 {
1181         ib_unregister_client(&umad_client);
1182         class_destroy(umad_class);
1183         unregister_chrdev_region(base_dev, IB_UMAD_MAX_PORTS * 2);
1184 }
1185
1186 module_init(ib_umad_init);
1187 module_exit(ib_umad_cleanup);