Merge branch 'for-next' of git://git.kernel.org/pub/scm/linux/kernel/git/gerg/m68knommu
[linux-2.6-block.git] / drivers / infiniband / core / device.c
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/netdevice.h>
41 #include <linux/security.h>
42 #include <linux/notifier.h>
43 #include <linux/hashtable.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 #include "restrack.h"
50
51 MODULE_AUTHOR("Roland Dreier");
52 MODULE_DESCRIPTION("core kernel InfiniBand API");
53 MODULE_LICENSE("Dual BSD/GPL");
54
55 struct workqueue_struct *ib_comp_wq;
56 struct workqueue_struct *ib_comp_unbound_wq;
57 struct workqueue_struct *ib_wq;
58 EXPORT_SYMBOL_GPL(ib_wq);
59
60 /*
61  * Each of the three rwsem locks (devices, clients, client_data) protects the
62  * xarray of the same name. Specifically it allows the caller to assert that
63  * the MARK will/will not be changing under the lock, and for devices and
64  * clients, that the value in the xarray is still a valid pointer. Change of
65  * the MARK is linked to the object state, so holding the lock and testing the
66  * MARK also asserts that the contained object is in a certain state.
67  *
68  * This is used to build a two stage register/unregister flow where objects
69  * can continue to be in the xarray even though they are still in progress to
70  * register/unregister.
71  *
72  * The xarray itself provides additional locking, and restartable iteration,
73  * which is also relied on.
74  *
75  * Locks should not be nested, with the exception of client_data, which is
76  * allowed to nest under the read side of the other two locks.
77  *
78  * The devices_rwsem also protects the device name list, any change or
79  * assignment of device name must also hold the write side to guarantee unique
80  * names.
81  */
82
83 /*
84  * devices contains devices that have had their names assigned. The
85  * devices may not be registered. Users that care about the registration
86  * status need to call ib_device_try_get() on the device to ensure it is
87  * registered, and keep it registered, for the required duration.
88  *
89  */
90 static DEFINE_XARRAY_FLAGS(devices, XA_FLAGS_ALLOC);
91 static DECLARE_RWSEM(devices_rwsem);
92 #define DEVICE_REGISTERED XA_MARK_1
93
94 static LIST_HEAD(client_list);
95 #define CLIENT_REGISTERED XA_MARK_1
96 static DEFINE_XARRAY_FLAGS(clients, XA_FLAGS_ALLOC);
97 static DECLARE_RWSEM(clients_rwsem);
98
99 /*
100  * If client_data is registered then the corresponding client must also still
101  * be registered.
102  */
103 #define CLIENT_DATA_REGISTERED XA_MARK_1
104 /*
105  * xarray has this behavior where it won't iterate over NULL values stored in
106  * allocated arrays.  So we need our own iterator to see all values stored in
107  * the array. This does the same thing as xa_for_each except that it also
108  * returns NULL valued entries if the array is allocating. Simplified to only
109  * work on simple xarrays.
110  */
111 static void *xan_find_marked(struct xarray *xa, unsigned long *indexp,
112                              xa_mark_t filter)
113 {
114         XA_STATE(xas, xa, *indexp);
115         void *entry;
116
117         rcu_read_lock();
118         do {
119                 entry = xas_find_marked(&xas, ULONG_MAX, filter);
120                 if (xa_is_zero(entry))
121                         break;
122         } while (xas_retry(&xas, entry));
123         rcu_read_unlock();
124
125         if (entry) {
126                 *indexp = xas.xa_index;
127                 if (xa_is_zero(entry))
128                         return NULL;
129                 return entry;
130         }
131         return XA_ERROR(-ENOENT);
132 }
133 #define xan_for_each_marked(xa, index, entry, filter)                          \
134         for (index = 0, entry = xan_find_marked(xa, &(index), filter);         \
135              !xa_is_err(entry);                                                \
136              (index)++, entry = xan_find_marked(xa, &(index), filter))
137
138 /* RCU hash table mapping netdevice pointers to struct ib_port_data */
139 static DEFINE_SPINLOCK(ndev_hash_lock);
140 static DECLARE_HASHTABLE(ndev_hash, 5);
141
142 static void free_netdevs(struct ib_device *ib_dev);
143 static void ib_unregister_work(struct work_struct *work);
144 static void __ib_unregister_device(struct ib_device *device);
145 static int ib_security_change(struct notifier_block *nb, unsigned long event,
146                               void *lsm_data);
147 static void ib_policy_change_task(struct work_struct *work);
148 static DECLARE_WORK(ib_policy_change_work, ib_policy_change_task);
149
150 static struct notifier_block ibdev_lsm_nb = {
151         .notifier_call = ib_security_change,
152 };
153
154 /* Pointer to the RCU head at the start of the ib_port_data array */
155 struct ib_port_data_rcu {
156         struct rcu_head rcu_head;
157         struct ib_port_data pdata[];
158 };
159
160 static int ib_device_check_mandatory(struct ib_device *device)
161 {
162 #define IB_MANDATORY_FUNC(x) { offsetof(struct ib_device_ops, x), #x }
163         static const struct {
164                 size_t offset;
165                 char  *name;
166         } mandatory_table[] = {
167                 IB_MANDATORY_FUNC(query_device),
168                 IB_MANDATORY_FUNC(query_port),
169                 IB_MANDATORY_FUNC(query_pkey),
170                 IB_MANDATORY_FUNC(alloc_pd),
171                 IB_MANDATORY_FUNC(dealloc_pd),
172                 IB_MANDATORY_FUNC(create_qp),
173                 IB_MANDATORY_FUNC(modify_qp),
174                 IB_MANDATORY_FUNC(destroy_qp),
175                 IB_MANDATORY_FUNC(post_send),
176                 IB_MANDATORY_FUNC(post_recv),
177                 IB_MANDATORY_FUNC(create_cq),
178                 IB_MANDATORY_FUNC(destroy_cq),
179                 IB_MANDATORY_FUNC(poll_cq),
180                 IB_MANDATORY_FUNC(req_notify_cq),
181                 IB_MANDATORY_FUNC(get_dma_mr),
182                 IB_MANDATORY_FUNC(dereg_mr),
183                 IB_MANDATORY_FUNC(get_port_immutable)
184         };
185         int i;
186
187         device->kverbs_provider = true;
188         for (i = 0; i < ARRAY_SIZE(mandatory_table); ++i) {
189                 if (!*(void **) ((void *) &device->ops +
190                                  mandatory_table[i].offset)) {
191                         device->kverbs_provider = false;
192                         break;
193                 }
194         }
195
196         return 0;
197 }
198
199 /*
200  * Caller must perform ib_device_put() to return the device reference count
201  * when ib_device_get_by_index() returns valid device pointer.
202  */
203 struct ib_device *ib_device_get_by_index(u32 index)
204 {
205         struct ib_device *device;
206
207         down_read(&devices_rwsem);
208         device = xa_load(&devices, index);
209         if (device) {
210                 if (!ib_device_try_get(device))
211                         device = NULL;
212         }
213         up_read(&devices_rwsem);
214         return device;
215 }
216
217 /**
218  * ib_device_put - Release IB device reference
219  * @device: device whose reference to be released
220  *
221  * ib_device_put() releases reference to the IB device to allow it to be
222  * unregistered and eventually free.
223  */
224 void ib_device_put(struct ib_device *device)
225 {
226         if (refcount_dec_and_test(&device->refcount))
227                 complete(&device->unreg_completion);
228 }
229 EXPORT_SYMBOL(ib_device_put);
230
231 static struct ib_device *__ib_device_get_by_name(const char *name)
232 {
233         struct ib_device *device;
234         unsigned long index;
235
236         xa_for_each (&devices, index, device)
237                 if (!strcmp(name, dev_name(&device->dev)))
238                         return device;
239
240         return NULL;
241 }
242
243 /**
244  * ib_device_get_by_name - Find an IB device by name
245  * @name: The name to look for
246  * @driver_id: The driver ID that must match (RDMA_DRIVER_UNKNOWN matches all)
247  *
248  * Find and hold an ib_device by its name. The caller must call
249  * ib_device_put() on the returned pointer.
250  */
251 struct ib_device *ib_device_get_by_name(const char *name,
252                                         enum rdma_driver_id driver_id)
253 {
254         struct ib_device *device;
255
256         down_read(&devices_rwsem);
257         device = __ib_device_get_by_name(name);
258         if (device && driver_id != RDMA_DRIVER_UNKNOWN &&
259             device->driver_id != driver_id)
260                 device = NULL;
261
262         if (device) {
263                 if (!ib_device_try_get(device))
264                         device = NULL;
265         }
266         up_read(&devices_rwsem);
267         return device;
268 }
269 EXPORT_SYMBOL(ib_device_get_by_name);
270
271 int ib_device_rename(struct ib_device *ibdev, const char *name)
272 {
273         int ret;
274
275         down_write(&devices_rwsem);
276         if (!strcmp(name, dev_name(&ibdev->dev))) {
277                 ret = 0;
278                 goto out;
279         }
280
281         if (__ib_device_get_by_name(name)) {
282                 ret = -EEXIST;
283                 goto out;
284         }
285
286         ret = device_rename(&ibdev->dev, name);
287         if (ret)
288                 goto out;
289         strlcpy(ibdev->name, name, IB_DEVICE_NAME_MAX);
290 out:
291         up_write(&devices_rwsem);
292         return ret;
293 }
294
295 static int alloc_name(struct ib_device *ibdev, const char *name)
296 {
297         struct ib_device *device;
298         unsigned long index;
299         struct ida inuse;
300         int rc;
301         int i;
302
303         lockdep_assert_held_exclusive(&devices_rwsem);
304         ida_init(&inuse);
305         xa_for_each (&devices, index, device) {
306                 char buf[IB_DEVICE_NAME_MAX];
307
308                 if (sscanf(dev_name(&device->dev), name, &i) != 1)
309                         continue;
310                 if (i < 0 || i >= INT_MAX)
311                         continue;
312                 snprintf(buf, sizeof buf, name, i);
313                 if (strcmp(buf, dev_name(&device->dev)) != 0)
314                         continue;
315
316                 rc = ida_alloc_range(&inuse, i, i, GFP_KERNEL);
317                 if (rc < 0)
318                         goto out;
319         }
320
321         rc = ida_alloc(&inuse, GFP_KERNEL);
322         if (rc < 0)
323                 goto out;
324
325         rc = dev_set_name(&ibdev->dev, name, rc);
326 out:
327         ida_destroy(&inuse);
328         return rc;
329 }
330
331 static void ib_device_release(struct device *device)
332 {
333         struct ib_device *dev = container_of(device, struct ib_device, dev);
334
335         free_netdevs(dev);
336         WARN_ON(refcount_read(&dev->refcount));
337         ib_cache_release_one(dev);
338         ib_security_release_port_pkey_list(dev);
339         xa_destroy(&dev->client_data);
340         if (dev->port_data)
341                 kfree_rcu(container_of(dev->port_data, struct ib_port_data_rcu,
342                                        pdata[0]),
343                           rcu_head);
344         kfree_rcu(dev, rcu_head);
345 }
346
347 static int ib_device_uevent(struct device *device,
348                             struct kobj_uevent_env *env)
349 {
350         if (add_uevent_var(env, "NAME=%s", dev_name(device)))
351                 return -ENOMEM;
352
353         /*
354          * It would be nice to pass the node GUID with the event...
355          */
356
357         return 0;
358 }
359
360 static struct class ib_class = {
361         .name    = "infiniband",
362         .dev_release = ib_device_release,
363         .dev_uevent = ib_device_uevent,
364 };
365
366 /**
367  * _ib_alloc_device - allocate an IB device struct
368  * @size:size of structure to allocate
369  *
370  * Low-level drivers should use ib_alloc_device() to allocate &struct
371  * ib_device.  @size is the size of the structure to be allocated,
372  * including any private data used by the low-level driver.
373  * ib_dealloc_device() must be used to free structures allocated with
374  * ib_alloc_device().
375  */
376 struct ib_device *_ib_alloc_device(size_t size)
377 {
378         struct ib_device *device;
379
380         if (WARN_ON(size < sizeof(struct ib_device)))
381                 return NULL;
382
383         device = kzalloc(size, GFP_KERNEL);
384         if (!device)
385                 return NULL;
386
387         if (rdma_restrack_init(device)) {
388                 kfree(device);
389                 return NULL;
390         }
391
392         device->dev.class = &ib_class;
393         device->groups[0] = &ib_dev_attr_group;
394         device->dev.groups = device->groups;
395         device_initialize(&device->dev);
396
397         INIT_LIST_HEAD(&device->event_handler_list);
398         spin_lock_init(&device->event_handler_lock);
399         mutex_init(&device->unregistration_lock);
400         /*
401          * client_data needs to be alloc because we don't want our mark to be
402          * destroyed if the user stores NULL in the client data.
403          */
404         xa_init_flags(&device->client_data, XA_FLAGS_ALLOC);
405         init_rwsem(&device->client_data_rwsem);
406         INIT_LIST_HEAD(&device->port_list);
407         init_completion(&device->unreg_completion);
408         INIT_WORK(&device->unregistration_work, ib_unregister_work);
409
410         return device;
411 }
412 EXPORT_SYMBOL(_ib_alloc_device);
413
414 /**
415  * ib_dealloc_device - free an IB device struct
416  * @device:structure to free
417  *
418  * Free a structure allocated with ib_alloc_device().
419  */
420 void ib_dealloc_device(struct ib_device *device)
421 {
422         if (device->ops.dealloc_driver)
423                 device->ops.dealloc_driver(device);
424
425         /*
426          * ib_unregister_driver() requires all devices to remain in the xarray
427          * while their ops are callable. The last op we call is dealloc_driver
428          * above.  This is needed to create a fence on op callbacks prior to
429          * allowing the driver module to unload.
430          */
431         down_write(&devices_rwsem);
432         if (xa_load(&devices, device->index) == device)
433                 xa_erase(&devices, device->index);
434         up_write(&devices_rwsem);
435
436         /* Expedite releasing netdev references */
437         free_netdevs(device);
438
439         WARN_ON(!xa_empty(&device->client_data));
440         WARN_ON(refcount_read(&device->refcount));
441         rdma_restrack_clean(device);
442         /* Balances with device_initialize */
443         put_device(&device->dev);
444 }
445 EXPORT_SYMBOL(ib_dealloc_device);
446
447 /*
448  * add_client_context() and remove_client_context() must be safe against
449  * parallel calls on the same device - registration/unregistration of both the
450  * device and client can be occurring in parallel.
451  *
452  * The routines need to be a fence, any caller must not return until the add
453  * or remove is fully completed.
454  */
455 static int add_client_context(struct ib_device *device,
456                               struct ib_client *client)
457 {
458         int ret = 0;
459
460         if (!device->kverbs_provider && !client->no_kverbs_req)
461                 return 0;
462
463         down_write(&device->client_data_rwsem);
464         /*
465          * Another caller to add_client_context got here first and has already
466          * completely initialized context.
467          */
468         if (xa_get_mark(&device->client_data, client->client_id,
469                     CLIENT_DATA_REGISTERED))
470                 goto out;
471
472         ret = xa_err(xa_store(&device->client_data, client->client_id, NULL,
473                               GFP_KERNEL));
474         if (ret)
475                 goto out;
476         downgrade_write(&device->client_data_rwsem);
477         if (client->add)
478                 client->add(device);
479
480         /* Readers shall not see a client until add has been completed */
481         xa_set_mark(&device->client_data, client->client_id,
482                     CLIENT_DATA_REGISTERED);
483         up_read(&device->client_data_rwsem);
484         return 0;
485
486 out:
487         up_write(&device->client_data_rwsem);
488         return ret;
489 }
490
491 static void remove_client_context(struct ib_device *device,
492                                   unsigned int client_id)
493 {
494         struct ib_client *client;
495         void *client_data;
496
497         down_write(&device->client_data_rwsem);
498         if (!xa_get_mark(&device->client_data, client_id,
499                          CLIENT_DATA_REGISTERED)) {
500                 up_write(&device->client_data_rwsem);
501                 return;
502         }
503         client_data = xa_load(&device->client_data, client_id);
504         xa_clear_mark(&device->client_data, client_id, CLIENT_DATA_REGISTERED);
505         client = xa_load(&clients, client_id);
506         downgrade_write(&device->client_data_rwsem);
507
508         /*
509          * Notice we cannot be holding any exclusive locks when calling the
510          * remove callback as the remove callback can recurse back into any
511          * public functions in this module and thus try for any locks those
512          * functions take.
513          *
514          * For this reason clients and drivers should not call the
515          * unregistration functions will holdling any locks.
516          *
517          * It tempting to drop the client_data_rwsem too, but this is required
518          * to ensure that unregister_client does not return until all clients
519          * are completely unregistered, which is required to avoid module
520          * unloading races.
521          */
522         if (client->remove)
523                 client->remove(device, client_data);
524
525         xa_erase(&device->client_data, client_id);
526         up_read(&device->client_data_rwsem);
527 }
528
529 static int alloc_port_data(struct ib_device *device)
530 {
531         struct ib_port_data_rcu *pdata_rcu;
532         unsigned int port;
533
534         if (device->port_data)
535                 return 0;
536
537         /* This can only be called once the physical port range is defined */
538         if (WARN_ON(!device->phys_port_cnt))
539                 return -EINVAL;
540
541         /*
542          * device->port_data is indexed directly by the port number to make
543          * access to this data as efficient as possible.
544          *
545          * Therefore port_data is declared as a 1 based array with potential
546          * empty slots at the beginning.
547          */
548         pdata_rcu = kzalloc(struct_size(pdata_rcu, pdata,
549                                         rdma_end_port(device) + 1),
550                             GFP_KERNEL);
551         if (!pdata_rcu)
552                 return -ENOMEM;
553         /*
554          * The rcu_head is put in front of the port data array and the stored
555          * pointer is adjusted since we never need to see that member until
556          * kfree_rcu.
557          */
558         device->port_data = pdata_rcu->pdata;
559
560         rdma_for_each_port (device, port) {
561                 struct ib_port_data *pdata = &device->port_data[port];
562
563                 pdata->ib_dev = device;
564                 spin_lock_init(&pdata->pkey_list_lock);
565                 INIT_LIST_HEAD(&pdata->pkey_list);
566                 spin_lock_init(&pdata->netdev_lock);
567                 INIT_HLIST_NODE(&pdata->ndev_hash_link);
568         }
569         return 0;
570 }
571
572 static int verify_immutable(const struct ib_device *dev, u8 port)
573 {
574         return WARN_ON(!rdma_cap_ib_mad(dev, port) &&
575                             rdma_max_mad_size(dev, port) != 0);
576 }
577
578 static int setup_port_data(struct ib_device *device)
579 {
580         unsigned int port;
581         int ret;
582
583         ret = alloc_port_data(device);
584         if (ret)
585                 return ret;
586
587         rdma_for_each_port (device, port) {
588                 struct ib_port_data *pdata = &device->port_data[port];
589
590                 ret = device->ops.get_port_immutable(device, port,
591                                                      &pdata->immutable);
592                 if (ret)
593                         return ret;
594
595                 if (verify_immutable(device, port))
596                         return -EINVAL;
597         }
598         return 0;
599 }
600
601 void ib_get_device_fw_str(struct ib_device *dev, char *str)
602 {
603         if (dev->ops.get_dev_fw_str)
604                 dev->ops.get_dev_fw_str(dev, str);
605         else
606                 str[0] = '\0';
607 }
608 EXPORT_SYMBOL(ib_get_device_fw_str);
609
610 static void ib_policy_change_task(struct work_struct *work)
611 {
612         struct ib_device *dev;
613         unsigned long index;
614
615         down_read(&devices_rwsem);
616         xa_for_each_marked (&devices, index, dev, DEVICE_REGISTERED) {
617                 unsigned int i;
618
619                 rdma_for_each_port (dev, i) {
620                         u64 sp;
621                         int ret = ib_get_cached_subnet_prefix(dev,
622                                                               i,
623                                                               &sp);
624
625                         WARN_ONCE(ret,
626                                   "ib_get_cached_subnet_prefix err: %d, this should never happen here\n",
627                                   ret);
628                         if (!ret)
629                                 ib_security_cache_change(dev, i, sp);
630                 }
631         }
632         up_read(&devices_rwsem);
633 }
634
635 static int ib_security_change(struct notifier_block *nb, unsigned long event,
636                               void *lsm_data)
637 {
638         if (event != LSM_POLICY_CHANGE)
639                 return NOTIFY_DONE;
640
641         schedule_work(&ib_policy_change_work);
642         ib_mad_agent_security_change();
643
644         return NOTIFY_OK;
645 }
646
647 /*
648  * Assign the unique string device name and the unique device index. This is
649  * undone by ib_dealloc_device.
650  */
651 static int assign_name(struct ib_device *device, const char *name)
652 {
653         static u32 last_id;
654         int ret;
655
656         down_write(&devices_rwsem);
657         /* Assign a unique name to the device */
658         if (strchr(name, '%'))
659                 ret = alloc_name(device, name);
660         else
661                 ret = dev_set_name(&device->dev, name);
662         if (ret)
663                 goto out;
664
665         if (__ib_device_get_by_name(dev_name(&device->dev))) {
666                 ret = -ENFILE;
667                 goto out;
668         }
669         strlcpy(device->name, dev_name(&device->dev), IB_DEVICE_NAME_MAX);
670
671         /* Cyclically allocate a user visible ID for the device */
672         device->index = last_id;
673         ret = xa_alloc(&devices, &device->index, INT_MAX, device, GFP_KERNEL);
674         if (ret == -ENOSPC) {
675                 device->index = 0;
676                 ret = xa_alloc(&devices, &device->index, INT_MAX, device,
677                                GFP_KERNEL);
678         }
679         if (ret)
680                 goto out;
681         last_id = device->index + 1;
682
683         ret = 0;
684
685 out:
686         up_write(&devices_rwsem);
687         return ret;
688 }
689
690 static void setup_dma_device(struct ib_device *device)
691 {
692         struct device *parent = device->dev.parent;
693
694         WARN_ON_ONCE(device->dma_device);
695         if (device->dev.dma_ops) {
696                 /*
697                  * The caller provided custom DMA operations. Copy the
698                  * DMA-related fields that are used by e.g. dma_alloc_coherent()
699                  * into device->dev.
700                  */
701                 device->dma_device = &device->dev;
702                 if (!device->dev.dma_mask) {
703                         if (parent)
704                                 device->dev.dma_mask = parent->dma_mask;
705                         else
706                                 WARN_ON_ONCE(true);
707                 }
708                 if (!device->dev.coherent_dma_mask) {
709                         if (parent)
710                                 device->dev.coherent_dma_mask =
711                                         parent->coherent_dma_mask;
712                         else
713                                 WARN_ON_ONCE(true);
714                 }
715         } else {
716                 /*
717                  * The caller did not provide custom DMA operations. Use the
718                  * DMA mapping operations of the parent device.
719                  */
720                 WARN_ON_ONCE(!parent);
721                 device->dma_device = parent;
722         }
723 }
724
725 /*
726  * setup_device() allocates memory and sets up data that requires calling the
727  * device ops, this is the only reason these actions are not done during
728  * ib_alloc_device. It is undone by ib_dealloc_device().
729  */
730 static int setup_device(struct ib_device *device)
731 {
732         struct ib_udata uhw = {.outlen = 0, .inlen = 0};
733         int ret;
734
735         setup_dma_device(device);
736
737         ret = ib_device_check_mandatory(device);
738         if (ret)
739                 return ret;
740
741         ret = setup_port_data(device);
742         if (ret) {
743                 dev_warn(&device->dev, "Couldn't create per-port data\n");
744                 return ret;
745         }
746
747         memset(&device->attrs, 0, sizeof(device->attrs));
748         ret = device->ops.query_device(device, &device->attrs, &uhw);
749         if (ret) {
750                 dev_warn(&device->dev,
751                          "Couldn't query the device attributes\n");
752                 return ret;
753         }
754
755         return 0;
756 }
757
758 static void disable_device(struct ib_device *device)
759 {
760         struct ib_client *client;
761
762         WARN_ON(!refcount_read(&device->refcount));
763
764         down_write(&devices_rwsem);
765         xa_clear_mark(&devices, device->index, DEVICE_REGISTERED);
766         up_write(&devices_rwsem);
767
768         down_read(&clients_rwsem);
769         list_for_each_entry_reverse(client, &client_list, list)
770                 remove_client_context(device, client->client_id);
771         up_read(&clients_rwsem);
772
773         /* Pairs with refcount_set in enable_device */
774         ib_device_put(device);
775         wait_for_completion(&device->unreg_completion);
776
777         /* Expedite removing unregistered pointers from the hash table */
778         free_netdevs(device);
779 }
780
781 /*
782  * An enabled device is visible to all clients and to all the public facing
783  * APIs that return a device pointer. This always returns with a new get, even
784  * if it fails.
785  */
786 static int enable_device_and_get(struct ib_device *device)
787 {
788         struct ib_client *client;
789         unsigned long index;
790         int ret = 0;
791
792         /*
793          * One ref belongs to the xa and the other belongs to this
794          * thread. This is needed to guard against parallel unregistration.
795          */
796         refcount_set(&device->refcount, 2);
797         down_write(&devices_rwsem);
798         xa_set_mark(&devices, device->index, DEVICE_REGISTERED);
799
800         /*
801          * By using downgrade_write() we ensure that no other thread can clear
802          * DEVICE_REGISTERED while we are completing the client setup.
803          */
804         downgrade_write(&devices_rwsem);
805
806         if (device->ops.enable_driver) {
807                 ret = device->ops.enable_driver(device);
808                 if (ret)
809                         goto out;
810         }
811
812         down_read(&clients_rwsem);
813         xa_for_each_marked (&clients, index, client, CLIENT_REGISTERED) {
814                 ret = add_client_context(device, client);
815                 if (ret)
816                         break;
817         }
818         up_read(&clients_rwsem);
819
820 out:
821         up_read(&devices_rwsem);
822         return ret;
823 }
824
825 /**
826  * ib_register_device - Register an IB device with IB core
827  * @device:Device to register
828  *
829  * Low-level drivers use ib_register_device() to register their
830  * devices with the IB core.  All registered clients will receive a
831  * callback for each device that is added. @device must be allocated
832  * with ib_alloc_device().
833  *
834  * If the driver uses ops.dealloc_driver and calls any ib_unregister_device()
835  * asynchronously then the device pointer may become freed as soon as this
836  * function returns.
837  */
838 int ib_register_device(struct ib_device *device, const char *name)
839 {
840         int ret;
841
842         ret = assign_name(device, name);
843         if (ret)
844                 return ret;
845
846         ret = setup_device(device);
847         if (ret)
848                 return ret;
849
850         ret = ib_cache_setup_one(device);
851         if (ret) {
852                 dev_warn(&device->dev,
853                          "Couldn't set up InfiniBand P_Key/GID cache\n");
854                 return ret;
855         }
856
857         ib_device_register_rdmacg(device);
858
859         ret = device_add(&device->dev);
860         if (ret)
861                 goto cg_cleanup;
862
863         ret = ib_device_register_sysfs(device);
864         if (ret) {
865                 dev_warn(&device->dev,
866                          "Couldn't register device with driver model\n");
867                 goto dev_cleanup;
868         }
869
870         ret = enable_device_and_get(device);
871         if (ret) {
872                 void (*dealloc_fn)(struct ib_device *);
873
874                 /*
875                  * If we hit this error flow then we don't want to
876                  * automatically dealloc the device since the caller is
877                  * expected to call ib_dealloc_device() after
878                  * ib_register_device() fails. This is tricky due to the
879                  * possibility for a parallel unregistration along with this
880                  * error flow. Since we have a refcount here we know any
881                  * parallel flow is stopped in disable_device and will see the
882                  * NULL pointers, causing the responsibility to
883                  * ib_dealloc_device() to revert back to this thread.
884                  */
885                 dealloc_fn = device->ops.dealloc_driver;
886                 device->ops.dealloc_driver = NULL;
887                 ib_device_put(device);
888                 __ib_unregister_device(device);
889                 device->ops.dealloc_driver = dealloc_fn;
890                 return ret;
891         }
892         ib_device_put(device);
893
894         return 0;
895
896 dev_cleanup:
897         device_del(&device->dev);
898 cg_cleanup:
899         ib_device_unregister_rdmacg(device);
900         ib_cache_cleanup_one(device);
901         return ret;
902 }
903 EXPORT_SYMBOL(ib_register_device);
904
905 /* Callers must hold a get on the device. */
906 static void __ib_unregister_device(struct ib_device *ib_dev)
907 {
908         /*
909          * We have a registration lock so that all the calls to unregister are
910          * fully fenced, once any unregister returns the device is truely
911          * unregistered even if multiple callers are unregistering it at the
912          * same time. This also interacts with the registration flow and
913          * provides sane semantics if register and unregister are racing.
914          */
915         mutex_lock(&ib_dev->unregistration_lock);
916         if (!refcount_read(&ib_dev->refcount))
917                 goto out;
918
919         disable_device(ib_dev);
920         ib_device_unregister_sysfs(ib_dev);
921         device_del(&ib_dev->dev);
922         ib_device_unregister_rdmacg(ib_dev);
923         ib_cache_cleanup_one(ib_dev);
924
925         /*
926          * Drivers using the new flow may not call ib_dealloc_device except
927          * in error unwind prior to registration success.
928          */
929         if (ib_dev->ops.dealloc_driver) {
930                 WARN_ON(kref_read(&ib_dev->dev.kobj.kref) <= 1);
931                 ib_dealloc_device(ib_dev);
932         }
933 out:
934         mutex_unlock(&ib_dev->unregistration_lock);
935 }
936
937 /**
938  * ib_unregister_device - Unregister an IB device
939  * @device: The device to unregister
940  *
941  * Unregister an IB device.  All clients will receive a remove callback.
942  *
943  * Callers should call this routine only once, and protect against races with
944  * registration. Typically it should only be called as part of a remove
945  * callback in an implementation of driver core's struct device_driver and
946  * related.
947  *
948  * If ops.dealloc_driver is used then ib_dev will be freed upon return from
949  * this function.
950  */
951 void ib_unregister_device(struct ib_device *ib_dev)
952 {
953         get_device(&ib_dev->dev);
954         __ib_unregister_device(ib_dev);
955         put_device(&ib_dev->dev);
956 }
957 EXPORT_SYMBOL(ib_unregister_device);
958
959 /**
960  * ib_unregister_device_and_put - Unregister a device while holding a 'get'
961  * device: The device to unregister
962  *
963  * This is the same as ib_unregister_device(), except it includes an internal
964  * ib_device_put() that should match a 'get' obtained by the caller.
965  *
966  * It is safe to call this routine concurrently from multiple threads while
967  * holding the 'get'. When the function returns the device is fully
968  * unregistered.
969  *
970  * Drivers using this flow MUST use the driver_unregister callback to clean up
971  * their resources associated with the device and dealloc it.
972  */
973 void ib_unregister_device_and_put(struct ib_device *ib_dev)
974 {
975         WARN_ON(!ib_dev->ops.dealloc_driver);
976         get_device(&ib_dev->dev);
977         ib_device_put(ib_dev);
978         __ib_unregister_device(ib_dev);
979         put_device(&ib_dev->dev);
980 }
981 EXPORT_SYMBOL(ib_unregister_device_and_put);
982
983 /**
984  * ib_unregister_driver - Unregister all IB devices for a driver
985  * @driver_id: The driver to unregister
986  *
987  * This implements a fence for device unregistration. It only returns once all
988  * devices associated with the driver_id have fully completed their
989  * unregistration and returned from ib_unregister_device*().
990  *
991  * If device's are not yet unregistered it goes ahead and starts unregistering
992  * them.
993  *
994  * This does not block creation of new devices with the given driver_id, that
995  * is the responsibility of the caller.
996  */
997 void ib_unregister_driver(enum rdma_driver_id driver_id)
998 {
999         struct ib_device *ib_dev;
1000         unsigned long index;
1001
1002         down_read(&devices_rwsem);
1003         xa_for_each (&devices, index, ib_dev) {
1004                 if (ib_dev->driver_id != driver_id)
1005                         continue;
1006
1007                 get_device(&ib_dev->dev);
1008                 up_read(&devices_rwsem);
1009
1010                 WARN_ON(!ib_dev->ops.dealloc_driver);
1011                 __ib_unregister_device(ib_dev);
1012
1013                 put_device(&ib_dev->dev);
1014                 down_read(&devices_rwsem);
1015         }
1016         up_read(&devices_rwsem);
1017 }
1018 EXPORT_SYMBOL(ib_unregister_driver);
1019
1020 static void ib_unregister_work(struct work_struct *work)
1021 {
1022         struct ib_device *ib_dev =
1023                 container_of(work, struct ib_device, unregistration_work);
1024
1025         __ib_unregister_device(ib_dev);
1026         put_device(&ib_dev->dev);
1027 }
1028
1029 /**
1030  * ib_unregister_device_queued - Unregister a device using a work queue
1031  * device: The device to unregister
1032  *
1033  * This schedules an asynchronous unregistration using a WQ for the device. A
1034  * driver should use this to avoid holding locks while doing unregistration,
1035  * such as holding the RTNL lock.
1036  *
1037  * Drivers using this API must use ib_unregister_driver before module unload
1038  * to ensure that all scheduled unregistrations have completed.
1039  */
1040 void ib_unregister_device_queued(struct ib_device *ib_dev)
1041 {
1042         WARN_ON(!refcount_read(&ib_dev->refcount));
1043         WARN_ON(!ib_dev->ops.dealloc_driver);
1044         get_device(&ib_dev->dev);
1045         if (!queue_work(system_unbound_wq, &ib_dev->unregistration_work))
1046                 put_device(&ib_dev->dev);
1047 }
1048 EXPORT_SYMBOL(ib_unregister_device_queued);
1049
1050 static int assign_client_id(struct ib_client *client)
1051 {
1052         int ret;
1053
1054         down_write(&clients_rwsem);
1055         /*
1056          * The add/remove callbacks must be called in FIFO/LIFO order. To
1057          * achieve this we assign client_ids so they are sorted in
1058          * registration order, and retain a linked list we can reverse iterate
1059          * to get the LIFO order. The extra linked list can go away if xarray
1060          * learns to reverse iterate.
1061          */
1062         if (list_empty(&client_list))
1063                 client->client_id = 0;
1064         else
1065                 client->client_id =
1066                         list_last_entry(&client_list, struct ib_client, list)
1067                                 ->client_id;
1068         ret = xa_alloc(&clients, &client->client_id, INT_MAX, client,
1069                        GFP_KERNEL);
1070         if (ret)
1071                 goto out;
1072
1073         xa_set_mark(&clients, client->client_id, CLIENT_REGISTERED);
1074         list_add_tail(&client->list, &client_list);
1075
1076 out:
1077         up_write(&clients_rwsem);
1078         return ret;
1079 }
1080
1081 /**
1082  * ib_register_client - Register an IB client
1083  * @client:Client to register
1084  *
1085  * Upper level users of the IB drivers can use ib_register_client() to
1086  * register callbacks for IB device addition and removal.  When an IB
1087  * device is added, each registered client's add method will be called
1088  * (in the order the clients were registered), and when a device is
1089  * removed, each client's remove method will be called (in the reverse
1090  * order that clients were registered).  In addition, when
1091  * ib_register_client() is called, the client will receive an add
1092  * callback for all devices already registered.
1093  */
1094 int ib_register_client(struct ib_client *client)
1095 {
1096         struct ib_device *device;
1097         unsigned long index;
1098         int ret;
1099
1100         ret = assign_client_id(client);
1101         if (ret)
1102                 return ret;
1103
1104         down_read(&devices_rwsem);
1105         xa_for_each_marked (&devices, index, device, DEVICE_REGISTERED) {
1106                 ret = add_client_context(device, client);
1107                 if (ret) {
1108                         up_read(&devices_rwsem);
1109                         ib_unregister_client(client);
1110                         return ret;
1111                 }
1112         }
1113         up_read(&devices_rwsem);
1114         return 0;
1115 }
1116 EXPORT_SYMBOL(ib_register_client);
1117
1118 /**
1119  * ib_unregister_client - Unregister an IB client
1120  * @client:Client to unregister
1121  *
1122  * Upper level users use ib_unregister_client() to remove their client
1123  * registration.  When ib_unregister_client() is called, the client
1124  * will receive a remove callback for each IB device still registered.
1125  *
1126  * This is a full fence, once it returns no client callbacks will be called,
1127  * or are running in another thread.
1128  */
1129 void ib_unregister_client(struct ib_client *client)
1130 {
1131         struct ib_device *device;
1132         unsigned long index;
1133
1134         down_write(&clients_rwsem);
1135         xa_clear_mark(&clients, client->client_id, CLIENT_REGISTERED);
1136         up_write(&clients_rwsem);
1137         /*
1138          * Every device still known must be serialized to make sure we are
1139          * done with the client callbacks before we return.
1140          */
1141         down_read(&devices_rwsem);
1142         xa_for_each (&devices, index, device)
1143                 remove_client_context(device, client->client_id);
1144         up_read(&devices_rwsem);
1145
1146         down_write(&clients_rwsem);
1147         list_del(&client->list);
1148         xa_erase(&clients, client->client_id);
1149         up_write(&clients_rwsem);
1150 }
1151 EXPORT_SYMBOL(ib_unregister_client);
1152
1153 /**
1154  * ib_set_client_data - Set IB client context
1155  * @device:Device to set context for
1156  * @client:Client to set context for
1157  * @data:Context to set
1158  *
1159  * ib_set_client_data() sets client context data that can be retrieved with
1160  * ib_get_client_data(). This can only be called while the client is
1161  * registered to the device, once the ib_client remove() callback returns this
1162  * cannot be called.
1163  */
1164 void ib_set_client_data(struct ib_device *device, struct ib_client *client,
1165                         void *data)
1166 {
1167         void *rc;
1168
1169         if (WARN_ON(IS_ERR(data)))
1170                 data = NULL;
1171
1172         rc = xa_store(&device->client_data, client->client_id, data,
1173                       GFP_KERNEL);
1174         WARN_ON(xa_is_err(rc));
1175 }
1176 EXPORT_SYMBOL(ib_set_client_data);
1177
1178 /**
1179  * ib_register_event_handler - Register an IB event handler
1180  * @event_handler:Handler to register
1181  *
1182  * ib_register_event_handler() registers an event handler that will be
1183  * called back when asynchronous IB events occur (as defined in
1184  * chapter 11 of the InfiniBand Architecture Specification).  This
1185  * callback may occur in interrupt context.
1186  */
1187 void ib_register_event_handler(struct ib_event_handler *event_handler)
1188 {
1189         unsigned long flags;
1190
1191         spin_lock_irqsave(&event_handler->device->event_handler_lock, flags);
1192         list_add_tail(&event_handler->list,
1193                       &event_handler->device->event_handler_list);
1194         spin_unlock_irqrestore(&event_handler->device->event_handler_lock, flags);
1195 }
1196 EXPORT_SYMBOL(ib_register_event_handler);
1197
1198 /**
1199  * ib_unregister_event_handler - Unregister an event handler
1200  * @event_handler:Handler to unregister
1201  *
1202  * Unregister an event handler registered with
1203  * ib_register_event_handler().
1204  */
1205 void ib_unregister_event_handler(struct ib_event_handler *event_handler)
1206 {
1207         unsigned long flags;
1208
1209         spin_lock_irqsave(&event_handler->device->event_handler_lock, flags);
1210         list_del(&event_handler->list);
1211         spin_unlock_irqrestore(&event_handler->device->event_handler_lock, flags);
1212 }
1213 EXPORT_SYMBOL(ib_unregister_event_handler);
1214
1215 /**
1216  * ib_dispatch_event - Dispatch an asynchronous event
1217  * @event:Event to dispatch
1218  *
1219  * Low-level drivers must call ib_dispatch_event() to dispatch the
1220  * event to all registered event handlers when an asynchronous event
1221  * occurs.
1222  */
1223 void ib_dispatch_event(struct ib_event *event)
1224 {
1225         unsigned long flags;
1226         struct ib_event_handler *handler;
1227
1228         spin_lock_irqsave(&event->device->event_handler_lock, flags);
1229
1230         list_for_each_entry(handler, &event->device->event_handler_list, list)
1231                 handler->handler(handler, event);
1232
1233         spin_unlock_irqrestore(&event->device->event_handler_lock, flags);
1234 }
1235 EXPORT_SYMBOL(ib_dispatch_event);
1236
1237 /**
1238  * ib_query_port - Query IB port attributes
1239  * @device:Device to query
1240  * @port_num:Port number to query
1241  * @port_attr:Port attributes
1242  *
1243  * ib_query_port() returns the attributes of a port through the
1244  * @port_attr pointer.
1245  */
1246 int ib_query_port(struct ib_device *device,
1247                   u8 port_num,
1248                   struct ib_port_attr *port_attr)
1249 {
1250         union ib_gid gid;
1251         int err;
1252
1253         if (!rdma_is_port_valid(device, port_num))
1254                 return -EINVAL;
1255
1256         memset(port_attr, 0, sizeof(*port_attr));
1257         err = device->ops.query_port(device, port_num, port_attr);
1258         if (err || port_attr->subnet_prefix)
1259                 return err;
1260
1261         if (rdma_port_get_link_layer(device, port_num) != IB_LINK_LAYER_INFINIBAND)
1262                 return 0;
1263
1264         err = device->ops.query_gid(device, port_num, 0, &gid);
1265         if (err)
1266                 return err;
1267
1268         port_attr->subnet_prefix = be64_to_cpu(gid.global.subnet_prefix);
1269         return 0;
1270 }
1271 EXPORT_SYMBOL(ib_query_port);
1272
1273 static void add_ndev_hash(struct ib_port_data *pdata)
1274 {
1275         unsigned long flags;
1276
1277         might_sleep();
1278
1279         spin_lock_irqsave(&ndev_hash_lock, flags);
1280         if (hash_hashed(&pdata->ndev_hash_link)) {
1281                 hash_del_rcu(&pdata->ndev_hash_link);
1282                 spin_unlock_irqrestore(&ndev_hash_lock, flags);
1283                 /*
1284                  * We cannot do hash_add_rcu after a hash_del_rcu until the
1285                  * grace period
1286                  */
1287                 synchronize_rcu();
1288                 spin_lock_irqsave(&ndev_hash_lock, flags);
1289         }
1290         if (pdata->netdev)
1291                 hash_add_rcu(ndev_hash, &pdata->ndev_hash_link,
1292                              (uintptr_t)pdata->netdev);
1293         spin_unlock_irqrestore(&ndev_hash_lock, flags);
1294 }
1295
1296 /**
1297  * ib_device_set_netdev - Associate the ib_dev with an underlying net_device
1298  * @ib_dev: Device to modify
1299  * @ndev: net_device to affiliate, may be NULL
1300  * @port: IB port the net_device is connected to
1301  *
1302  * Drivers should use this to link the ib_device to a netdev so the netdev
1303  * shows up in interfaces like ib_enum_roce_netdev. Only one netdev may be
1304  * affiliated with any port.
1305  *
1306  * The caller must ensure that the given ndev is not unregistered or
1307  * unregistering, and that either the ib_device is unregistered or
1308  * ib_device_set_netdev() is called with NULL when the ndev sends a
1309  * NETDEV_UNREGISTER event.
1310  */
1311 int ib_device_set_netdev(struct ib_device *ib_dev, struct net_device *ndev,
1312                          unsigned int port)
1313 {
1314         struct net_device *old_ndev;
1315         struct ib_port_data *pdata;
1316         unsigned long flags;
1317         int ret;
1318
1319         /*
1320          * Drivers wish to call this before ib_register_driver, so we have to
1321          * setup the port data early.
1322          */
1323         ret = alloc_port_data(ib_dev);
1324         if (ret)
1325                 return ret;
1326
1327         if (!rdma_is_port_valid(ib_dev, port))
1328                 return -EINVAL;
1329
1330         pdata = &ib_dev->port_data[port];
1331         spin_lock_irqsave(&pdata->netdev_lock, flags);
1332         old_ndev = rcu_dereference_protected(
1333                 pdata->netdev, lockdep_is_held(&pdata->netdev_lock));
1334         if (old_ndev == ndev) {
1335                 spin_unlock_irqrestore(&pdata->netdev_lock, flags);
1336                 return 0;
1337         }
1338
1339         if (ndev)
1340                 dev_hold(ndev);
1341         rcu_assign_pointer(pdata->netdev, ndev);
1342         spin_unlock_irqrestore(&pdata->netdev_lock, flags);
1343
1344         add_ndev_hash(pdata);
1345         if (old_ndev)
1346                 dev_put(old_ndev);
1347
1348         return 0;
1349 }
1350 EXPORT_SYMBOL(ib_device_set_netdev);
1351
1352 static void free_netdevs(struct ib_device *ib_dev)
1353 {
1354         unsigned long flags;
1355         unsigned int port;
1356
1357         rdma_for_each_port (ib_dev, port) {
1358                 struct ib_port_data *pdata = &ib_dev->port_data[port];
1359                 struct net_device *ndev;
1360
1361                 spin_lock_irqsave(&pdata->netdev_lock, flags);
1362                 ndev = rcu_dereference_protected(
1363                         pdata->netdev, lockdep_is_held(&pdata->netdev_lock));
1364                 if (ndev) {
1365                         spin_lock(&ndev_hash_lock);
1366                         hash_del_rcu(&pdata->ndev_hash_link);
1367                         spin_unlock(&ndev_hash_lock);
1368
1369                         /*
1370                          * If this is the last dev_put there is still a
1371                          * synchronize_rcu before the netdev is kfreed, so we
1372                          * can continue to rely on unlocked pointer
1373                          * comparisons after the put
1374                          */
1375                         rcu_assign_pointer(pdata->netdev, NULL);
1376                         dev_put(ndev);
1377                 }
1378                 spin_unlock_irqrestore(&pdata->netdev_lock, flags);
1379         }
1380 }
1381
1382 struct net_device *ib_device_get_netdev(struct ib_device *ib_dev,
1383                                         unsigned int port)
1384 {
1385         struct ib_port_data *pdata;
1386         struct net_device *res;
1387
1388         if (!rdma_is_port_valid(ib_dev, port))
1389                 return NULL;
1390
1391         pdata = &ib_dev->port_data[port];
1392
1393         /*
1394          * New drivers should use ib_device_set_netdev() not the legacy
1395          * get_netdev().
1396          */
1397         if (ib_dev->ops.get_netdev)
1398                 res = ib_dev->ops.get_netdev(ib_dev, port);
1399         else {
1400                 spin_lock(&pdata->netdev_lock);
1401                 res = rcu_dereference_protected(
1402                         pdata->netdev, lockdep_is_held(&pdata->netdev_lock));
1403                 if (res)
1404                         dev_hold(res);
1405                 spin_unlock(&pdata->netdev_lock);
1406         }
1407
1408         /*
1409          * If we are starting to unregister expedite things by preventing
1410          * propagation of an unregistering netdev.
1411          */
1412         if (res && res->reg_state != NETREG_REGISTERED) {
1413                 dev_put(res);
1414                 return NULL;
1415         }
1416
1417         return res;
1418 }
1419
1420 /**
1421  * ib_device_get_by_netdev - Find an IB device associated with a netdev
1422  * @ndev: netdev to locate
1423  * @driver_id: The driver ID that must match (RDMA_DRIVER_UNKNOWN matches all)
1424  *
1425  * Find and hold an ib_device that is associated with a netdev via
1426  * ib_device_set_netdev(). The caller must call ib_device_put() on the
1427  * returned pointer.
1428  */
1429 struct ib_device *ib_device_get_by_netdev(struct net_device *ndev,
1430                                           enum rdma_driver_id driver_id)
1431 {
1432         struct ib_device *res = NULL;
1433         struct ib_port_data *cur;
1434
1435         rcu_read_lock();
1436         hash_for_each_possible_rcu (ndev_hash, cur, ndev_hash_link,
1437                                     (uintptr_t)ndev) {
1438                 if (rcu_access_pointer(cur->netdev) == ndev &&
1439                     (driver_id == RDMA_DRIVER_UNKNOWN ||
1440                      cur->ib_dev->driver_id == driver_id) &&
1441                     ib_device_try_get(cur->ib_dev)) {
1442                         res = cur->ib_dev;
1443                         break;
1444                 }
1445         }
1446         rcu_read_unlock();
1447
1448         return res;
1449 }
1450 EXPORT_SYMBOL(ib_device_get_by_netdev);
1451
1452 /**
1453  * ib_enum_roce_netdev - enumerate all RoCE ports
1454  * @ib_dev : IB device we want to query
1455  * @filter: Should we call the callback?
1456  * @filter_cookie: Cookie passed to filter
1457  * @cb: Callback to call for each found RoCE ports
1458  * @cookie: Cookie passed back to the callback
1459  *
1460  * Enumerates all of the physical RoCE ports of ib_dev
1461  * which are related to netdevice and calls callback() on each
1462  * device for which filter() function returns non zero.
1463  */
1464 void ib_enum_roce_netdev(struct ib_device *ib_dev,
1465                          roce_netdev_filter filter,
1466                          void *filter_cookie,
1467                          roce_netdev_callback cb,
1468                          void *cookie)
1469 {
1470         unsigned int port;
1471
1472         rdma_for_each_port (ib_dev, port)
1473                 if (rdma_protocol_roce(ib_dev, port)) {
1474                         struct net_device *idev =
1475                                 ib_device_get_netdev(ib_dev, port);
1476
1477                         if (filter(ib_dev, port, idev, filter_cookie))
1478                                 cb(ib_dev, port, idev, cookie);
1479
1480                         if (idev)
1481                                 dev_put(idev);
1482                 }
1483 }
1484
1485 /**
1486  * ib_enum_all_roce_netdevs - enumerate all RoCE devices
1487  * @filter: Should we call the callback?
1488  * @filter_cookie: Cookie passed to filter
1489  * @cb: Callback to call for each found RoCE ports
1490  * @cookie: Cookie passed back to the callback
1491  *
1492  * Enumerates all RoCE devices' physical ports which are related
1493  * to netdevices and calls callback() on each device for which
1494  * filter() function returns non zero.
1495  */
1496 void ib_enum_all_roce_netdevs(roce_netdev_filter filter,
1497                               void *filter_cookie,
1498                               roce_netdev_callback cb,
1499                               void *cookie)
1500 {
1501         struct ib_device *dev;
1502         unsigned long index;
1503
1504         down_read(&devices_rwsem);
1505         xa_for_each_marked (&devices, index, dev, DEVICE_REGISTERED)
1506                 ib_enum_roce_netdev(dev, filter, filter_cookie, cb, cookie);
1507         up_read(&devices_rwsem);
1508 }
1509
1510 /**
1511  * ib_enum_all_devs - enumerate all ib_devices
1512  * @cb: Callback to call for each found ib_device
1513  *
1514  * Enumerates all ib_devices and calls callback() on each device.
1515  */
1516 int ib_enum_all_devs(nldev_callback nldev_cb, struct sk_buff *skb,
1517                      struct netlink_callback *cb)
1518 {
1519         unsigned long index;
1520         struct ib_device *dev;
1521         unsigned int idx = 0;
1522         int ret = 0;
1523
1524         down_read(&devices_rwsem);
1525         xa_for_each_marked (&devices, index, dev, DEVICE_REGISTERED) {
1526                 ret = nldev_cb(dev, skb, cb, idx);
1527                 if (ret)
1528                         break;
1529                 idx++;
1530         }
1531         up_read(&devices_rwsem);
1532         return ret;
1533 }
1534
1535 /**
1536  * ib_query_pkey - Get P_Key table entry
1537  * @device:Device to query
1538  * @port_num:Port number to query
1539  * @index:P_Key table index to query
1540  * @pkey:Returned P_Key
1541  *
1542  * ib_query_pkey() fetches the specified P_Key table entry.
1543  */
1544 int ib_query_pkey(struct ib_device *device,
1545                   u8 port_num, u16 index, u16 *pkey)
1546 {
1547         if (!rdma_is_port_valid(device, port_num))
1548                 return -EINVAL;
1549
1550         return device->ops.query_pkey(device, port_num, index, pkey);
1551 }
1552 EXPORT_SYMBOL(ib_query_pkey);
1553
1554 /**
1555  * ib_modify_device - Change IB device attributes
1556  * @device:Device to modify
1557  * @device_modify_mask:Mask of attributes to change
1558  * @device_modify:New attribute values
1559  *
1560  * ib_modify_device() changes a device's attributes as specified by
1561  * the @device_modify_mask and @device_modify structure.
1562  */
1563 int ib_modify_device(struct ib_device *device,
1564                      int device_modify_mask,
1565                      struct ib_device_modify *device_modify)
1566 {
1567         if (!device->ops.modify_device)
1568                 return -ENOSYS;
1569
1570         return device->ops.modify_device(device, device_modify_mask,
1571                                          device_modify);
1572 }
1573 EXPORT_SYMBOL(ib_modify_device);
1574
1575 /**
1576  * ib_modify_port - Modifies the attributes for the specified port.
1577  * @device: The device to modify.
1578  * @port_num: The number of the port to modify.
1579  * @port_modify_mask: Mask used to specify which attributes of the port
1580  *   to change.
1581  * @port_modify: New attribute values for the port.
1582  *
1583  * ib_modify_port() changes a port's attributes as specified by the
1584  * @port_modify_mask and @port_modify structure.
1585  */
1586 int ib_modify_port(struct ib_device *device,
1587                    u8 port_num, int port_modify_mask,
1588                    struct ib_port_modify *port_modify)
1589 {
1590         int rc;
1591
1592         if (!rdma_is_port_valid(device, port_num))
1593                 return -EINVAL;
1594
1595         if (device->ops.modify_port)
1596                 rc = device->ops.modify_port(device, port_num,
1597                                              port_modify_mask,
1598                                              port_modify);
1599         else
1600                 rc = rdma_protocol_roce(device, port_num) ? 0 : -ENOSYS;
1601         return rc;
1602 }
1603 EXPORT_SYMBOL(ib_modify_port);
1604
1605 /**
1606  * ib_find_gid - Returns the port number and GID table index where
1607  *   a specified GID value occurs. Its searches only for IB link layer.
1608  * @device: The device to query.
1609  * @gid: The GID value to search for.
1610  * @port_num: The port number of the device where the GID value was found.
1611  * @index: The index into the GID table where the GID was found.  This
1612  *   parameter may be NULL.
1613  */
1614 int ib_find_gid(struct ib_device *device, union ib_gid *gid,
1615                 u8 *port_num, u16 *index)
1616 {
1617         union ib_gid tmp_gid;
1618         unsigned int port;
1619         int ret, i;
1620
1621         rdma_for_each_port (device, port) {
1622                 if (!rdma_protocol_ib(device, port))
1623                         continue;
1624
1625                 for (i = 0; i < device->port_data[port].immutable.gid_tbl_len;
1626                      ++i) {
1627                         ret = rdma_query_gid(device, port, i, &tmp_gid);
1628                         if (ret)
1629                                 return ret;
1630                         if (!memcmp(&tmp_gid, gid, sizeof *gid)) {
1631                                 *port_num = port;
1632                                 if (index)
1633                                         *index = i;
1634                                 return 0;
1635                         }
1636                 }
1637         }
1638
1639         return -ENOENT;
1640 }
1641 EXPORT_SYMBOL(ib_find_gid);
1642
1643 /**
1644  * ib_find_pkey - Returns the PKey table index where a specified
1645  *   PKey value occurs.
1646  * @device: The device to query.
1647  * @port_num: The port number of the device to search for the PKey.
1648  * @pkey: The PKey value to search for.
1649  * @index: The index into the PKey table where the PKey was found.
1650  */
1651 int ib_find_pkey(struct ib_device *device,
1652                  u8 port_num, u16 pkey, u16 *index)
1653 {
1654         int ret, i;
1655         u16 tmp_pkey;
1656         int partial_ix = -1;
1657
1658         for (i = 0; i < device->port_data[port_num].immutable.pkey_tbl_len;
1659              ++i) {
1660                 ret = ib_query_pkey(device, port_num, i, &tmp_pkey);
1661                 if (ret)
1662                         return ret;
1663                 if ((pkey & 0x7fff) == (tmp_pkey & 0x7fff)) {
1664                         /* if there is full-member pkey take it.*/
1665                         if (tmp_pkey & 0x8000) {
1666                                 *index = i;
1667                                 return 0;
1668                         }
1669                         if (partial_ix < 0)
1670                                 partial_ix = i;
1671                 }
1672         }
1673
1674         /*no full-member, if exists take the limited*/
1675         if (partial_ix >= 0) {
1676                 *index = partial_ix;
1677                 return 0;
1678         }
1679         return -ENOENT;
1680 }
1681 EXPORT_SYMBOL(ib_find_pkey);
1682
1683 /**
1684  * ib_get_net_dev_by_params() - Return the appropriate net_dev
1685  * for a received CM request
1686  * @dev:        An RDMA device on which the request has been received.
1687  * @port:       Port number on the RDMA device.
1688  * @pkey:       The Pkey the request came on.
1689  * @gid:        A GID that the net_dev uses to communicate.
1690  * @addr:       Contains the IP address that the request specified as its
1691  *              destination.
1692  *
1693  */
1694 struct net_device *ib_get_net_dev_by_params(struct ib_device *dev,
1695                                             u8 port,
1696                                             u16 pkey,
1697                                             const union ib_gid *gid,
1698                                             const struct sockaddr *addr)
1699 {
1700         struct net_device *net_dev = NULL;
1701         unsigned long index;
1702         void *client_data;
1703
1704         if (!rdma_protocol_ib(dev, port))
1705                 return NULL;
1706
1707         /*
1708          * Holding the read side guarantees that the client will not become
1709          * unregistered while we are calling get_net_dev_by_params()
1710          */
1711         down_read(&dev->client_data_rwsem);
1712         xan_for_each_marked (&dev->client_data, index, client_data,
1713                              CLIENT_DATA_REGISTERED) {
1714                 struct ib_client *client = xa_load(&clients, index);
1715
1716                 if (!client || !client->get_net_dev_by_params)
1717                         continue;
1718
1719                 net_dev = client->get_net_dev_by_params(dev, port, pkey, gid,
1720                                                         addr, client_data);
1721                 if (net_dev)
1722                         break;
1723         }
1724         up_read(&dev->client_data_rwsem);
1725
1726         return net_dev;
1727 }
1728 EXPORT_SYMBOL(ib_get_net_dev_by_params);
1729
1730 void ib_set_device_ops(struct ib_device *dev, const struct ib_device_ops *ops)
1731 {
1732         struct ib_device_ops *dev_ops = &dev->ops;
1733 #define SET_DEVICE_OP(ptr, name)                                               \
1734         do {                                                                   \
1735                 if (ops->name)                                                 \
1736                         if (!((ptr)->name))                                    \
1737                                 (ptr)->name = ops->name;                       \
1738         } while (0)
1739
1740 #define SET_OBJ_SIZE(ptr, name) SET_DEVICE_OP(ptr, size_##name)
1741
1742         SET_DEVICE_OP(dev_ops, add_gid);
1743         SET_DEVICE_OP(dev_ops, advise_mr);
1744         SET_DEVICE_OP(dev_ops, alloc_dm);
1745         SET_DEVICE_OP(dev_ops, alloc_fmr);
1746         SET_DEVICE_OP(dev_ops, alloc_hw_stats);
1747         SET_DEVICE_OP(dev_ops, alloc_mr);
1748         SET_DEVICE_OP(dev_ops, alloc_mw);
1749         SET_DEVICE_OP(dev_ops, alloc_pd);
1750         SET_DEVICE_OP(dev_ops, alloc_rdma_netdev);
1751         SET_DEVICE_OP(dev_ops, alloc_ucontext);
1752         SET_DEVICE_OP(dev_ops, alloc_xrcd);
1753         SET_DEVICE_OP(dev_ops, attach_mcast);
1754         SET_DEVICE_OP(dev_ops, check_mr_status);
1755         SET_DEVICE_OP(dev_ops, create_ah);
1756         SET_DEVICE_OP(dev_ops, create_counters);
1757         SET_DEVICE_OP(dev_ops, create_cq);
1758         SET_DEVICE_OP(dev_ops, create_flow);
1759         SET_DEVICE_OP(dev_ops, create_flow_action_esp);
1760         SET_DEVICE_OP(dev_ops, create_qp);
1761         SET_DEVICE_OP(dev_ops, create_rwq_ind_table);
1762         SET_DEVICE_OP(dev_ops, create_srq);
1763         SET_DEVICE_OP(dev_ops, create_wq);
1764         SET_DEVICE_OP(dev_ops, dealloc_dm);
1765         SET_DEVICE_OP(dev_ops, dealloc_driver);
1766         SET_DEVICE_OP(dev_ops, dealloc_fmr);
1767         SET_DEVICE_OP(dev_ops, dealloc_mw);
1768         SET_DEVICE_OP(dev_ops, dealloc_pd);
1769         SET_DEVICE_OP(dev_ops, dealloc_ucontext);
1770         SET_DEVICE_OP(dev_ops, dealloc_xrcd);
1771         SET_DEVICE_OP(dev_ops, del_gid);
1772         SET_DEVICE_OP(dev_ops, dereg_mr);
1773         SET_DEVICE_OP(dev_ops, destroy_ah);
1774         SET_DEVICE_OP(dev_ops, destroy_counters);
1775         SET_DEVICE_OP(dev_ops, destroy_cq);
1776         SET_DEVICE_OP(dev_ops, destroy_flow);
1777         SET_DEVICE_OP(dev_ops, destroy_flow_action);
1778         SET_DEVICE_OP(dev_ops, destroy_qp);
1779         SET_DEVICE_OP(dev_ops, destroy_rwq_ind_table);
1780         SET_DEVICE_OP(dev_ops, destroy_srq);
1781         SET_DEVICE_OP(dev_ops, destroy_wq);
1782         SET_DEVICE_OP(dev_ops, detach_mcast);
1783         SET_DEVICE_OP(dev_ops, disassociate_ucontext);
1784         SET_DEVICE_OP(dev_ops, drain_rq);
1785         SET_DEVICE_OP(dev_ops, drain_sq);
1786         SET_DEVICE_OP(dev_ops, enable_driver);
1787         SET_DEVICE_OP(dev_ops, fill_res_entry);
1788         SET_DEVICE_OP(dev_ops, get_dev_fw_str);
1789         SET_DEVICE_OP(dev_ops, get_dma_mr);
1790         SET_DEVICE_OP(dev_ops, get_hw_stats);
1791         SET_DEVICE_OP(dev_ops, get_link_layer);
1792         SET_DEVICE_OP(dev_ops, get_netdev);
1793         SET_DEVICE_OP(dev_ops, get_port_immutable);
1794         SET_DEVICE_OP(dev_ops, get_vector_affinity);
1795         SET_DEVICE_OP(dev_ops, get_vf_config);
1796         SET_DEVICE_OP(dev_ops, get_vf_stats);
1797         SET_DEVICE_OP(dev_ops, init_port);
1798         SET_DEVICE_OP(dev_ops, map_mr_sg);
1799         SET_DEVICE_OP(dev_ops, map_phys_fmr);
1800         SET_DEVICE_OP(dev_ops, mmap);
1801         SET_DEVICE_OP(dev_ops, modify_ah);
1802         SET_DEVICE_OP(dev_ops, modify_cq);
1803         SET_DEVICE_OP(dev_ops, modify_device);
1804         SET_DEVICE_OP(dev_ops, modify_flow_action_esp);
1805         SET_DEVICE_OP(dev_ops, modify_port);
1806         SET_DEVICE_OP(dev_ops, modify_qp);
1807         SET_DEVICE_OP(dev_ops, modify_srq);
1808         SET_DEVICE_OP(dev_ops, modify_wq);
1809         SET_DEVICE_OP(dev_ops, peek_cq);
1810         SET_DEVICE_OP(dev_ops, poll_cq);
1811         SET_DEVICE_OP(dev_ops, post_recv);
1812         SET_DEVICE_OP(dev_ops, post_send);
1813         SET_DEVICE_OP(dev_ops, post_srq_recv);
1814         SET_DEVICE_OP(dev_ops, process_mad);
1815         SET_DEVICE_OP(dev_ops, query_ah);
1816         SET_DEVICE_OP(dev_ops, query_device);
1817         SET_DEVICE_OP(dev_ops, query_gid);
1818         SET_DEVICE_OP(dev_ops, query_pkey);
1819         SET_DEVICE_OP(dev_ops, query_port);
1820         SET_DEVICE_OP(dev_ops, query_qp);
1821         SET_DEVICE_OP(dev_ops, query_srq);
1822         SET_DEVICE_OP(dev_ops, rdma_netdev_get_params);
1823         SET_DEVICE_OP(dev_ops, read_counters);
1824         SET_DEVICE_OP(dev_ops, reg_dm_mr);
1825         SET_DEVICE_OP(dev_ops, reg_user_mr);
1826         SET_DEVICE_OP(dev_ops, req_ncomp_notif);
1827         SET_DEVICE_OP(dev_ops, req_notify_cq);
1828         SET_DEVICE_OP(dev_ops, rereg_user_mr);
1829         SET_DEVICE_OP(dev_ops, resize_cq);
1830         SET_DEVICE_OP(dev_ops, set_vf_guid);
1831         SET_DEVICE_OP(dev_ops, set_vf_link_state);
1832         SET_DEVICE_OP(dev_ops, unmap_fmr);
1833
1834         SET_OBJ_SIZE(dev_ops, ib_pd);
1835         SET_OBJ_SIZE(dev_ops, ib_ucontext);
1836 }
1837 EXPORT_SYMBOL(ib_set_device_ops);
1838
1839 static const struct rdma_nl_cbs ibnl_ls_cb_table[RDMA_NL_LS_NUM_OPS] = {
1840         [RDMA_NL_LS_OP_RESOLVE] = {
1841                 .doit = ib_nl_handle_resolve_resp,
1842                 .flags = RDMA_NL_ADMIN_PERM,
1843         },
1844         [RDMA_NL_LS_OP_SET_TIMEOUT] = {
1845                 .doit = ib_nl_handle_set_timeout,
1846                 .flags = RDMA_NL_ADMIN_PERM,
1847         },
1848         [RDMA_NL_LS_OP_IP_RESOLVE] = {
1849                 .doit = ib_nl_handle_ip_res_resp,
1850                 .flags = RDMA_NL_ADMIN_PERM,
1851         },
1852 };
1853
1854 static int __init ib_core_init(void)
1855 {
1856         int ret;
1857
1858         ib_wq = alloc_workqueue("infiniband", 0, 0);
1859         if (!ib_wq)
1860                 return -ENOMEM;
1861
1862         ib_comp_wq = alloc_workqueue("ib-comp-wq",
1863                         WQ_HIGHPRI | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
1864         if (!ib_comp_wq) {
1865                 ret = -ENOMEM;
1866                 goto err;
1867         }
1868
1869         ib_comp_unbound_wq =
1870                 alloc_workqueue("ib-comp-unb-wq",
1871                                 WQ_UNBOUND | WQ_HIGHPRI | WQ_MEM_RECLAIM |
1872                                 WQ_SYSFS, WQ_UNBOUND_MAX_ACTIVE);
1873         if (!ib_comp_unbound_wq) {
1874                 ret = -ENOMEM;
1875                 goto err_comp;
1876         }
1877
1878         ret = class_register(&ib_class);
1879         if (ret) {
1880                 pr_warn("Couldn't create InfiniBand device class\n");
1881                 goto err_comp_unbound;
1882         }
1883
1884         ret = rdma_nl_init();
1885         if (ret) {
1886                 pr_warn("Couldn't init IB netlink interface: err %d\n", ret);
1887                 goto err_sysfs;
1888         }
1889
1890         ret = addr_init();
1891         if (ret) {
1892                 pr_warn("Could't init IB address resolution\n");
1893                 goto err_ibnl;
1894         }
1895
1896         ret = ib_mad_init();
1897         if (ret) {
1898                 pr_warn("Couldn't init IB MAD\n");
1899                 goto err_addr;
1900         }
1901
1902         ret = ib_sa_init();
1903         if (ret) {
1904                 pr_warn("Couldn't init SA\n");
1905                 goto err_mad;
1906         }
1907
1908         ret = register_lsm_notifier(&ibdev_lsm_nb);
1909         if (ret) {
1910                 pr_warn("Couldn't register LSM notifier. ret %d\n", ret);
1911                 goto err_sa;
1912         }
1913
1914         nldev_init();
1915         rdma_nl_register(RDMA_NL_LS, ibnl_ls_cb_table);
1916         roce_gid_mgmt_init();
1917
1918         return 0;
1919
1920 err_sa:
1921         ib_sa_cleanup();
1922 err_mad:
1923         ib_mad_cleanup();
1924 err_addr:
1925         addr_cleanup();
1926 err_ibnl:
1927         rdma_nl_exit();
1928 err_sysfs:
1929         class_unregister(&ib_class);
1930 err_comp_unbound:
1931         destroy_workqueue(ib_comp_unbound_wq);
1932 err_comp:
1933         destroy_workqueue(ib_comp_wq);
1934 err:
1935         destroy_workqueue(ib_wq);
1936         return ret;
1937 }
1938
1939 static void __exit ib_core_cleanup(void)
1940 {
1941         roce_gid_mgmt_cleanup();
1942         nldev_exit();
1943         rdma_nl_unregister(RDMA_NL_LS);
1944         unregister_lsm_notifier(&ibdev_lsm_nb);
1945         ib_sa_cleanup();
1946         ib_mad_cleanup();
1947         addr_cleanup();
1948         rdma_nl_exit();
1949         class_unregister(&ib_class);
1950         destroy_workqueue(ib_comp_unbound_wq);
1951         destroy_workqueue(ib_comp_wq);
1952         /* Make sure that any pending umem accounting work is done. */
1953         destroy_workqueue(ib_wq);
1954         flush_workqueue(system_unbound_wq);
1955         WARN_ON(!xa_empty(&clients));
1956         WARN_ON(!xa_empty(&devices));
1957 }
1958
1959 MODULE_ALIAS_RDMA_NETLINK(RDMA_NL_LS, 4);
1960
1961 subsys_initcall(ib_core_init);
1962 module_exit(ib_core_cleanup);