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