xref: /linux/drivers/infiniband/core/device.c (revision b76960c0f6b25d447a1493c4388defb9e8e76c63)
1 /*
2  * Copyright (c) 2004 Topspin Communications.  All rights reserved.
3  * Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
4  *
5  * This software is available to you under a choice of one of two
6  * licenses.  You may choose to be licensed under the terms of the GNU
7  * General Public License (GPL) Version 2, available from the file
8  * COPYING in the main directory of this source tree, or the
9  * OpenIB.org BSD license below:
10  *
11  *     Redistribution and use in source and binary forms, with or
12  *     without modification, are permitted provided that the following
13  *     conditions are met:
14  *
15  *      - Redistributions of source code must retain the above
16  *        copyright notice, this list of conditions and the following
17  *        disclaimer.
18  *
19  *      - Redistributions in binary form must reproduce the above
20  *        copyright notice, this list of conditions and the following
21  *        disclaimer in the documentation and/or other materials
22  *        provided with the distribution.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31  * SOFTWARE.
32  */
33 
34 #include <linux/module.h>
35 #include <linux/string.h>
36 #include <linux/errno.h>
37 #include <linux/kernel.h>
38 #include <linux/slab.h>
39 #include <linux/init.h>
40 #include <linux/mutex.h>
41 #include <linux/netdevice.h>
42 #include <linux/security.h>
43 #include <linux/notifier.h>
44 #include <rdma/rdma_netlink.h>
45 #include <rdma/ib_addr.h>
46 #include <rdma/ib_cache.h>
47 
48 #include "core_priv.h"
49 
50 MODULE_AUTHOR("Roland Dreier");
51 MODULE_DESCRIPTION("core kernel InfiniBand API");
52 MODULE_LICENSE("Dual BSD/GPL");
53 
54 struct ib_client_data {
55 	struct list_head  list;
56 	struct ib_client *client;
57 	void *            data;
58 	/* The device or client is going down. Do not call client or device
59 	 * callbacks other than remove(). */
60 	bool		  going_down;
61 };
62 
63 struct workqueue_struct *ib_comp_wq;
64 struct workqueue_struct *ib_wq;
65 EXPORT_SYMBOL_GPL(ib_wq);
66 
67 /* The device_list and client_list contain devices and clients after their
68  * registration has completed, and the devices and clients are removed
69  * during unregistration. */
70 static LIST_HEAD(device_list);
71 static LIST_HEAD(client_list);
72 
73 /*
74  * device_mutex and lists_rwsem protect access to both device_list and
75  * client_list.  device_mutex protects writer access by device and client
76  * registration / de-registration.  lists_rwsem protects reader access to
77  * these lists.  Iterators of these lists must lock it for read, while updates
78  * to the lists must be done with a write lock. A special case is when the
79  * device_mutex is locked. In this case locking the lists for read access is
80  * not necessary as the device_mutex implies it.
81  *
82  * lists_rwsem also protects access to the client data list.
83  */
84 static DEFINE_MUTEX(device_mutex);
85 static DECLARE_RWSEM(lists_rwsem);
86 
87 static int ib_security_change(struct notifier_block *nb, unsigned long event,
88 			      void *lsm_data);
89 static void ib_policy_change_task(struct work_struct *work);
90 static DECLARE_WORK(ib_policy_change_work, ib_policy_change_task);
91 
92 static struct notifier_block ibdev_lsm_nb = {
93 	.notifier_call = ib_security_change,
94 };
95 
96 static int ib_device_check_mandatory(struct ib_device *device)
97 {
98 #define IB_MANDATORY_FUNC(x) { offsetof(struct ib_device, x), #x }
99 	static const struct {
100 		size_t offset;
101 		char  *name;
102 	} mandatory_table[] = {
103 		IB_MANDATORY_FUNC(query_device),
104 		IB_MANDATORY_FUNC(query_port),
105 		IB_MANDATORY_FUNC(query_pkey),
106 		IB_MANDATORY_FUNC(query_gid),
107 		IB_MANDATORY_FUNC(alloc_pd),
108 		IB_MANDATORY_FUNC(dealloc_pd),
109 		IB_MANDATORY_FUNC(create_ah),
110 		IB_MANDATORY_FUNC(destroy_ah),
111 		IB_MANDATORY_FUNC(create_qp),
112 		IB_MANDATORY_FUNC(modify_qp),
113 		IB_MANDATORY_FUNC(destroy_qp),
114 		IB_MANDATORY_FUNC(post_send),
115 		IB_MANDATORY_FUNC(post_recv),
116 		IB_MANDATORY_FUNC(create_cq),
117 		IB_MANDATORY_FUNC(destroy_cq),
118 		IB_MANDATORY_FUNC(poll_cq),
119 		IB_MANDATORY_FUNC(req_notify_cq),
120 		IB_MANDATORY_FUNC(get_dma_mr),
121 		IB_MANDATORY_FUNC(dereg_mr),
122 		IB_MANDATORY_FUNC(get_port_immutable)
123 	};
124 	int i;
125 
126 	for (i = 0; i < ARRAY_SIZE(mandatory_table); ++i) {
127 		if (!*(void **) ((void *) device + mandatory_table[i].offset)) {
128 			pr_warn("Device %s is missing mandatory function %s\n",
129 				device->name, mandatory_table[i].name);
130 			return -EINVAL;
131 		}
132 	}
133 
134 	return 0;
135 }
136 
137 static struct ib_device *__ib_device_get_by_index(u32 index)
138 {
139 	struct ib_device *device;
140 
141 	list_for_each_entry(device, &device_list, core_list)
142 		if (device->index == index)
143 			return device;
144 
145 	return NULL;
146 }
147 
148 /*
149  * Caller is responsible to return refrerence count by calling put_device()
150  */
151 struct ib_device *ib_device_get_by_index(u32 index)
152 {
153 	struct ib_device *device;
154 
155 	down_read(&lists_rwsem);
156 	device = __ib_device_get_by_index(index);
157 	if (device)
158 		get_device(&device->dev);
159 
160 	up_read(&lists_rwsem);
161 	return device;
162 }
163 
164 static struct ib_device *__ib_device_get_by_name(const char *name)
165 {
166 	struct ib_device *device;
167 
168 	list_for_each_entry(device, &device_list, core_list)
169 		if (!strncmp(name, device->name, IB_DEVICE_NAME_MAX))
170 			return device;
171 
172 	return NULL;
173 }
174 
175 static int alloc_name(char *name)
176 {
177 	unsigned long *inuse;
178 	char buf[IB_DEVICE_NAME_MAX];
179 	struct ib_device *device;
180 	int i;
181 
182 	inuse = (unsigned long *) get_zeroed_page(GFP_KERNEL);
183 	if (!inuse)
184 		return -ENOMEM;
185 
186 	list_for_each_entry(device, &device_list, core_list) {
187 		if (!sscanf(device->name, name, &i))
188 			continue;
189 		if (i < 0 || i >= PAGE_SIZE * 8)
190 			continue;
191 		snprintf(buf, sizeof buf, name, i);
192 		if (!strncmp(buf, device->name, IB_DEVICE_NAME_MAX))
193 			set_bit(i, inuse);
194 	}
195 
196 	i = find_first_zero_bit(inuse, PAGE_SIZE * 8);
197 	free_page((unsigned long) inuse);
198 	snprintf(buf, sizeof buf, name, i);
199 
200 	if (__ib_device_get_by_name(buf))
201 		return -ENFILE;
202 
203 	strlcpy(name, buf, IB_DEVICE_NAME_MAX);
204 	return 0;
205 }
206 
207 static void ib_device_release(struct device *device)
208 {
209 	struct ib_device *dev = container_of(device, struct ib_device, dev);
210 
211 	WARN_ON(dev->reg_state == IB_DEV_REGISTERED);
212 	if (dev->reg_state == IB_DEV_UNREGISTERED) {
213 		/*
214 		 * In IB_DEV_UNINITIALIZED state, cache or port table
215 		 * is not even created. Free cache and port table only when
216 		 * device reaches UNREGISTERED state.
217 		 */
218 		ib_cache_release_one(dev);
219 		kfree(dev->port_immutable);
220 	}
221 	kfree(dev);
222 }
223 
224 static int ib_device_uevent(struct device *device,
225 			    struct kobj_uevent_env *env)
226 {
227 	struct ib_device *dev = container_of(device, struct ib_device, dev);
228 
229 	if (add_uevent_var(env, "NAME=%s", dev->name))
230 		return -ENOMEM;
231 
232 	/*
233 	 * It would be nice to pass the node GUID with the event...
234 	 */
235 
236 	return 0;
237 }
238 
239 static struct class ib_class = {
240 	.name    = "infiniband",
241 	.dev_release = ib_device_release,
242 	.dev_uevent = ib_device_uevent,
243 };
244 
245 /**
246  * ib_alloc_device - allocate an IB device struct
247  * @size:size of structure to allocate
248  *
249  * Low-level drivers should use ib_alloc_device() to allocate &struct
250  * ib_device.  @size is the size of the structure to be allocated,
251  * including any private data used by the low-level driver.
252  * ib_dealloc_device() must be used to free structures allocated with
253  * ib_alloc_device().
254  */
255 struct ib_device *ib_alloc_device(size_t size)
256 {
257 	struct ib_device *device;
258 
259 	if (WARN_ON(size < sizeof(struct ib_device)))
260 		return NULL;
261 
262 	device = kzalloc(size, GFP_KERNEL);
263 	if (!device)
264 		return NULL;
265 
266 	rdma_restrack_init(&device->res);
267 
268 	device->dev.class = &ib_class;
269 	device_initialize(&device->dev);
270 
271 	dev_set_drvdata(&device->dev, device);
272 
273 	INIT_LIST_HEAD(&device->event_handler_list);
274 	spin_lock_init(&device->event_handler_lock);
275 	spin_lock_init(&device->client_data_lock);
276 	INIT_LIST_HEAD(&device->client_data_list);
277 	INIT_LIST_HEAD(&device->port_list);
278 
279 	return device;
280 }
281 EXPORT_SYMBOL(ib_alloc_device);
282 
283 /**
284  * ib_dealloc_device - free an IB device struct
285  * @device:structure to free
286  *
287  * Free a structure allocated with ib_alloc_device().
288  */
289 void ib_dealloc_device(struct ib_device *device)
290 {
291 	WARN_ON(device->reg_state != IB_DEV_UNREGISTERED &&
292 		device->reg_state != IB_DEV_UNINITIALIZED);
293 	put_device(&device->dev);
294 }
295 EXPORT_SYMBOL(ib_dealloc_device);
296 
297 static int add_client_context(struct ib_device *device, struct ib_client *client)
298 {
299 	struct ib_client_data *context;
300 	unsigned long flags;
301 
302 	context = kmalloc(sizeof *context, GFP_KERNEL);
303 	if (!context)
304 		return -ENOMEM;
305 
306 	context->client = client;
307 	context->data   = NULL;
308 	context->going_down = false;
309 
310 	down_write(&lists_rwsem);
311 	spin_lock_irqsave(&device->client_data_lock, flags);
312 	list_add(&context->list, &device->client_data_list);
313 	spin_unlock_irqrestore(&device->client_data_lock, flags);
314 	up_write(&lists_rwsem);
315 
316 	return 0;
317 }
318 
319 static int verify_immutable(const struct ib_device *dev, u8 port)
320 {
321 	return WARN_ON(!rdma_cap_ib_mad(dev, port) &&
322 			    rdma_max_mad_size(dev, port) != 0);
323 }
324 
325 static int read_port_immutable(struct ib_device *device)
326 {
327 	int ret;
328 	u8 start_port = rdma_start_port(device);
329 	u8 end_port = rdma_end_port(device);
330 	u8 port;
331 
332 	/**
333 	 * device->port_immutable is indexed directly by the port number to make
334 	 * access to this data as efficient as possible.
335 	 *
336 	 * Therefore port_immutable is declared as a 1 based array with
337 	 * potential empty slots at the beginning.
338 	 */
339 	device->port_immutable = kzalloc(sizeof(*device->port_immutable)
340 					 * (end_port + 1),
341 					 GFP_KERNEL);
342 	if (!device->port_immutable)
343 		return -ENOMEM;
344 
345 	for (port = start_port; port <= end_port; ++port) {
346 		ret = device->get_port_immutable(device, port,
347 						 &device->port_immutable[port]);
348 		if (ret)
349 			return ret;
350 
351 		if (verify_immutable(device, port))
352 			return -EINVAL;
353 	}
354 	return 0;
355 }
356 
357 void ib_get_device_fw_str(struct ib_device *dev, char *str)
358 {
359 	if (dev->get_dev_fw_str)
360 		dev->get_dev_fw_str(dev, str);
361 	else
362 		str[0] = '\0';
363 }
364 EXPORT_SYMBOL(ib_get_device_fw_str);
365 
366 static int setup_port_pkey_list(struct ib_device *device)
367 {
368 	int i;
369 
370 	/**
371 	 * device->port_pkey_list is indexed directly by the port number,
372 	 * Therefore it is declared as a 1 based array with potential empty
373 	 * slots at the beginning.
374 	 */
375 	device->port_pkey_list = kcalloc(rdma_end_port(device) + 1,
376 					 sizeof(*device->port_pkey_list),
377 					 GFP_KERNEL);
378 
379 	if (!device->port_pkey_list)
380 		return -ENOMEM;
381 
382 	for (i = 0; i < (rdma_end_port(device) + 1); i++) {
383 		spin_lock_init(&device->port_pkey_list[i].list_lock);
384 		INIT_LIST_HEAD(&device->port_pkey_list[i].pkey_list);
385 	}
386 
387 	return 0;
388 }
389 
390 static void ib_policy_change_task(struct work_struct *work)
391 {
392 	struct ib_device *dev;
393 
394 	down_read(&lists_rwsem);
395 	list_for_each_entry(dev, &device_list, core_list) {
396 		int i;
397 
398 		for (i = rdma_start_port(dev); i <= rdma_end_port(dev); i++) {
399 			u64 sp;
400 			int ret = ib_get_cached_subnet_prefix(dev,
401 							      i,
402 							      &sp);
403 
404 			WARN_ONCE(ret,
405 				  "ib_get_cached_subnet_prefix err: %d, this should never happen here\n",
406 				  ret);
407 			if (!ret)
408 				ib_security_cache_change(dev, i, sp);
409 		}
410 	}
411 	up_read(&lists_rwsem);
412 }
413 
414 static int ib_security_change(struct notifier_block *nb, unsigned long event,
415 			      void *lsm_data)
416 {
417 	if (event != LSM_POLICY_CHANGE)
418 		return NOTIFY_DONE;
419 
420 	schedule_work(&ib_policy_change_work);
421 
422 	return NOTIFY_OK;
423 }
424 
425 /**
426  *	__dev_new_index	-	allocate an device index
427  *
428  *	Returns a suitable unique value for a new device interface
429  *	number.  It assumes that there are less than 2^32-1 ib devices
430  *	will be present in the system.
431  */
432 static u32 __dev_new_index(void)
433 {
434 	/*
435 	 * The device index to allow stable naming.
436 	 * Similar to struct net -> ifindex.
437 	 */
438 	static u32 index;
439 
440 	for (;;) {
441 		if (!(++index))
442 			index = 1;
443 
444 		if (!__ib_device_get_by_index(index))
445 			return index;
446 	}
447 }
448 
449 /**
450  * ib_register_device - Register an IB device with IB core
451  * @device:Device to register
452  *
453  * Low-level drivers use ib_register_device() to register their
454  * devices with the IB core.  All registered clients will receive a
455  * callback for each device that is added. @device must be allocated
456  * with ib_alloc_device().
457  */
458 int ib_register_device(struct ib_device *device,
459 		       int (*port_callback)(struct ib_device *,
460 					    u8, struct kobject *))
461 {
462 	int ret;
463 	struct ib_client *client;
464 	struct ib_udata uhw = {.outlen = 0, .inlen = 0};
465 	struct device *parent = device->dev.parent;
466 
467 	WARN_ON_ONCE(device->dma_device);
468 	if (device->dev.dma_ops) {
469 		/*
470 		 * The caller provided custom DMA operations. Copy the
471 		 * DMA-related fields that are used by e.g. dma_alloc_coherent()
472 		 * into device->dev.
473 		 */
474 		device->dma_device = &device->dev;
475 		if (!device->dev.dma_mask) {
476 			if (parent)
477 				device->dev.dma_mask = parent->dma_mask;
478 			else
479 				WARN_ON_ONCE(true);
480 		}
481 		if (!device->dev.coherent_dma_mask) {
482 			if (parent)
483 				device->dev.coherent_dma_mask =
484 					parent->coherent_dma_mask;
485 			else
486 				WARN_ON_ONCE(true);
487 		}
488 	} else {
489 		/*
490 		 * The caller did not provide custom DMA operations. Use the
491 		 * DMA mapping operations of the parent device.
492 		 */
493 		WARN_ON_ONCE(!parent);
494 		device->dma_device = parent;
495 	}
496 
497 	mutex_lock(&device_mutex);
498 
499 	if (strchr(device->name, '%')) {
500 		ret = alloc_name(device->name);
501 		if (ret)
502 			goto out;
503 	}
504 
505 	if (ib_device_check_mandatory(device)) {
506 		ret = -EINVAL;
507 		goto out;
508 	}
509 
510 	ret = read_port_immutable(device);
511 	if (ret) {
512 		pr_warn("Couldn't create per port immutable data %s\n",
513 			device->name);
514 		goto out;
515 	}
516 
517 	ret = setup_port_pkey_list(device);
518 	if (ret) {
519 		pr_warn("Couldn't create per port_pkey_list\n");
520 		goto out;
521 	}
522 
523 	ret = ib_cache_setup_one(device);
524 	if (ret) {
525 		pr_warn("Couldn't set up InfiniBand P_Key/GID cache\n");
526 		goto port_cleanup;
527 	}
528 
529 	ret = ib_device_register_rdmacg(device);
530 	if (ret) {
531 		pr_warn("Couldn't register device with rdma cgroup\n");
532 		goto cache_cleanup;
533 	}
534 
535 	memset(&device->attrs, 0, sizeof(device->attrs));
536 	ret = device->query_device(device, &device->attrs, &uhw);
537 	if (ret) {
538 		pr_warn("Couldn't query the device attributes\n");
539 		goto cg_cleanup;
540 	}
541 
542 	ret = ib_device_register_sysfs(device, port_callback);
543 	if (ret) {
544 		pr_warn("Couldn't register device %s with driver model\n",
545 			device->name);
546 		goto cg_cleanup;
547 	}
548 
549 	device->reg_state = IB_DEV_REGISTERED;
550 
551 	list_for_each_entry(client, &client_list, list)
552 		if (!add_client_context(device, client) && client->add)
553 			client->add(device);
554 
555 	device->index = __dev_new_index();
556 	down_write(&lists_rwsem);
557 	list_add_tail(&device->core_list, &device_list);
558 	up_write(&lists_rwsem);
559 	mutex_unlock(&device_mutex);
560 	return 0;
561 
562 cg_cleanup:
563 	ib_device_unregister_rdmacg(device);
564 cache_cleanup:
565 	ib_cache_cleanup_one(device);
566 	ib_cache_release_one(device);
567 port_cleanup:
568 	kfree(device->port_immutable);
569 out:
570 	mutex_unlock(&device_mutex);
571 	return ret;
572 }
573 EXPORT_SYMBOL(ib_register_device);
574 
575 /**
576  * ib_unregister_device - Unregister an IB device
577  * @device:Device to unregister
578  *
579  * Unregister an IB device.  All clients will receive a remove callback.
580  */
581 void ib_unregister_device(struct ib_device *device)
582 {
583 	struct ib_client_data *context, *tmp;
584 	unsigned long flags;
585 
586 	mutex_lock(&device_mutex);
587 
588 	down_write(&lists_rwsem);
589 	list_del(&device->core_list);
590 	spin_lock_irqsave(&device->client_data_lock, flags);
591 	list_for_each_entry_safe(context, tmp, &device->client_data_list, list)
592 		context->going_down = true;
593 	spin_unlock_irqrestore(&device->client_data_lock, flags);
594 	downgrade_write(&lists_rwsem);
595 
596 	list_for_each_entry_safe(context, tmp, &device->client_data_list,
597 				 list) {
598 		if (context->client->remove)
599 			context->client->remove(device, context->data);
600 	}
601 	up_read(&lists_rwsem);
602 
603 	rdma_restrack_clean(&device->res);
604 
605 	ib_device_unregister_rdmacg(device);
606 	ib_device_unregister_sysfs(device);
607 
608 	mutex_unlock(&device_mutex);
609 
610 	ib_cache_cleanup_one(device);
611 
612 	ib_security_destroy_port_pkey_list(device);
613 	kfree(device->port_pkey_list);
614 
615 	down_write(&lists_rwsem);
616 	spin_lock_irqsave(&device->client_data_lock, flags);
617 	list_for_each_entry_safe(context, tmp, &device->client_data_list, list)
618 		kfree(context);
619 	spin_unlock_irqrestore(&device->client_data_lock, flags);
620 	up_write(&lists_rwsem);
621 
622 	device->reg_state = IB_DEV_UNREGISTERED;
623 }
624 EXPORT_SYMBOL(ib_unregister_device);
625 
626 /**
627  * ib_register_client - Register an IB client
628  * @client:Client to register
629  *
630  * Upper level users of the IB drivers can use ib_register_client() to
631  * register callbacks for IB device addition and removal.  When an IB
632  * device is added, each registered client's add method will be called
633  * (in the order the clients were registered), and when a device is
634  * removed, each client's remove method will be called (in the reverse
635  * order that clients were registered).  In addition, when
636  * ib_register_client() is called, the client will receive an add
637  * callback for all devices already registered.
638  */
639 int ib_register_client(struct ib_client *client)
640 {
641 	struct ib_device *device;
642 
643 	mutex_lock(&device_mutex);
644 
645 	list_for_each_entry(device, &device_list, core_list)
646 		if (!add_client_context(device, client) && client->add)
647 			client->add(device);
648 
649 	down_write(&lists_rwsem);
650 	list_add_tail(&client->list, &client_list);
651 	up_write(&lists_rwsem);
652 
653 	mutex_unlock(&device_mutex);
654 
655 	return 0;
656 }
657 EXPORT_SYMBOL(ib_register_client);
658 
659 /**
660  * ib_unregister_client - Unregister an IB client
661  * @client:Client to unregister
662  *
663  * Upper level users use ib_unregister_client() to remove their client
664  * registration.  When ib_unregister_client() is called, the client
665  * will receive a remove callback for each IB device still registered.
666  */
667 void ib_unregister_client(struct ib_client *client)
668 {
669 	struct ib_client_data *context, *tmp;
670 	struct ib_device *device;
671 	unsigned long flags;
672 
673 	mutex_lock(&device_mutex);
674 
675 	down_write(&lists_rwsem);
676 	list_del(&client->list);
677 	up_write(&lists_rwsem);
678 
679 	list_for_each_entry(device, &device_list, core_list) {
680 		struct ib_client_data *found_context = NULL;
681 
682 		down_write(&lists_rwsem);
683 		spin_lock_irqsave(&device->client_data_lock, flags);
684 		list_for_each_entry_safe(context, tmp, &device->client_data_list, list)
685 			if (context->client == client) {
686 				context->going_down = true;
687 				found_context = context;
688 				break;
689 			}
690 		spin_unlock_irqrestore(&device->client_data_lock, flags);
691 		up_write(&lists_rwsem);
692 
693 		if (client->remove)
694 			client->remove(device, found_context ?
695 					       found_context->data : NULL);
696 
697 		if (!found_context) {
698 			pr_warn("No client context found for %s/%s\n",
699 				device->name, client->name);
700 			continue;
701 		}
702 
703 		down_write(&lists_rwsem);
704 		spin_lock_irqsave(&device->client_data_lock, flags);
705 		list_del(&found_context->list);
706 		kfree(found_context);
707 		spin_unlock_irqrestore(&device->client_data_lock, flags);
708 		up_write(&lists_rwsem);
709 	}
710 
711 	mutex_unlock(&device_mutex);
712 }
713 EXPORT_SYMBOL(ib_unregister_client);
714 
715 /**
716  * ib_get_client_data - Get IB client context
717  * @device:Device to get context for
718  * @client:Client to get context for
719  *
720  * ib_get_client_data() returns client context set with
721  * ib_set_client_data().
722  */
723 void *ib_get_client_data(struct ib_device *device, struct ib_client *client)
724 {
725 	struct ib_client_data *context;
726 	void *ret = NULL;
727 	unsigned long flags;
728 
729 	spin_lock_irqsave(&device->client_data_lock, flags);
730 	list_for_each_entry(context, &device->client_data_list, list)
731 		if (context->client == client) {
732 			ret = context->data;
733 			break;
734 		}
735 	spin_unlock_irqrestore(&device->client_data_lock, flags);
736 
737 	return ret;
738 }
739 EXPORT_SYMBOL(ib_get_client_data);
740 
741 /**
742  * ib_set_client_data - Set IB client context
743  * @device:Device to set context for
744  * @client:Client to set context for
745  * @data:Context to set
746  *
747  * ib_set_client_data() sets client context that can be retrieved with
748  * ib_get_client_data().
749  */
750 void ib_set_client_data(struct ib_device *device, struct ib_client *client,
751 			void *data)
752 {
753 	struct ib_client_data *context;
754 	unsigned long flags;
755 
756 	spin_lock_irqsave(&device->client_data_lock, flags);
757 	list_for_each_entry(context, &device->client_data_list, list)
758 		if (context->client == client) {
759 			context->data = data;
760 			goto out;
761 		}
762 
763 	pr_warn("No client context found for %s/%s\n",
764 		device->name, client->name);
765 
766 out:
767 	spin_unlock_irqrestore(&device->client_data_lock, flags);
768 }
769 EXPORT_SYMBOL(ib_set_client_data);
770 
771 /**
772  * ib_register_event_handler - Register an IB event handler
773  * @event_handler:Handler to register
774  *
775  * ib_register_event_handler() registers an event handler that will be
776  * called back when asynchronous IB events occur (as defined in
777  * chapter 11 of the InfiniBand Architecture Specification).  This
778  * callback may occur in interrupt context.
779  */
780 void ib_register_event_handler(struct ib_event_handler *event_handler)
781 {
782 	unsigned long flags;
783 
784 	spin_lock_irqsave(&event_handler->device->event_handler_lock, flags);
785 	list_add_tail(&event_handler->list,
786 		      &event_handler->device->event_handler_list);
787 	spin_unlock_irqrestore(&event_handler->device->event_handler_lock, flags);
788 }
789 EXPORT_SYMBOL(ib_register_event_handler);
790 
791 /**
792  * ib_unregister_event_handler - Unregister an event handler
793  * @event_handler:Handler to unregister
794  *
795  * Unregister an event handler registered with
796  * ib_register_event_handler().
797  */
798 void ib_unregister_event_handler(struct ib_event_handler *event_handler)
799 {
800 	unsigned long flags;
801 
802 	spin_lock_irqsave(&event_handler->device->event_handler_lock, flags);
803 	list_del(&event_handler->list);
804 	spin_unlock_irqrestore(&event_handler->device->event_handler_lock, flags);
805 }
806 EXPORT_SYMBOL(ib_unregister_event_handler);
807 
808 /**
809  * ib_dispatch_event - Dispatch an asynchronous event
810  * @event:Event to dispatch
811  *
812  * Low-level drivers must call ib_dispatch_event() to dispatch the
813  * event to all registered event handlers when an asynchronous event
814  * occurs.
815  */
816 void ib_dispatch_event(struct ib_event *event)
817 {
818 	unsigned long flags;
819 	struct ib_event_handler *handler;
820 
821 	spin_lock_irqsave(&event->device->event_handler_lock, flags);
822 
823 	list_for_each_entry(handler, &event->device->event_handler_list, list)
824 		handler->handler(handler, event);
825 
826 	spin_unlock_irqrestore(&event->device->event_handler_lock, flags);
827 }
828 EXPORT_SYMBOL(ib_dispatch_event);
829 
830 /**
831  * ib_query_port - Query IB port attributes
832  * @device:Device to query
833  * @port_num:Port number to query
834  * @port_attr:Port attributes
835  *
836  * ib_query_port() returns the attributes of a port through the
837  * @port_attr pointer.
838  */
839 int ib_query_port(struct ib_device *device,
840 		  u8 port_num,
841 		  struct ib_port_attr *port_attr)
842 {
843 	union ib_gid gid;
844 	int err;
845 
846 	if (!rdma_is_port_valid(device, port_num))
847 		return -EINVAL;
848 
849 	memset(port_attr, 0, sizeof(*port_attr));
850 	err = device->query_port(device, port_num, port_attr);
851 	if (err || port_attr->subnet_prefix)
852 		return err;
853 
854 	if (rdma_port_get_link_layer(device, port_num) != IB_LINK_LAYER_INFINIBAND)
855 		return 0;
856 
857 	err = ib_query_gid(device, port_num, 0, &gid, NULL);
858 	if (err)
859 		return err;
860 
861 	port_attr->subnet_prefix = be64_to_cpu(gid.global.subnet_prefix);
862 	return 0;
863 }
864 EXPORT_SYMBOL(ib_query_port);
865 
866 /**
867  * ib_query_gid - Get GID table entry
868  * @device:Device to query
869  * @port_num:Port number to query
870  * @index:GID table index to query
871  * @gid:Returned GID
872  * @attr: Returned GID attributes related to this GID index (only in RoCE).
873  *   NULL means ignore.
874  *
875  * ib_query_gid() fetches the specified GID table entry.
876  */
877 int ib_query_gid(struct ib_device *device,
878 		 u8 port_num, int index, union ib_gid *gid,
879 		 struct ib_gid_attr *attr)
880 {
881 	if (rdma_cap_roce_gid_table(device, port_num))
882 		return ib_get_cached_gid(device, port_num, index, gid, attr);
883 
884 	if (attr)
885 		return -EINVAL;
886 
887 	return device->query_gid(device, port_num, index, gid);
888 }
889 EXPORT_SYMBOL(ib_query_gid);
890 
891 /**
892  * ib_enum_roce_netdev - enumerate all RoCE ports
893  * @ib_dev : IB device we want to query
894  * @filter: Should we call the callback?
895  * @filter_cookie: Cookie passed to filter
896  * @cb: Callback to call for each found RoCE ports
897  * @cookie: Cookie passed back to the callback
898  *
899  * Enumerates all of the physical RoCE ports of ib_dev
900  * which are related to netdevice and calls callback() on each
901  * device for which filter() function returns non zero.
902  */
903 void ib_enum_roce_netdev(struct ib_device *ib_dev,
904 			 roce_netdev_filter filter,
905 			 void *filter_cookie,
906 			 roce_netdev_callback cb,
907 			 void *cookie)
908 {
909 	u8 port;
910 
911 	for (port = rdma_start_port(ib_dev); port <= rdma_end_port(ib_dev);
912 	     port++)
913 		if (rdma_protocol_roce(ib_dev, port)) {
914 			struct net_device *idev = NULL;
915 
916 			if (ib_dev->get_netdev)
917 				idev = ib_dev->get_netdev(ib_dev, port);
918 
919 			if (idev &&
920 			    idev->reg_state >= NETREG_UNREGISTERED) {
921 				dev_put(idev);
922 				idev = NULL;
923 			}
924 
925 			if (filter(ib_dev, port, idev, filter_cookie))
926 				cb(ib_dev, port, idev, cookie);
927 
928 			if (idev)
929 				dev_put(idev);
930 		}
931 }
932 
933 /**
934  * ib_enum_all_roce_netdevs - enumerate all RoCE devices
935  * @filter: Should we call the callback?
936  * @filter_cookie: Cookie passed to filter
937  * @cb: Callback to call for each found RoCE ports
938  * @cookie: Cookie passed back to the callback
939  *
940  * Enumerates all RoCE devices' physical ports which are related
941  * to netdevices and calls callback() on each device for which
942  * filter() function returns non zero.
943  */
944 void ib_enum_all_roce_netdevs(roce_netdev_filter filter,
945 			      void *filter_cookie,
946 			      roce_netdev_callback cb,
947 			      void *cookie)
948 {
949 	struct ib_device *dev;
950 
951 	down_read(&lists_rwsem);
952 	list_for_each_entry(dev, &device_list, core_list)
953 		ib_enum_roce_netdev(dev, filter, filter_cookie, cb, cookie);
954 	up_read(&lists_rwsem);
955 }
956 
957 /**
958  * ib_enum_all_devs - enumerate all ib_devices
959  * @cb: Callback to call for each found ib_device
960  *
961  * Enumerates all ib_devices and calls callback() on each device.
962  */
963 int ib_enum_all_devs(nldev_callback nldev_cb, struct sk_buff *skb,
964 		     struct netlink_callback *cb)
965 {
966 	struct ib_device *dev;
967 	unsigned int idx = 0;
968 	int ret = 0;
969 
970 	down_read(&lists_rwsem);
971 	list_for_each_entry(dev, &device_list, core_list) {
972 		ret = nldev_cb(dev, skb, cb, idx);
973 		if (ret)
974 			break;
975 		idx++;
976 	}
977 
978 	up_read(&lists_rwsem);
979 	return ret;
980 }
981 
982 /**
983  * ib_query_pkey - Get P_Key table entry
984  * @device:Device to query
985  * @port_num:Port number to query
986  * @index:P_Key table index to query
987  * @pkey:Returned P_Key
988  *
989  * ib_query_pkey() fetches the specified P_Key table entry.
990  */
991 int ib_query_pkey(struct ib_device *device,
992 		  u8 port_num, u16 index, u16 *pkey)
993 {
994 	return device->query_pkey(device, port_num, index, pkey);
995 }
996 EXPORT_SYMBOL(ib_query_pkey);
997 
998 /**
999  * ib_modify_device - Change IB device attributes
1000  * @device:Device to modify
1001  * @device_modify_mask:Mask of attributes to change
1002  * @device_modify:New attribute values
1003  *
1004  * ib_modify_device() changes a device's attributes as specified by
1005  * the @device_modify_mask and @device_modify structure.
1006  */
1007 int ib_modify_device(struct ib_device *device,
1008 		     int device_modify_mask,
1009 		     struct ib_device_modify *device_modify)
1010 {
1011 	if (!device->modify_device)
1012 		return -ENOSYS;
1013 
1014 	return device->modify_device(device, device_modify_mask,
1015 				     device_modify);
1016 }
1017 EXPORT_SYMBOL(ib_modify_device);
1018 
1019 /**
1020  * ib_modify_port - Modifies the attributes for the specified port.
1021  * @device: The device to modify.
1022  * @port_num: The number of the port to modify.
1023  * @port_modify_mask: Mask used to specify which attributes of the port
1024  *   to change.
1025  * @port_modify: New attribute values for the port.
1026  *
1027  * ib_modify_port() changes a port's attributes as specified by the
1028  * @port_modify_mask and @port_modify structure.
1029  */
1030 int ib_modify_port(struct ib_device *device,
1031 		   u8 port_num, int port_modify_mask,
1032 		   struct ib_port_modify *port_modify)
1033 {
1034 	int rc;
1035 
1036 	if (!rdma_is_port_valid(device, port_num))
1037 		return -EINVAL;
1038 
1039 	if (device->modify_port)
1040 		rc = device->modify_port(device, port_num, port_modify_mask,
1041 					   port_modify);
1042 	else
1043 		rc = rdma_protocol_roce(device, port_num) ? 0 : -ENOSYS;
1044 	return rc;
1045 }
1046 EXPORT_SYMBOL(ib_modify_port);
1047 
1048 /**
1049  * ib_find_gid - Returns the port number and GID table index where
1050  *   a specified GID value occurs. Its searches only for IB link layer.
1051  * @device: The device to query.
1052  * @gid: The GID value to search for.
1053  * @ndev: The ndev related to the GID to search for.
1054  * @port_num: The port number of the device where the GID value was found.
1055  * @index: The index into the GID table where the GID was found.  This
1056  *   parameter may be NULL.
1057  */
1058 int ib_find_gid(struct ib_device *device, union ib_gid *gid,
1059 		struct net_device *ndev, u8 *port_num, u16 *index)
1060 {
1061 	union ib_gid tmp_gid;
1062 	int ret, port, i;
1063 
1064 	for (port = rdma_start_port(device); port <= rdma_end_port(device); ++port) {
1065 		if (rdma_cap_roce_gid_table(device, port))
1066 			continue;
1067 
1068 		for (i = 0; i < device->port_immutable[port].gid_tbl_len; ++i) {
1069 			ret = ib_query_gid(device, port, i, &tmp_gid, NULL);
1070 			if (ret)
1071 				return ret;
1072 			if (!memcmp(&tmp_gid, gid, sizeof *gid)) {
1073 				*port_num = port;
1074 				if (index)
1075 					*index = i;
1076 				return 0;
1077 			}
1078 		}
1079 	}
1080 
1081 	return -ENOENT;
1082 }
1083 EXPORT_SYMBOL(ib_find_gid);
1084 
1085 /**
1086  * ib_find_pkey - Returns the PKey table index where a specified
1087  *   PKey value occurs.
1088  * @device: The device to query.
1089  * @port_num: The port number of the device to search for the PKey.
1090  * @pkey: The PKey value to search for.
1091  * @index: The index into the PKey table where the PKey was found.
1092  */
1093 int ib_find_pkey(struct ib_device *device,
1094 		 u8 port_num, u16 pkey, u16 *index)
1095 {
1096 	int ret, i;
1097 	u16 tmp_pkey;
1098 	int partial_ix = -1;
1099 
1100 	for (i = 0; i < device->port_immutable[port_num].pkey_tbl_len; ++i) {
1101 		ret = ib_query_pkey(device, port_num, i, &tmp_pkey);
1102 		if (ret)
1103 			return ret;
1104 		if ((pkey & 0x7fff) == (tmp_pkey & 0x7fff)) {
1105 			/* if there is full-member pkey take it.*/
1106 			if (tmp_pkey & 0x8000) {
1107 				*index = i;
1108 				return 0;
1109 			}
1110 			if (partial_ix < 0)
1111 				partial_ix = i;
1112 		}
1113 	}
1114 
1115 	/*no full-member, if exists take the limited*/
1116 	if (partial_ix >= 0) {
1117 		*index = partial_ix;
1118 		return 0;
1119 	}
1120 	return -ENOENT;
1121 }
1122 EXPORT_SYMBOL(ib_find_pkey);
1123 
1124 /**
1125  * ib_get_net_dev_by_params() - Return the appropriate net_dev
1126  * for a received CM request
1127  * @dev:	An RDMA device on which the request has been received.
1128  * @port:	Port number on the RDMA device.
1129  * @pkey:	The Pkey the request came on.
1130  * @gid:	A GID that the net_dev uses to communicate.
1131  * @addr:	Contains the IP address that the request specified as its
1132  *		destination.
1133  */
1134 struct net_device *ib_get_net_dev_by_params(struct ib_device *dev,
1135 					    u8 port,
1136 					    u16 pkey,
1137 					    const union ib_gid *gid,
1138 					    const struct sockaddr *addr)
1139 {
1140 	struct net_device *net_dev = NULL;
1141 	struct ib_client_data *context;
1142 
1143 	if (!rdma_protocol_ib(dev, port))
1144 		return NULL;
1145 
1146 	down_read(&lists_rwsem);
1147 
1148 	list_for_each_entry(context, &dev->client_data_list, list) {
1149 		struct ib_client *client = context->client;
1150 
1151 		if (context->going_down)
1152 			continue;
1153 
1154 		if (client->get_net_dev_by_params) {
1155 			net_dev = client->get_net_dev_by_params(dev, port, pkey,
1156 								gid, addr,
1157 								context->data);
1158 			if (net_dev)
1159 				break;
1160 		}
1161 	}
1162 
1163 	up_read(&lists_rwsem);
1164 
1165 	return net_dev;
1166 }
1167 EXPORT_SYMBOL(ib_get_net_dev_by_params);
1168 
1169 static const struct rdma_nl_cbs ibnl_ls_cb_table[RDMA_NL_LS_NUM_OPS] = {
1170 	[RDMA_NL_LS_OP_RESOLVE] = {
1171 		.doit = ib_nl_handle_resolve_resp,
1172 		.flags = RDMA_NL_ADMIN_PERM,
1173 	},
1174 	[RDMA_NL_LS_OP_SET_TIMEOUT] = {
1175 		.doit = ib_nl_handle_set_timeout,
1176 		.flags = RDMA_NL_ADMIN_PERM,
1177 	},
1178 	[RDMA_NL_LS_OP_IP_RESOLVE] = {
1179 		.doit = ib_nl_handle_ip_res_resp,
1180 		.flags = RDMA_NL_ADMIN_PERM,
1181 	},
1182 };
1183 
1184 static int __init ib_core_init(void)
1185 {
1186 	int ret;
1187 
1188 	ib_wq = alloc_workqueue("infiniband", 0, 0);
1189 	if (!ib_wq)
1190 		return -ENOMEM;
1191 
1192 	ib_comp_wq = alloc_workqueue("ib-comp-wq",
1193 			WQ_HIGHPRI | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
1194 	if (!ib_comp_wq) {
1195 		ret = -ENOMEM;
1196 		goto err;
1197 	}
1198 
1199 	ret = class_register(&ib_class);
1200 	if (ret) {
1201 		pr_warn("Couldn't create InfiniBand device class\n");
1202 		goto err_comp;
1203 	}
1204 
1205 	ret = rdma_nl_init();
1206 	if (ret) {
1207 		pr_warn("Couldn't init IB netlink interface: err %d\n", ret);
1208 		goto err_sysfs;
1209 	}
1210 
1211 	ret = addr_init();
1212 	if (ret) {
1213 		pr_warn("Could't init IB address resolution\n");
1214 		goto err_ibnl;
1215 	}
1216 
1217 	ret = ib_mad_init();
1218 	if (ret) {
1219 		pr_warn("Couldn't init IB MAD\n");
1220 		goto err_addr;
1221 	}
1222 
1223 	ret = ib_sa_init();
1224 	if (ret) {
1225 		pr_warn("Couldn't init SA\n");
1226 		goto err_mad;
1227 	}
1228 
1229 	ret = register_lsm_notifier(&ibdev_lsm_nb);
1230 	if (ret) {
1231 		pr_warn("Couldn't register LSM notifier. ret %d\n", ret);
1232 		goto err_sa;
1233 	}
1234 
1235 	nldev_init();
1236 	rdma_nl_register(RDMA_NL_LS, ibnl_ls_cb_table);
1237 	ib_cache_setup();
1238 
1239 	return 0;
1240 
1241 err_sa:
1242 	ib_sa_cleanup();
1243 err_mad:
1244 	ib_mad_cleanup();
1245 err_addr:
1246 	addr_cleanup();
1247 err_ibnl:
1248 	rdma_nl_exit();
1249 err_sysfs:
1250 	class_unregister(&ib_class);
1251 err_comp:
1252 	destroy_workqueue(ib_comp_wq);
1253 err:
1254 	destroy_workqueue(ib_wq);
1255 	return ret;
1256 }
1257 
1258 static void __exit ib_core_cleanup(void)
1259 {
1260 	ib_cache_cleanup();
1261 	nldev_exit();
1262 	rdma_nl_unregister(RDMA_NL_LS);
1263 	unregister_lsm_notifier(&ibdev_lsm_nb);
1264 	ib_sa_cleanup();
1265 	ib_mad_cleanup();
1266 	addr_cleanup();
1267 	rdma_nl_exit();
1268 	class_unregister(&ib_class);
1269 	destroy_workqueue(ib_comp_wq);
1270 	/* Make sure that any pending umem accounting work is done. */
1271 	destroy_workqueue(ib_wq);
1272 }
1273 
1274 MODULE_ALIAS_RDMA_NETLINK(RDMA_NL_LS, 4);
1275 
1276 subsys_initcall(ib_core_init);
1277 module_exit(ib_core_cleanup);
1278