Whamcloud - gitweb
Revert "LU-7030 security: put imp_sec after all requests drained off"
[fs/lustre-release.git] / lustre / obdclass / genops.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2015, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/obdclass/genops.c
37  *
38  * These are the only exported functions, they provide some generic
39  * infrastructure for managing object devices
40  */
41
42 #define DEBUG_SUBSYSTEM S_CLASS
43
44 #include <linux/kthread.h>
45 #include <obd_class.h>
46 #include <lprocfs_status.h>
47 #include <lustre_disk.h>
48 #include <lustre_kernelcomm.h>
49
50 spinlock_t obd_types_lock;
51
52 static struct kmem_cache *obd_device_cachep;
53 struct kmem_cache *obdo_cachep;
54 EXPORT_SYMBOL(obdo_cachep);
55 static struct kmem_cache *import_cachep;
56
57 static struct list_head obd_zombie_imports;
58 static struct list_head obd_zombie_exports;
59 static spinlock_t  obd_zombie_impexp_lock;
60
61 static void obd_zombie_impexp_notify(void);
62 static void obd_zombie_export_add(struct obd_export *exp);
63 static void obd_zombie_import_add(struct obd_import *imp);
64 static void print_export_data(struct obd_export *exp,
65                               const char *status, int locks);
66
67 struct list_head obd_stale_exports;
68 spinlock_t       obd_stale_export_lock;
69 atomic_t         obd_stale_export_num;
70
71 int (*ptlrpc_put_connection_superhack)(struct ptlrpc_connection *c);
72 EXPORT_SYMBOL(ptlrpc_put_connection_superhack);
73
74 /*
75  * support functions: we could use inter-module communication, but this
76  * is more portable to other OS's
77  */
78 static struct obd_device *obd_device_alloc(void)
79 {
80         struct obd_device *obd;
81
82         OBD_SLAB_ALLOC_PTR_GFP(obd, obd_device_cachep, GFP_NOFS);
83         if (obd != NULL) {
84                 obd->obd_magic = OBD_DEVICE_MAGIC;
85         }
86         return obd;
87 }
88
89 static void obd_device_free(struct obd_device *obd)
90 {
91         LASSERT(obd != NULL);
92         LASSERTF(obd->obd_magic == OBD_DEVICE_MAGIC, "obd %p obd_magic %08x != %08x\n",
93                  obd, obd->obd_magic, OBD_DEVICE_MAGIC);
94         if (obd->obd_namespace != NULL) {
95                 CERROR("obd %p: namespace %p was not properly cleaned up (obd_force=%d)!\n",
96                        obd, obd->obd_namespace, obd->obd_force);
97                 LBUG();
98         }
99         lu_ref_fini(&obd->obd_reference);
100         OBD_SLAB_FREE_PTR(obd, obd_device_cachep);
101 }
102
103 struct obd_type *class_search_type(const char *name)
104 {
105         struct list_head *tmp;
106         struct obd_type *type;
107
108         spin_lock(&obd_types_lock);
109         list_for_each(tmp, &obd_types) {
110                 type = list_entry(tmp, struct obd_type, typ_chain);
111                 if (strcmp(type->typ_name, name) == 0) {
112                         spin_unlock(&obd_types_lock);
113                         return type;
114                 }
115         }
116         spin_unlock(&obd_types_lock);
117         return NULL;
118 }
119 EXPORT_SYMBOL(class_search_type);
120
121 struct obd_type *class_get_type(const char *name)
122 {
123         struct obd_type *type = class_search_type(name);
124
125 #ifdef HAVE_MODULE_LOADING_SUPPORT
126         if (!type) {
127                 const char *modname = name;
128
129                 if (strcmp(modname, "obdfilter") == 0)
130                         modname = "ofd";
131
132                 if (strcmp(modname, LUSTRE_LWP_NAME) == 0)
133                         modname = LUSTRE_OSP_NAME;
134
135                 if (!strncmp(modname, LUSTRE_MDS_NAME, strlen(LUSTRE_MDS_NAME)))
136                         modname = LUSTRE_MDT_NAME;
137
138                 if (!request_module("%s", modname)) {
139                         CDEBUG(D_INFO, "Loaded module '%s'\n", modname);
140                         type = class_search_type(name);
141                 } else {
142                         LCONSOLE_ERROR_MSG(0x158, "Can't load module '%s'\n",
143                                            modname);
144                 }
145         }
146 #endif
147         if (type) {
148                 spin_lock(&type->obd_type_lock);
149                 type->typ_refcnt++;
150                 try_module_get(type->typ_dt_ops->o_owner);
151                 spin_unlock(&type->obd_type_lock);
152         }
153         return type;
154 }
155
156 void class_put_type(struct obd_type *type)
157 {
158         LASSERT(type);
159         spin_lock(&type->obd_type_lock);
160         type->typ_refcnt--;
161         module_put(type->typ_dt_ops->o_owner);
162         spin_unlock(&type->obd_type_lock);
163 }
164
165 #define CLASS_MAX_NAME 1024
166
167 int class_register_type(struct obd_ops *dt_ops, struct md_ops *md_ops,
168                         bool enable_proc, struct lprocfs_vars *vars,
169                         const char *name, struct lu_device_type *ldt)
170 {
171         struct obd_type *type;
172         int rc = 0;
173         ENTRY;
174
175         /* sanity check */
176         LASSERT(strnlen(name, CLASS_MAX_NAME) < CLASS_MAX_NAME);
177
178         if (class_search_type(name)) {
179                 CDEBUG(D_IOCTL, "Type %s already registered\n", name);
180                 RETURN(-EEXIST);
181         }
182
183         rc = -ENOMEM;
184         OBD_ALLOC(type, sizeof(*type));
185         if (type == NULL)
186                 RETURN(rc);
187
188         OBD_ALLOC_PTR(type->typ_dt_ops);
189         OBD_ALLOC_PTR(type->typ_md_ops);
190         OBD_ALLOC(type->typ_name, strlen(name) + 1);
191
192         if (type->typ_dt_ops == NULL ||
193             type->typ_md_ops == NULL ||
194             type->typ_name == NULL)
195                 GOTO (failed, rc);
196
197         *(type->typ_dt_ops) = *dt_ops;
198         /* md_ops is optional */
199         if (md_ops)
200                 *(type->typ_md_ops) = *md_ops;
201         strcpy(type->typ_name, name);
202         spin_lock_init(&type->obd_type_lock);
203
204 #ifdef CONFIG_PROC_FS
205         if (enable_proc) {
206                 type->typ_procroot = lprocfs_register(type->typ_name,
207                                                       proc_lustre_root,
208                                                       vars, type);
209                 if (IS_ERR(type->typ_procroot)) {
210                         rc = PTR_ERR(type->typ_procroot);
211                         type->typ_procroot = NULL;
212                         GOTO(failed, rc);
213                 }
214         }
215 #endif
216         if (ldt != NULL) {
217                 type->typ_lu = ldt;
218                 rc = lu_device_type_init(ldt);
219                 if (rc != 0)
220                         GOTO (failed, rc);
221         }
222
223         spin_lock(&obd_types_lock);
224         list_add(&type->typ_chain, &obd_types);
225         spin_unlock(&obd_types_lock);
226
227         RETURN (0);
228
229 failed:
230         if (type->typ_name != NULL) {
231 #ifdef CONFIG_PROC_FS
232                 if (type->typ_procroot != NULL)
233                         remove_proc_subtree(type->typ_name, proc_lustre_root);
234 #endif
235                 OBD_FREE(type->typ_name, strlen(name) + 1);
236         }
237         if (type->typ_md_ops != NULL)
238                 OBD_FREE_PTR(type->typ_md_ops);
239         if (type->typ_dt_ops != NULL)
240                 OBD_FREE_PTR(type->typ_dt_ops);
241         OBD_FREE(type, sizeof(*type));
242         RETURN(rc);
243 }
244 EXPORT_SYMBOL(class_register_type);
245
246 int class_unregister_type(const char *name)
247 {
248         struct obd_type *type = class_search_type(name);
249         ENTRY;
250
251         if (!type) {
252                 CERROR("unknown obd type\n");
253                 RETURN(-EINVAL);
254         }
255
256         if (type->typ_refcnt) {
257                 CERROR("type %s has refcount (%d)\n", name, type->typ_refcnt);
258                 /* This is a bad situation, let's make the best of it */
259                 /* Remove ops, but leave the name for debugging */
260                 OBD_FREE_PTR(type->typ_dt_ops);
261                 OBD_FREE_PTR(type->typ_md_ops);
262                 RETURN(-EBUSY);
263         }
264
265         /* we do not use type->typ_procroot as for compatibility purposes
266          * other modules can share names (i.e. lod can use lov entry). so
267          * we can't reference pointer as it can get invalided when another
268          * module removes the entry */
269 #ifdef CONFIG_PROC_FS
270         if (type->typ_procroot != NULL)
271                 remove_proc_subtree(type->typ_name, proc_lustre_root);
272         if (type->typ_procsym != NULL)
273                 lprocfs_remove(&type->typ_procsym);
274 #endif
275         if (type->typ_lu)
276                 lu_device_type_fini(type->typ_lu);
277
278         spin_lock(&obd_types_lock);
279         list_del(&type->typ_chain);
280         spin_unlock(&obd_types_lock);
281         OBD_FREE(type->typ_name, strlen(name) + 1);
282         if (type->typ_dt_ops != NULL)
283                 OBD_FREE_PTR(type->typ_dt_ops);
284         if (type->typ_md_ops != NULL)
285                 OBD_FREE_PTR(type->typ_md_ops);
286         OBD_FREE(type, sizeof(*type));
287         RETURN(0);
288 } /* class_unregister_type */
289 EXPORT_SYMBOL(class_unregister_type);
290
291 /**
292  * Create a new obd device.
293  *
294  * Find an empty slot in ::obd_devs[], create a new obd device in it.
295  *
296  * \param[in] type_name obd device type string.
297  * \param[in] name      obd device name.
298  *
299  * \retval NULL if create fails, otherwise return the obd device
300  *         pointer created.
301  */
302 struct obd_device *class_newdev(const char *type_name, const char *name)
303 {
304         struct obd_device *result = NULL;
305         struct obd_device *newdev;
306         struct obd_type *type = NULL;
307         int i;
308         int new_obd_minor = 0;
309         ENTRY;
310
311         if (strlen(name) >= MAX_OBD_NAME) {
312                 CERROR("name/uuid must be < %u bytes long\n", MAX_OBD_NAME);
313                 RETURN(ERR_PTR(-EINVAL));
314         }
315
316         type = class_get_type(type_name);
317         if (type == NULL){
318                 CERROR("OBD: unknown type: %s\n", type_name);
319                 RETURN(ERR_PTR(-ENODEV));
320         }
321
322         newdev = obd_device_alloc();
323         if (newdev == NULL)
324                 GOTO(out_type, result = ERR_PTR(-ENOMEM));
325
326         LASSERT(newdev->obd_magic == OBD_DEVICE_MAGIC);
327
328         write_lock(&obd_dev_lock);
329         for (i = 0; i < class_devno_max(); i++) {
330                 struct obd_device *obd = class_num2obd(i);
331
332                 if (obd && (strcmp(name, obd->obd_name) == 0)) {
333                         CERROR("Device %s already exists at %d, won't add\n",
334                                name, i);
335                         if (result) {
336                                 LASSERTF(result->obd_magic == OBD_DEVICE_MAGIC,
337                                          "%p obd_magic %08x != %08x\n", result,
338                                          result->obd_magic, OBD_DEVICE_MAGIC);
339                                 LASSERTF(result->obd_minor == new_obd_minor,
340                                          "%p obd_minor %d != %d\n", result,
341                                          result->obd_minor, new_obd_minor);
342
343                                 obd_devs[result->obd_minor] = NULL;
344                                 result->obd_name[0]='\0';
345                          }
346                         result = ERR_PTR(-EEXIST);
347                         break;
348                 }
349                 if (!result && !obd) {
350                         result = newdev;
351                         result->obd_minor = i;
352                         new_obd_minor = i;
353                         result->obd_type = type;
354                         strncpy(result->obd_name, name,
355                                 sizeof(result->obd_name) - 1);
356                         obd_devs[i] = result;
357                 }
358         }
359         write_unlock(&obd_dev_lock);
360
361         if (result == NULL && i >= class_devno_max()) {
362                 CERROR("all %u OBD devices used, increase MAX_OBD_DEVICES\n",
363                        class_devno_max());
364                 GOTO(out, result = ERR_PTR(-EOVERFLOW));
365         }
366
367         if (IS_ERR(result))
368                 GOTO(out, result);
369
370         CDEBUG(D_IOCTL, "Adding new device %s (%p)\n",
371                result->obd_name, result);
372
373         RETURN(result);
374 out:
375         obd_device_free(newdev);
376 out_type:
377         class_put_type(type);
378         return result;
379 }
380
381 void class_release_dev(struct obd_device *obd)
382 {
383         struct obd_type *obd_type = obd->obd_type;
384
385         LASSERTF(obd->obd_magic == OBD_DEVICE_MAGIC, "%p obd_magic %08x != %08x\n",
386                  obd, obd->obd_magic, OBD_DEVICE_MAGIC);
387         LASSERTF(obd == obd_devs[obd->obd_minor], "obd %p != obd_devs[%d] %p\n",
388                  obd, obd->obd_minor, obd_devs[obd->obd_minor]);
389         LASSERT(obd_type != NULL);
390
391         CDEBUG(D_INFO, "Release obd device %s at %d obd_type name =%s\n",
392                obd->obd_name, obd->obd_minor, obd->obd_type->typ_name);
393
394         write_lock(&obd_dev_lock);
395         obd_devs[obd->obd_minor] = NULL;
396         write_unlock(&obd_dev_lock);
397         obd_device_free(obd);
398
399         class_put_type(obd_type);
400 }
401
402 int class_name2dev(const char *name)
403 {
404         int i;
405
406         if (!name)
407                 return -1;
408
409         read_lock(&obd_dev_lock);
410         for (i = 0; i < class_devno_max(); i++) {
411                 struct obd_device *obd = class_num2obd(i);
412
413                 if (obd && strcmp(name, obd->obd_name) == 0) {
414                         /* Make sure we finished attaching before we give
415                            out any references */
416                         LASSERT(obd->obd_magic == OBD_DEVICE_MAGIC);
417                         if (obd->obd_attached) {
418                                 read_unlock(&obd_dev_lock);
419                                 return i;
420                         }
421                         break;
422                 }
423         }
424         read_unlock(&obd_dev_lock);
425
426         return -1;
427 }
428
429 struct obd_device *class_name2obd(const char *name)
430 {
431         int dev = class_name2dev(name);
432
433         if (dev < 0 || dev > class_devno_max())
434                 return NULL;
435         return class_num2obd(dev);
436 }
437 EXPORT_SYMBOL(class_name2obd);
438
439 int class_uuid2dev(struct obd_uuid *uuid)
440 {
441         int i;
442
443         read_lock(&obd_dev_lock);
444         for (i = 0; i < class_devno_max(); i++) {
445                 struct obd_device *obd = class_num2obd(i);
446
447                 if (obd && obd_uuid_equals(uuid, &obd->obd_uuid)) {
448                         LASSERT(obd->obd_magic == OBD_DEVICE_MAGIC);
449                         read_unlock(&obd_dev_lock);
450                         return i;
451                 }
452         }
453         read_unlock(&obd_dev_lock);
454
455         return -1;
456 }
457
458 struct obd_device *class_uuid2obd(struct obd_uuid *uuid)
459 {
460         int dev = class_uuid2dev(uuid);
461         if (dev < 0)
462                 return NULL;
463         return class_num2obd(dev);
464 }
465 EXPORT_SYMBOL(class_uuid2obd);
466
467 /**
468  * Get obd device from ::obd_devs[]
469  *
470  * \param num [in] array index
471  *
472  * \retval NULL if ::obd_devs[\a num] does not contains an obd device
473  *         otherwise return the obd device there.
474  */
475 struct obd_device *class_num2obd(int num)
476 {
477         struct obd_device *obd = NULL;
478
479         if (num < class_devno_max()) {
480                 obd = obd_devs[num];
481                 if (obd == NULL)
482                         return NULL;
483
484                 LASSERTF(obd->obd_magic == OBD_DEVICE_MAGIC,
485                          "%p obd_magic %08x != %08x\n",
486                          obd, obd->obd_magic, OBD_DEVICE_MAGIC);
487                 LASSERTF(obd->obd_minor == num,
488                          "%p obd_minor %0d != %0d\n",
489                          obd, obd->obd_minor, num);
490         }
491
492         return obd;
493 }
494
495 /**
496  * Get obd devices count. Device in any
497  *    state are counted
498  * \retval obd device count
499  */
500 int get_devices_count(void)
501 {
502         int index, max_index = class_devno_max(), dev_count = 0;
503
504         read_lock(&obd_dev_lock);
505         for (index = 0; index <= max_index; index++) {
506                 struct obd_device *obd = class_num2obd(index);
507                 if (obd != NULL)
508                         dev_count++;
509         }
510         read_unlock(&obd_dev_lock);
511
512         return dev_count;
513 }
514 EXPORT_SYMBOL(get_devices_count);
515
516 void class_obd_list(void)
517 {
518         char *status;
519         int i;
520
521         read_lock(&obd_dev_lock);
522         for (i = 0; i < class_devno_max(); i++) {
523                 struct obd_device *obd = class_num2obd(i);
524
525                 if (obd == NULL)
526                         continue;
527                 if (obd->obd_stopping)
528                         status = "ST";
529                 else if (obd->obd_set_up)
530                         status = "UP";
531                 else if (obd->obd_attached)
532                         status = "AT";
533                 else
534                         status = "--";
535                 LCONSOLE(D_CONFIG, "%3d %s %s %s %s %d\n",
536                          i, status, obd->obd_type->typ_name,
537                          obd->obd_name, obd->obd_uuid.uuid,
538                          atomic_read(&obd->obd_refcount));
539         }
540         read_unlock(&obd_dev_lock);
541         return;
542 }
543
544 /* Search for a client OBD connected to tgt_uuid.  If grp_uuid is
545    specified, then only the client with that uuid is returned,
546    otherwise any client connected to the tgt is returned. */
547 struct obd_device * class_find_client_obd(struct obd_uuid *tgt_uuid,
548                                           const char * typ_name,
549                                           struct obd_uuid *grp_uuid)
550 {
551         int i;
552
553         read_lock(&obd_dev_lock);
554         for (i = 0; i < class_devno_max(); i++) {
555                 struct obd_device *obd = class_num2obd(i);
556
557                 if (obd == NULL)
558                         continue;
559                 if ((strncmp(obd->obd_type->typ_name, typ_name,
560                              strlen(typ_name)) == 0)) {
561                         if (obd_uuid_equals(tgt_uuid,
562                                             &obd->u.cli.cl_target_uuid) &&
563                             ((grp_uuid)? obd_uuid_equals(grp_uuid,
564                                                          &obd->obd_uuid) : 1)) {
565                                 read_unlock(&obd_dev_lock);
566                                 return obd;
567                         }
568                 }
569         }
570         read_unlock(&obd_dev_lock);
571
572         return NULL;
573 }
574 EXPORT_SYMBOL(class_find_client_obd);
575
576 /* Iterate the obd_device list looking devices have grp_uuid. Start
577    searching at *next, and if a device is found, the next index to look
578    at is saved in *next. If next is NULL, then the first matching device
579    will always be returned. */
580 struct obd_device * class_devices_in_group(struct obd_uuid *grp_uuid, int *next)
581 {
582         int i;
583
584         if (next == NULL)
585                 i = 0;
586         else if (*next >= 0 && *next < class_devno_max())
587                 i = *next;
588         else
589                 return NULL;
590
591         read_lock(&obd_dev_lock);
592         for (; i < class_devno_max(); i++) {
593                 struct obd_device *obd = class_num2obd(i);
594
595                 if (obd == NULL)
596                         continue;
597                 if (obd_uuid_equals(grp_uuid, &obd->obd_uuid)) {
598                         if (next != NULL)
599                                 *next = i+1;
600                         read_unlock(&obd_dev_lock);
601                         return obd;
602                 }
603         }
604         read_unlock(&obd_dev_lock);
605
606         return NULL;
607 }
608 EXPORT_SYMBOL(class_devices_in_group);
609
610 /**
611  * to notify sptlrpc log for \a fsname has changed, let every relevant OBD
612  * adjust sptlrpc settings accordingly.
613  */
614 int class_notify_sptlrpc_conf(const char *fsname, int namelen)
615 {
616         struct obd_device  *obd;
617         const char         *type;
618         int                 i, rc = 0, rc2;
619
620         LASSERT(namelen > 0);
621
622         read_lock(&obd_dev_lock);
623         for (i = 0; i < class_devno_max(); i++) {
624                 obd = class_num2obd(i);
625
626                 if (obd == NULL || obd->obd_set_up == 0 || obd->obd_stopping)
627                         continue;
628
629                 /* only notify mdc, osc, osp, lwp, mdt, ost
630                  * because only these have a -sptlrpc llog */
631                 type = obd->obd_type->typ_name;
632                 if (strcmp(type, LUSTRE_MDC_NAME) != 0 &&
633                     strcmp(type, LUSTRE_OSC_NAME) != 0 &&
634                     strcmp(type, LUSTRE_OSP_NAME) != 0 &&
635                     strcmp(type, LUSTRE_LWP_NAME) != 0 &&
636                     strcmp(type, LUSTRE_MDT_NAME) != 0 &&
637                     strcmp(type, LUSTRE_OST_NAME) != 0)
638                         continue;
639
640                 if (strncmp(obd->obd_name, fsname, namelen))
641                         continue;
642
643                 class_incref(obd, __FUNCTION__, obd);
644                 read_unlock(&obd_dev_lock);
645                 rc2 = obd_set_info_async(NULL, obd->obd_self_export,
646                                          sizeof(KEY_SPTLRPC_CONF),
647                                          KEY_SPTLRPC_CONF, 0, NULL, NULL);
648                 rc = rc ? rc : rc2;
649                 class_decref(obd, __FUNCTION__, obd);
650                 read_lock(&obd_dev_lock);
651         }
652         read_unlock(&obd_dev_lock);
653         return rc;
654 }
655 EXPORT_SYMBOL(class_notify_sptlrpc_conf);
656
657 void obd_cleanup_caches(void)
658 {
659         ENTRY;
660         if (obd_device_cachep) {
661                 kmem_cache_destroy(obd_device_cachep);
662                 obd_device_cachep = NULL;
663         }
664         if (obdo_cachep) {
665                 kmem_cache_destroy(obdo_cachep);
666                 obdo_cachep = NULL;
667         }
668         if (import_cachep) {
669                 kmem_cache_destroy(import_cachep);
670                 import_cachep = NULL;
671         }
672
673         EXIT;
674 }
675
676 int obd_init_caches(void)
677 {
678         int rc;
679         ENTRY;
680
681         LASSERT(obd_device_cachep == NULL);
682         obd_device_cachep = kmem_cache_create("ll_obd_dev_cache",
683                                               sizeof(struct obd_device),
684                                               0, 0, NULL);
685         if (!obd_device_cachep)
686                 GOTO(out, rc = -ENOMEM);
687
688         LASSERT(obdo_cachep == NULL);
689         obdo_cachep = kmem_cache_create("ll_obdo_cache", sizeof(struct obdo),
690                                         0, 0, NULL);
691         if (!obdo_cachep)
692                 GOTO(out, rc = -ENOMEM);
693
694         LASSERT(import_cachep == NULL);
695         import_cachep = kmem_cache_create("ll_import_cache",
696                                           sizeof(struct obd_import),
697                                           0, 0, NULL);
698         if (!import_cachep)
699                 GOTO(out, rc = -ENOMEM);
700
701         RETURN(0);
702 out:
703         obd_cleanup_caches();
704         RETURN(rc);
705 }
706
707 /* map connection to client */
708 struct obd_export *class_conn2export(struct lustre_handle *conn)
709 {
710         struct obd_export *export;
711         ENTRY;
712
713         if (!conn) {
714                 CDEBUG(D_CACHE, "looking for null handle\n");
715                 RETURN(NULL);
716         }
717
718         if (conn->cookie == -1) {  /* this means assign a new connection */
719                 CDEBUG(D_CACHE, "want a new connection\n");
720                 RETURN(NULL);
721         }
722
723         CDEBUG(D_INFO, "looking for export cookie "LPX64"\n", conn->cookie);
724         export = class_handle2object(conn->cookie, NULL);
725         RETURN(export);
726 }
727 EXPORT_SYMBOL(class_conn2export);
728
729 struct obd_device *class_exp2obd(struct obd_export *exp)
730 {
731         if (exp)
732                 return exp->exp_obd;
733         return NULL;
734 }
735 EXPORT_SYMBOL(class_exp2obd);
736
737 struct obd_device *class_conn2obd(struct lustre_handle *conn)
738 {
739         struct obd_export *export;
740         export = class_conn2export(conn);
741         if (export) {
742                 struct obd_device *obd = export->exp_obd;
743                 class_export_put(export);
744                 return obd;
745         }
746         return NULL;
747 }
748
749 struct obd_import *class_exp2cliimp(struct obd_export *exp)
750 {
751         struct obd_device *obd = exp->exp_obd;
752         if (obd == NULL)
753                 return NULL;
754         return obd->u.cli.cl_import;
755 }
756 EXPORT_SYMBOL(class_exp2cliimp);
757
758 struct obd_import *class_conn2cliimp(struct lustre_handle *conn)
759 {
760         struct obd_device *obd = class_conn2obd(conn);
761         if (obd == NULL)
762                 return NULL;
763         return obd->u.cli.cl_import;
764 }
765
766 /* Export management functions */
767 static void class_export_destroy(struct obd_export *exp)
768 {
769         struct obd_device *obd = exp->exp_obd;
770         ENTRY;
771
772         LASSERT_ATOMIC_ZERO(&exp->exp_refcount);
773         LASSERT(obd != NULL);
774
775         CDEBUG(D_IOCTL, "destroying export %p/%s for %s\n", exp,
776                exp->exp_client_uuid.uuid, obd->obd_name);
777
778         /* "Local" exports (lctl, LOV->{mdc,osc}) have no connection. */
779         if (exp->exp_connection)
780                 ptlrpc_put_connection_superhack(exp->exp_connection);
781
782         LASSERT(list_empty(&exp->exp_outstanding_replies));
783         LASSERT(list_empty(&exp->exp_uncommitted_replies));
784         LASSERT(list_empty(&exp->exp_req_replay_queue));
785         LASSERT(list_empty(&exp->exp_hp_rpcs));
786         obd_destroy_export(exp);
787         class_decref(obd, "export", exp);
788
789         OBD_FREE_RCU(exp, sizeof(*exp), &exp->exp_handle);
790         EXIT;
791 }
792
793 static void export_handle_addref(void *export)
794 {
795         class_export_get(export);
796 }
797
798 static struct portals_handle_ops export_handle_ops = {
799         .hop_addref = export_handle_addref,
800         .hop_free   = NULL,
801 };
802
803 struct obd_export *class_export_get(struct obd_export *exp)
804 {
805         atomic_inc(&exp->exp_refcount);
806         CDEBUG(D_INFO, "GETting export %p : new refcount %d\n", exp,
807                atomic_read(&exp->exp_refcount));
808         return exp;
809 }
810 EXPORT_SYMBOL(class_export_get);
811
812 void class_export_put(struct obd_export *exp)
813 {
814         LASSERT(exp != NULL);
815         LASSERT_ATOMIC_GT_LT(&exp->exp_refcount, 0, LI_POISON);
816         CDEBUG(D_INFO, "PUTting export %p : new refcount %d\n", exp,
817                atomic_read(&exp->exp_refcount) - 1);
818
819         if (atomic_dec_and_test(&exp->exp_refcount)) {
820                 LASSERT(!list_empty(&exp->exp_obd_chain));
821                 LASSERT(list_empty(&exp->exp_stale_list));
822                 CDEBUG(D_IOCTL, "final put %p/%s\n",
823                        exp, exp->exp_client_uuid.uuid);
824
825                 /* release nid stat refererence */
826                 lprocfs_exp_cleanup(exp);
827
828                 obd_zombie_export_add(exp);
829         }
830 }
831 EXPORT_SYMBOL(class_export_put);
832
833 /* Creates a new export, adds it to the hash table, and returns a
834  * pointer to it. The refcount is 2: one for the hash reference, and
835  * one for the pointer returned by this function. */
836 struct obd_export *class_new_export(struct obd_device *obd,
837                                     struct obd_uuid *cluuid)
838 {
839         struct obd_export *export;
840         struct cfs_hash *hash = NULL;
841         int rc = 0;
842         ENTRY;
843
844         OBD_ALLOC_PTR(export);
845         if (!export)
846                 return ERR_PTR(-ENOMEM);
847
848         export->exp_conn_cnt = 0;
849         export->exp_lock_hash = NULL;
850         export->exp_flock_hash = NULL;
851         atomic_set(&export->exp_refcount, 2);
852         atomic_set(&export->exp_rpc_count, 0);
853         atomic_set(&export->exp_cb_count, 0);
854         atomic_set(&export->exp_locks_count, 0);
855 #if LUSTRE_TRACKS_LOCK_EXP_REFS
856         INIT_LIST_HEAD(&export->exp_locks_list);
857         spin_lock_init(&export->exp_locks_list_guard);
858 #endif
859         atomic_set(&export->exp_replay_count, 0);
860         export->exp_obd = obd;
861         INIT_LIST_HEAD(&export->exp_outstanding_replies);
862         spin_lock_init(&export->exp_uncommitted_replies_lock);
863         INIT_LIST_HEAD(&export->exp_uncommitted_replies);
864         INIT_LIST_HEAD(&export->exp_req_replay_queue);
865         INIT_LIST_HEAD(&export->exp_handle.h_link);
866         INIT_LIST_HEAD(&export->exp_hp_rpcs);
867         INIT_LIST_HEAD(&export->exp_reg_rpcs);
868         class_handle_hash(&export->exp_handle, &export_handle_ops);
869         export->exp_last_request_time = cfs_time_current_sec();
870         spin_lock_init(&export->exp_lock);
871         spin_lock_init(&export->exp_rpc_lock);
872         INIT_HLIST_NODE(&export->exp_uuid_hash);
873         INIT_HLIST_NODE(&export->exp_nid_hash);
874         INIT_HLIST_NODE(&export->exp_gen_hash);
875         spin_lock_init(&export->exp_bl_list_lock);
876         INIT_LIST_HEAD(&export->exp_bl_list);
877         INIT_LIST_HEAD(&export->exp_stale_list);
878
879         export->exp_sp_peer = LUSTRE_SP_ANY;
880         export->exp_flvr.sf_rpc = SPTLRPC_FLVR_INVALID;
881         export->exp_client_uuid = *cluuid;
882         obd_init_export(export);
883
884         spin_lock(&obd->obd_dev_lock);
885         /* shouldn't happen, but might race */
886         if (obd->obd_stopping)
887                 GOTO(exit_unlock, rc = -ENODEV);
888
889         hash = cfs_hash_getref(obd->obd_uuid_hash);
890         if (hash == NULL)
891                 GOTO(exit_unlock, rc = -ENODEV);
892         spin_unlock(&obd->obd_dev_lock);
893
894         if (!obd_uuid_equals(cluuid, &obd->obd_uuid)) {
895                 rc = cfs_hash_add_unique(hash, cluuid, &export->exp_uuid_hash);
896                 if (rc != 0) {
897                         LCONSOLE_WARN("%s: denying duplicate export for %s, %d\n",
898                                       obd->obd_name, cluuid->uuid, rc);
899                         GOTO(exit_err, rc = -EALREADY);
900                 }
901         }
902
903         at_init(&export->exp_bl_lock_at, obd_timeout, 0);
904         spin_lock(&obd->obd_dev_lock);
905         if (obd->obd_stopping) {
906                 cfs_hash_del(hash, cluuid, &export->exp_uuid_hash);
907                 GOTO(exit_unlock, rc = -ENODEV);
908         }
909
910         class_incref(obd, "export", export);
911         list_add(&export->exp_obd_chain, &export->exp_obd->obd_exports);
912         list_add_tail(&export->exp_obd_chain_timed,
913                       &export->exp_obd->obd_exports_timed);
914         export->exp_obd->obd_num_exports++;
915         spin_unlock(&obd->obd_dev_lock);
916         cfs_hash_putref(hash);
917         RETURN(export);
918
919 exit_unlock:
920         spin_unlock(&obd->obd_dev_lock);
921 exit_err:
922         if (hash)
923                 cfs_hash_putref(hash);
924         class_handle_unhash(&export->exp_handle);
925         LASSERT(hlist_unhashed(&export->exp_uuid_hash));
926         obd_destroy_export(export);
927         OBD_FREE_PTR(export);
928         return ERR_PTR(rc);
929 }
930 EXPORT_SYMBOL(class_new_export);
931
932 void class_unlink_export(struct obd_export *exp)
933 {
934         class_handle_unhash(&exp->exp_handle);
935
936         spin_lock(&exp->exp_obd->obd_dev_lock);
937         /* delete an uuid-export hashitem from hashtables */
938         if (!hlist_unhashed(&exp->exp_uuid_hash))
939                 cfs_hash_del(exp->exp_obd->obd_uuid_hash,
940                              &exp->exp_client_uuid,
941                              &exp->exp_uuid_hash);
942
943         if (!hlist_unhashed(&exp->exp_gen_hash)) {
944                 struct tg_export_data   *ted = &exp->exp_target_data;
945                 struct cfs_hash         *hash;
946
947                 /* Because obd_gen_hash will not be released until
948                  * class_cleanup(), so hash should never be NULL here */
949                 hash = cfs_hash_getref(exp->exp_obd->obd_gen_hash);
950                 LASSERT(hash != NULL);
951                 cfs_hash_del(hash, &ted->ted_lcd->lcd_generation,
952                              &exp->exp_gen_hash);
953                 cfs_hash_putref(hash);
954         }
955
956         list_move(&exp->exp_obd_chain, &exp->exp_obd->obd_unlinked_exports);
957         list_del_init(&exp->exp_obd_chain_timed);
958         exp->exp_obd->obd_num_exports--;
959         spin_unlock(&exp->exp_obd->obd_dev_lock);
960         atomic_inc(&obd_stale_export_num);
961
962         /* A reference is kept by obd_stale_exports list */
963         obd_stale_export_put(exp);
964 }
965 EXPORT_SYMBOL(class_unlink_export);
966
967 /* Import management functions */
968 static void class_import_destroy(struct obd_import *imp)
969 {
970         ENTRY;
971
972         CDEBUG(D_IOCTL, "destroying import %p for %s\n", imp,
973                 imp->imp_obd->obd_name);
974
975         LASSERT_ATOMIC_ZERO(&imp->imp_refcount);
976
977         ptlrpc_put_connection_superhack(imp->imp_connection);
978
979         while (!list_empty(&imp->imp_conn_list)) {
980                 struct obd_import_conn *imp_conn;
981
982                 imp_conn = list_entry(imp->imp_conn_list.next,
983                                       struct obd_import_conn, oic_item);
984                 list_del_init(&imp_conn->oic_item);
985                 ptlrpc_put_connection_superhack(imp_conn->oic_conn);
986                 OBD_FREE(imp_conn, sizeof(*imp_conn));
987         }
988
989         LASSERT(imp->imp_sec == NULL);
990         class_decref(imp->imp_obd, "import", imp);
991         OBD_FREE_RCU(imp, sizeof(*imp), &imp->imp_handle);
992         EXIT;
993 }
994
995 static void import_handle_addref(void *import)
996 {
997         class_import_get(import);
998 }
999
1000 static struct portals_handle_ops import_handle_ops = {
1001         .hop_addref = import_handle_addref,
1002         .hop_free   = NULL,
1003 };
1004
1005 struct obd_import *class_import_get(struct obd_import *import)
1006 {
1007         atomic_inc(&import->imp_refcount);
1008         CDEBUG(D_INFO, "import %p refcount=%d obd=%s\n", import,
1009                atomic_read(&import->imp_refcount),
1010                import->imp_obd->obd_name);
1011         return import;
1012 }
1013 EXPORT_SYMBOL(class_import_get);
1014
1015 void class_import_put(struct obd_import *imp)
1016 {
1017         ENTRY;
1018
1019         LASSERT(list_empty(&imp->imp_zombie_chain));
1020         LASSERT_ATOMIC_GT_LT(&imp->imp_refcount, 0, LI_POISON);
1021
1022         CDEBUG(D_INFO, "import %p refcount=%d obd=%s\n", imp,
1023                atomic_read(&imp->imp_refcount) - 1,
1024                imp->imp_obd->obd_name);
1025
1026         if (atomic_dec_and_test(&imp->imp_refcount)) {
1027                 CDEBUG(D_INFO, "final put import %p\n", imp);
1028                 obd_zombie_import_add(imp);
1029         }
1030
1031         /* catch possible import put race */
1032         LASSERT_ATOMIC_GE_LT(&imp->imp_refcount, 0, LI_POISON);
1033         EXIT;
1034 }
1035 EXPORT_SYMBOL(class_import_put);
1036
1037 static void init_imp_at(struct imp_at *at) {
1038         int i;
1039         at_init(&at->iat_net_latency, 0, 0);
1040         for (i = 0; i < IMP_AT_MAX_PORTALS; i++) {
1041                 /* max service estimates are tracked on the server side, so
1042                    don't use the AT history here, just use the last reported
1043                    val. (But keep hist for proc histogram, worst_ever) */
1044                 at_init(&at->iat_service_estimate[i], INITIAL_CONNECT_TIMEOUT,
1045                         AT_FLG_NOHIST);
1046         }
1047 }
1048
1049 struct obd_import *class_new_import(struct obd_device *obd)
1050 {
1051         struct obd_import *imp;
1052
1053         OBD_ALLOC(imp, sizeof(*imp));
1054         if (imp == NULL)
1055                 return NULL;
1056
1057         INIT_LIST_HEAD(&imp->imp_pinger_chain);
1058         INIT_LIST_HEAD(&imp->imp_zombie_chain);
1059         INIT_LIST_HEAD(&imp->imp_replay_list);
1060         INIT_LIST_HEAD(&imp->imp_sending_list);
1061         INIT_LIST_HEAD(&imp->imp_delayed_list);
1062         INIT_LIST_HEAD(&imp->imp_committed_list);
1063         INIT_LIST_HEAD(&imp->imp_unreplied_list);
1064         imp->imp_known_replied_xid = 0;
1065         imp->imp_replay_cursor = &imp->imp_committed_list;
1066         spin_lock_init(&imp->imp_lock);
1067         imp->imp_last_success_conn = 0;
1068         imp->imp_state = LUSTRE_IMP_NEW;
1069         imp->imp_obd = class_incref(obd, "import", imp);
1070         mutex_init(&imp->imp_sec_mutex);
1071         init_waitqueue_head(&imp->imp_recovery_waitq);
1072
1073         atomic_set(&imp->imp_refcount, 2);
1074         atomic_set(&imp->imp_unregistering, 0);
1075         atomic_set(&imp->imp_inflight, 0);
1076         atomic_set(&imp->imp_replay_inflight, 0);
1077         atomic_set(&imp->imp_inval_count, 0);
1078         INIT_LIST_HEAD(&imp->imp_conn_list);
1079         INIT_LIST_HEAD(&imp->imp_handle.h_link);
1080         class_handle_hash(&imp->imp_handle, &import_handle_ops);
1081         init_imp_at(&imp->imp_at);
1082
1083         /* the default magic is V2, will be used in connect RPC, and
1084          * then adjusted according to the flags in request/reply. */
1085         imp->imp_msg_magic = LUSTRE_MSG_MAGIC_V2;
1086
1087         return imp;
1088 }
1089 EXPORT_SYMBOL(class_new_import);
1090
1091 void class_destroy_import(struct obd_import *import)
1092 {
1093         LASSERT(import != NULL);
1094         LASSERT(import != LP_POISON);
1095
1096         class_handle_unhash(&import->imp_handle);
1097
1098         spin_lock(&import->imp_lock);
1099         import->imp_generation++;
1100         spin_unlock(&import->imp_lock);
1101         class_import_put(import);
1102 }
1103 EXPORT_SYMBOL(class_destroy_import);
1104
1105 #if LUSTRE_TRACKS_LOCK_EXP_REFS
1106
1107 void __class_export_add_lock_ref(struct obd_export *exp, struct ldlm_lock *lock)
1108 {
1109         spin_lock(&exp->exp_locks_list_guard);
1110
1111         LASSERT(lock->l_exp_refs_nr >= 0);
1112
1113         if (lock->l_exp_refs_target != NULL &&
1114             lock->l_exp_refs_target != exp) {
1115                 LCONSOLE_WARN("setting export %p for lock %p which already has export %p\n",
1116                               exp, lock, lock->l_exp_refs_target);
1117         }
1118         if ((lock->l_exp_refs_nr ++) == 0) {
1119                 list_add(&lock->l_exp_refs_link, &exp->exp_locks_list);
1120                 lock->l_exp_refs_target = exp;
1121         }
1122         CDEBUG(D_INFO, "lock = %p, export = %p, refs = %u\n",
1123                lock, exp, lock->l_exp_refs_nr);
1124         spin_unlock(&exp->exp_locks_list_guard);
1125 }
1126
1127 void __class_export_del_lock_ref(struct obd_export *exp, struct ldlm_lock *lock)
1128 {
1129         spin_lock(&exp->exp_locks_list_guard);
1130         LASSERT(lock->l_exp_refs_nr > 0);
1131         if (lock->l_exp_refs_target != exp) {
1132                 LCONSOLE_WARN("lock %p, "
1133                               "mismatching export pointers: %p, %p\n",
1134                               lock, lock->l_exp_refs_target, exp);
1135         }
1136         if (-- lock->l_exp_refs_nr == 0) {
1137                 list_del_init(&lock->l_exp_refs_link);
1138                 lock->l_exp_refs_target = NULL;
1139         }
1140         CDEBUG(D_INFO, "lock = %p, export = %p, refs = %u\n",
1141                lock, exp, lock->l_exp_refs_nr);
1142         spin_unlock(&exp->exp_locks_list_guard);
1143 }
1144 #endif
1145
1146 /* A connection defines an export context in which preallocation can
1147    be managed. This releases the export pointer reference, and returns
1148    the export handle, so the export refcount is 1 when this function
1149    returns. */
1150 int class_connect(struct lustre_handle *conn, struct obd_device *obd,
1151                   struct obd_uuid *cluuid)
1152 {
1153         struct obd_export *export;
1154         LASSERT(conn != NULL);
1155         LASSERT(obd != NULL);
1156         LASSERT(cluuid != NULL);
1157         ENTRY;
1158
1159         export = class_new_export(obd, cluuid);
1160         if (IS_ERR(export))
1161                 RETURN(PTR_ERR(export));
1162
1163         conn->cookie = export->exp_handle.h_cookie;
1164         class_export_put(export);
1165
1166         CDEBUG(D_IOCTL, "connect: client %s, cookie "LPX64"\n",
1167                cluuid->uuid, conn->cookie);
1168         RETURN(0);
1169 }
1170 EXPORT_SYMBOL(class_connect);
1171
1172 /* if export is involved in recovery then clean up related things */
1173 static void class_export_recovery_cleanup(struct obd_export *exp)
1174 {
1175         struct obd_device *obd = exp->exp_obd;
1176
1177         spin_lock(&obd->obd_recovery_task_lock);
1178         if (obd->obd_recovering) {
1179                 if (exp->exp_in_recovery) {
1180                         spin_lock(&exp->exp_lock);
1181                         exp->exp_in_recovery = 0;
1182                         spin_unlock(&exp->exp_lock);
1183                         LASSERT_ATOMIC_POS(&obd->obd_connected_clients);
1184                         atomic_dec(&obd->obd_connected_clients);
1185                 }
1186
1187                 /* if called during recovery then should update
1188                  * obd_stale_clients counter,
1189                  * lightweight exports are not counted */
1190                 if ((exp_connect_flags(exp) & OBD_CONNECT_LIGHTWEIGHT) == 0)
1191                         exp->exp_obd->obd_stale_clients++;
1192         }
1193         spin_unlock(&obd->obd_recovery_task_lock);
1194
1195         spin_lock(&exp->exp_lock);
1196         /** Cleanup req replay fields */
1197         if (exp->exp_req_replay_needed) {
1198                 exp->exp_req_replay_needed = 0;
1199
1200                 LASSERT(atomic_read(&obd->obd_req_replay_clients));
1201                 atomic_dec(&obd->obd_req_replay_clients);
1202         }
1203
1204         /** Cleanup lock replay data */
1205         if (exp->exp_lock_replay_needed) {
1206                 exp->exp_lock_replay_needed = 0;
1207
1208                 LASSERT(atomic_read(&obd->obd_lock_replay_clients));
1209                 atomic_dec(&obd->obd_lock_replay_clients);
1210         }
1211         spin_unlock(&exp->exp_lock);
1212 }
1213
1214 /* This function removes 1-3 references from the export:
1215  * 1 - for export pointer passed
1216  * and if disconnect really need
1217  * 2 - removing from hash
1218  * 3 - in client_unlink_export
1219  * The export pointer passed to this function can destroyed */
1220 int class_disconnect(struct obd_export *export)
1221 {
1222         int already_disconnected;
1223         ENTRY;
1224
1225         if (export == NULL) {
1226                 CWARN("attempting to free NULL export %p\n", export);
1227                 RETURN(-EINVAL);
1228         }
1229
1230         spin_lock(&export->exp_lock);
1231         already_disconnected = export->exp_disconnected;
1232         export->exp_disconnected = 1;
1233         spin_unlock(&export->exp_lock);
1234
1235         /* class_cleanup(), abort_recovery(), and class_fail_export()
1236          * all end up in here, and if any of them race we shouldn't
1237          * call extra class_export_puts(). */
1238         if (already_disconnected) {
1239                 LASSERT(hlist_unhashed(&export->exp_nid_hash));
1240                 GOTO(no_disconn, already_disconnected);
1241         }
1242
1243         CDEBUG(D_IOCTL, "disconnect: cookie "LPX64"\n",
1244                export->exp_handle.h_cookie);
1245
1246         if (!hlist_unhashed(&export->exp_nid_hash))
1247                 cfs_hash_del(export->exp_obd->obd_nid_hash,
1248                              &export->exp_connection->c_peer.nid,
1249                              &export->exp_nid_hash);
1250
1251         class_export_recovery_cleanup(export);
1252         class_unlink_export(export);
1253 no_disconn:
1254         class_export_put(export);
1255         RETURN(0);
1256 }
1257 EXPORT_SYMBOL(class_disconnect);
1258
1259 /* Return non-zero for a fully connected export */
1260 int class_connected_export(struct obd_export *exp)
1261 {
1262         int connected = 0;
1263
1264         if (exp) {
1265                 spin_lock(&exp->exp_lock);
1266                 connected = (exp->exp_conn_cnt > 0) && !exp->exp_failed;
1267                 spin_unlock(&exp->exp_lock);
1268         }
1269         return connected;
1270 }
1271 EXPORT_SYMBOL(class_connected_export);
1272
1273 static void class_disconnect_export_list(struct list_head *list,
1274                                          enum obd_option flags)
1275 {
1276         int rc;
1277         struct obd_export *exp;
1278         ENTRY;
1279
1280         /* It's possible that an export may disconnect itself, but
1281          * nothing else will be added to this list. */
1282         while (!list_empty(list)) {
1283                 exp = list_entry(list->next, struct obd_export,
1284                                  exp_obd_chain);
1285                 /* need for safe call CDEBUG after obd_disconnect */
1286                 class_export_get(exp);
1287
1288                 spin_lock(&exp->exp_lock);
1289                 exp->exp_flags = flags;
1290                 spin_unlock(&exp->exp_lock);
1291
1292                 if (obd_uuid_equals(&exp->exp_client_uuid,
1293                                     &exp->exp_obd->obd_uuid)) {
1294                         CDEBUG(D_HA,
1295                                "exp %p export uuid == obd uuid, don't discon\n",
1296                                exp);
1297                         /* Need to delete this now so we don't end up pointing
1298                          * to work_list later when this export is cleaned up. */
1299                         list_del_init(&exp->exp_obd_chain);
1300                         class_export_put(exp);
1301                         continue;
1302                 }
1303
1304                 class_export_get(exp);
1305                 CDEBUG(D_HA, "%s: disconnecting export at %s (%p), "
1306                        "last request at "CFS_TIME_T"\n",
1307                        exp->exp_obd->obd_name, obd_export_nid2str(exp),
1308                        exp, exp->exp_last_request_time);
1309                 /* release one export reference anyway */
1310                 rc = obd_disconnect(exp);
1311
1312                 CDEBUG(D_HA, "disconnected export at %s (%p): rc %d\n",
1313                        obd_export_nid2str(exp), exp, rc);
1314                 class_export_put(exp);
1315         }
1316         EXIT;
1317 }
1318
1319 void class_disconnect_exports(struct obd_device *obd)
1320 {
1321         struct list_head work_list;
1322         ENTRY;
1323
1324         /* Move all of the exports from obd_exports to a work list, en masse. */
1325         INIT_LIST_HEAD(&work_list);
1326         spin_lock(&obd->obd_dev_lock);
1327         list_splice_init(&obd->obd_exports, &work_list);
1328         list_splice_init(&obd->obd_delayed_exports, &work_list);
1329         spin_unlock(&obd->obd_dev_lock);
1330
1331         if (!list_empty(&work_list)) {
1332                 CDEBUG(D_HA, "OBD device %d (%p) has exports, "
1333                        "disconnecting them\n", obd->obd_minor, obd);
1334                 class_disconnect_export_list(&work_list,
1335                                              exp_flags_from_obd(obd));
1336         } else
1337                 CDEBUG(D_HA, "OBD device %d (%p) has no exports\n",
1338                        obd->obd_minor, obd);
1339         EXIT;
1340 }
1341 EXPORT_SYMBOL(class_disconnect_exports);
1342
1343 /* Remove exports that have not completed recovery.
1344  */
1345 void class_disconnect_stale_exports(struct obd_device *obd,
1346                                     int (*test_export)(struct obd_export *))
1347 {
1348         struct list_head work_list;
1349         struct obd_export *exp, *n;
1350         int evicted = 0;
1351         ENTRY;
1352
1353         INIT_LIST_HEAD(&work_list);
1354         spin_lock(&obd->obd_dev_lock);
1355         list_for_each_entry_safe(exp, n, &obd->obd_exports,
1356                                  exp_obd_chain) {
1357                 /* don't count self-export as client */
1358                 if (obd_uuid_equals(&exp->exp_client_uuid,
1359                                     &exp->exp_obd->obd_uuid))
1360                         continue;
1361
1362                 /* don't evict clients which have no slot in last_rcvd
1363                  * (e.g. lightweight connection) */
1364                 if (exp->exp_target_data.ted_lr_idx == -1)
1365                         continue;
1366
1367                 spin_lock(&exp->exp_lock);
1368                 if (exp->exp_failed || test_export(exp)) {
1369                         spin_unlock(&exp->exp_lock);
1370                         continue;
1371                 }
1372                 exp->exp_failed = 1;
1373                 spin_unlock(&exp->exp_lock);
1374
1375                 list_move(&exp->exp_obd_chain, &work_list);
1376                 evicted++;
1377                 CDEBUG(D_HA, "%s: disconnect stale client %s@%s\n",
1378                        obd->obd_name, exp->exp_client_uuid.uuid,
1379                        exp->exp_connection == NULL ? "<unknown>" :
1380                        libcfs_nid2str(exp->exp_connection->c_peer.nid));
1381                 print_export_data(exp, "EVICTING", 0);
1382         }
1383         spin_unlock(&obd->obd_dev_lock);
1384
1385         if (evicted)
1386                 LCONSOLE_WARN("%s: disconnecting %d stale clients\n",
1387                               obd->obd_name, evicted);
1388
1389         class_disconnect_export_list(&work_list, exp_flags_from_obd(obd) |
1390                                                  OBD_OPT_ABORT_RECOV);
1391         EXIT;
1392 }
1393 EXPORT_SYMBOL(class_disconnect_stale_exports);
1394
1395 void class_fail_export(struct obd_export *exp)
1396 {
1397         int rc, already_failed;
1398
1399         spin_lock(&exp->exp_lock);
1400         already_failed = exp->exp_failed;
1401         exp->exp_failed = 1;
1402         spin_unlock(&exp->exp_lock);
1403
1404         if (already_failed) {
1405                 CDEBUG(D_HA, "disconnecting dead export %p/%s; skipping\n",
1406                        exp, exp->exp_client_uuid.uuid);
1407                 return;
1408         }
1409
1410         CDEBUG(D_HA, "disconnecting export %p/%s\n",
1411                exp, exp->exp_client_uuid.uuid);
1412
1413         if (obd_dump_on_timeout)
1414                 libcfs_debug_dumplog();
1415
1416         /* need for safe call CDEBUG after obd_disconnect */
1417         class_export_get(exp);
1418
1419         /* Most callers into obd_disconnect are removing their own reference
1420          * (request, for example) in addition to the one from the hash table.
1421          * We don't have such a reference here, so make one. */
1422         class_export_get(exp);
1423         rc = obd_disconnect(exp);
1424         if (rc)
1425                 CERROR("disconnecting export %p failed: %d\n", exp, rc);
1426         else
1427                 CDEBUG(D_HA, "disconnected export %p/%s\n",
1428                        exp, exp->exp_client_uuid.uuid);
1429         class_export_put(exp);
1430 }
1431 EXPORT_SYMBOL(class_fail_export);
1432
1433 char *obd_export_nid2str(struct obd_export *exp)
1434 {
1435         if (exp->exp_connection != NULL)
1436                 return libcfs_nid2str(exp->exp_connection->c_peer.nid);
1437
1438         return "(no nid)";
1439 }
1440 EXPORT_SYMBOL(obd_export_nid2str);
1441
1442 int obd_export_evict_by_nid(struct obd_device *obd, const char *nid)
1443 {
1444         struct cfs_hash *nid_hash;
1445         struct obd_export *doomed_exp = NULL;
1446         int exports_evicted = 0;
1447
1448         lnet_nid_t nid_key = libcfs_str2nid((char *)nid);
1449
1450         spin_lock(&obd->obd_dev_lock);
1451         /* umount has run already, so evict thread should leave
1452          * its task to umount thread now */
1453         if (obd->obd_stopping) {
1454                 spin_unlock(&obd->obd_dev_lock);
1455                 return exports_evicted;
1456         }
1457         nid_hash = obd->obd_nid_hash;
1458         cfs_hash_getref(nid_hash);
1459         spin_unlock(&obd->obd_dev_lock);
1460
1461         do {
1462                 doomed_exp = cfs_hash_lookup(nid_hash, &nid_key);
1463                 if (doomed_exp == NULL)
1464                         break;
1465
1466                 LASSERTF(doomed_exp->exp_connection->c_peer.nid == nid_key,
1467                          "nid %s found, wanted nid %s, requested nid %s\n",
1468                          obd_export_nid2str(doomed_exp),
1469                          libcfs_nid2str(nid_key), nid);
1470                 LASSERTF(doomed_exp != obd->obd_self_export,
1471                          "self-export is hashed by NID?\n");
1472                 exports_evicted++;
1473                 LCONSOLE_WARN("%s: evicting %s (at %s) by administrative "
1474                               "request\n", obd->obd_name,
1475                               obd_uuid2str(&doomed_exp->exp_client_uuid),
1476                               obd_export_nid2str(doomed_exp));
1477                 class_fail_export(doomed_exp);
1478                 class_export_put(doomed_exp);
1479         } while (1);
1480
1481         cfs_hash_putref(nid_hash);
1482
1483         if (!exports_evicted)
1484                 CDEBUG(D_HA,"%s: can't disconnect NID '%s': no exports found\n",
1485                        obd->obd_name, nid);
1486         return exports_evicted;
1487 }
1488 EXPORT_SYMBOL(obd_export_evict_by_nid);
1489
1490 int obd_export_evict_by_uuid(struct obd_device *obd, const char *uuid)
1491 {
1492         struct cfs_hash *uuid_hash;
1493         struct obd_export *doomed_exp = NULL;
1494         struct obd_uuid doomed_uuid;
1495         int exports_evicted = 0;
1496
1497         spin_lock(&obd->obd_dev_lock);
1498         if (obd->obd_stopping) {
1499                 spin_unlock(&obd->obd_dev_lock);
1500                 return exports_evicted;
1501         }
1502         uuid_hash = obd->obd_uuid_hash;
1503         cfs_hash_getref(uuid_hash);
1504         spin_unlock(&obd->obd_dev_lock);
1505
1506         obd_str2uuid(&doomed_uuid, uuid);
1507         if (obd_uuid_equals(&doomed_uuid, &obd->obd_uuid)) {
1508                 CERROR("%s: can't evict myself\n", obd->obd_name);
1509                 cfs_hash_putref(uuid_hash);
1510                 return exports_evicted;
1511         }
1512
1513         doomed_exp = cfs_hash_lookup(uuid_hash, &doomed_uuid);
1514
1515         if (doomed_exp == NULL) {
1516                 CERROR("%s: can't disconnect %s: no exports found\n",
1517                        obd->obd_name, uuid);
1518         } else {
1519                 CWARN("%s: evicting %s at adminstrative request\n",
1520                        obd->obd_name, doomed_exp->exp_client_uuid.uuid);
1521                 class_fail_export(doomed_exp);
1522                 class_export_put(doomed_exp);
1523                 exports_evicted++;
1524         }
1525         cfs_hash_putref(uuid_hash);
1526
1527         return exports_evicted;
1528 }
1529
1530 #if LUSTRE_TRACKS_LOCK_EXP_REFS
1531 void (*class_export_dump_hook)(struct obd_export*) = NULL;
1532 #endif
1533
1534 static void print_export_data(struct obd_export *exp, const char *status,
1535                               int locks)
1536 {
1537         struct ptlrpc_reply_state *rs;
1538         struct ptlrpc_reply_state *first_reply = NULL;
1539         int nreplies = 0;
1540
1541         spin_lock(&exp->exp_lock);
1542         list_for_each_entry(rs, &exp->exp_outstanding_replies,
1543                             rs_exp_list) {
1544                 if (nreplies == 0)
1545                         first_reply = rs;
1546                 nreplies++;
1547         }
1548         spin_unlock(&exp->exp_lock);
1549
1550         CDEBUG(D_HA, "%s: %s %p %s %s %d (%d %d %d) %d %d %d %d: %p %s "LPU64"\n",
1551                exp->exp_obd->obd_name, status, exp, exp->exp_client_uuid.uuid,
1552                obd_export_nid2str(exp), atomic_read(&exp->exp_refcount),
1553                atomic_read(&exp->exp_rpc_count),
1554                atomic_read(&exp->exp_cb_count),
1555                atomic_read(&exp->exp_locks_count),
1556                exp->exp_disconnected, exp->exp_delayed, exp->exp_failed,
1557                nreplies, first_reply, nreplies > 3 ? "..." : "",
1558                exp->exp_last_committed);
1559 #if LUSTRE_TRACKS_LOCK_EXP_REFS
1560         if (locks && class_export_dump_hook != NULL)
1561                 class_export_dump_hook(exp);
1562 #endif
1563 }
1564
1565 void dump_exports(struct obd_device *obd, int locks)
1566 {
1567         struct obd_export *exp;
1568
1569         spin_lock(&obd->obd_dev_lock);
1570         list_for_each_entry(exp, &obd->obd_exports, exp_obd_chain)
1571                 print_export_data(exp, "ACTIVE", locks);
1572         list_for_each_entry(exp, &obd->obd_unlinked_exports, exp_obd_chain)
1573                 print_export_data(exp, "UNLINKED", locks);
1574         list_for_each_entry(exp, &obd->obd_delayed_exports, exp_obd_chain)
1575                 print_export_data(exp, "DELAYED", locks);
1576         spin_unlock(&obd->obd_dev_lock);
1577         spin_lock(&obd_zombie_impexp_lock);
1578         list_for_each_entry(exp, &obd_zombie_exports, exp_obd_chain)
1579                 print_export_data(exp, "ZOMBIE", locks);
1580         spin_unlock(&obd_zombie_impexp_lock);
1581 }
1582
1583 void obd_exports_barrier(struct obd_device *obd)
1584 {
1585         int waited = 2;
1586         LASSERT(list_empty(&obd->obd_exports));
1587         spin_lock(&obd->obd_dev_lock);
1588         while (!list_empty(&obd->obd_unlinked_exports)) {
1589                 spin_unlock(&obd->obd_dev_lock);
1590                 set_current_state(TASK_UNINTERRUPTIBLE);
1591                 schedule_timeout(cfs_time_seconds(waited));
1592                 if (waited > 5 && IS_PO2(waited)) {
1593                         LCONSOLE_WARN("%s is waiting for obd_unlinked_exports "
1594                                       "more than %d seconds. "
1595                                       "The obd refcount = %d. Is it stuck?\n",
1596                                       obd->obd_name, waited,
1597                                       atomic_read(&obd->obd_refcount));
1598                         dump_exports(obd, 1);
1599                 }
1600                 waited *= 2;
1601                 spin_lock(&obd->obd_dev_lock);
1602         }
1603         spin_unlock(&obd->obd_dev_lock);
1604 }
1605 EXPORT_SYMBOL(obd_exports_barrier);
1606
1607 /* Total amount of zombies to be destroyed */
1608 static int zombies_count = 0;
1609
1610 /**
1611  * kill zombie imports and exports
1612  */
1613 void obd_zombie_impexp_cull(void)
1614 {
1615         struct obd_import *import;
1616         struct obd_export *export;
1617         ENTRY;
1618
1619         do {
1620                 spin_lock(&obd_zombie_impexp_lock);
1621
1622                 import = NULL;
1623                 if (!list_empty(&obd_zombie_imports)) {
1624                         import = list_entry(obd_zombie_imports.next,
1625                                             struct obd_import,
1626                                             imp_zombie_chain);
1627                         list_del_init(&import->imp_zombie_chain);
1628                 }
1629
1630                 export = NULL;
1631                 if (!list_empty(&obd_zombie_exports)) {
1632                         export = list_entry(obd_zombie_exports.next,
1633                                             struct obd_export,
1634                                             exp_obd_chain);
1635                         list_del_init(&export->exp_obd_chain);
1636                 }
1637
1638                 spin_unlock(&obd_zombie_impexp_lock);
1639
1640                 if (import != NULL) {
1641                         class_import_destroy(import);
1642                         spin_lock(&obd_zombie_impexp_lock);
1643                         zombies_count--;
1644                         spin_unlock(&obd_zombie_impexp_lock);
1645                 }
1646
1647                 if (export != NULL) {
1648                         class_export_destroy(export);
1649                         spin_lock(&obd_zombie_impexp_lock);
1650                         zombies_count--;
1651                         spin_unlock(&obd_zombie_impexp_lock);
1652                 }
1653
1654                 cond_resched();
1655         } while (import != NULL || export != NULL);
1656         EXIT;
1657 }
1658
1659 static struct completion        obd_zombie_start;
1660 static struct completion        obd_zombie_stop;
1661 static unsigned long            obd_zombie_flags;
1662 static wait_queue_head_t        obd_zombie_waitq;
1663 static pid_t                    obd_zombie_pid;
1664
1665 enum {
1666         OBD_ZOMBIE_STOP         = 0x0001,
1667 };
1668
1669 /**
1670  * check for work for kill zombie import/export thread.
1671  */
1672 static int obd_zombie_impexp_check(void *arg)
1673 {
1674         int rc;
1675
1676         spin_lock(&obd_zombie_impexp_lock);
1677         rc = (zombies_count == 0) &&
1678              !test_bit(OBD_ZOMBIE_STOP, &obd_zombie_flags);
1679         spin_unlock(&obd_zombie_impexp_lock);
1680
1681         RETURN(rc);
1682 }
1683
1684 /**
1685  * Add export to the obd_zombe thread and notify it.
1686  */
1687 static void obd_zombie_export_add(struct obd_export *exp) {
1688         atomic_dec(&obd_stale_export_num);
1689         spin_lock(&exp->exp_obd->obd_dev_lock);
1690         LASSERT(!list_empty(&exp->exp_obd_chain));
1691         list_del_init(&exp->exp_obd_chain);
1692         spin_unlock(&exp->exp_obd->obd_dev_lock);
1693         spin_lock(&obd_zombie_impexp_lock);
1694         zombies_count++;
1695         list_add(&exp->exp_obd_chain, &obd_zombie_exports);
1696         spin_unlock(&obd_zombie_impexp_lock);
1697
1698         obd_zombie_impexp_notify();
1699 }
1700
1701 /**
1702  * Add import to the obd_zombe thread and notify it.
1703  */
1704 static void obd_zombie_import_add(struct obd_import *imp) {
1705         LASSERT(imp->imp_sec == NULL);
1706         spin_lock(&obd_zombie_impexp_lock);
1707         LASSERT(list_empty(&imp->imp_zombie_chain));
1708         zombies_count++;
1709         list_add(&imp->imp_zombie_chain, &obd_zombie_imports);
1710         spin_unlock(&obd_zombie_impexp_lock);
1711
1712         obd_zombie_impexp_notify();
1713 }
1714
1715 /**
1716  * notify import/export destroy thread about new zombie.
1717  */
1718 static void obd_zombie_impexp_notify(void)
1719 {
1720         /*
1721          * Make sure obd_zomebie_impexp_thread get this notification.
1722          * It is possible this signal only get by obd_zombie_barrier, and
1723          * barrier gulps this notification and sleeps away and hangs ensues
1724          */
1725         wake_up_all(&obd_zombie_waitq);
1726 }
1727
1728 /**
1729  * check whether obd_zombie is idle
1730  */
1731 static int obd_zombie_is_idle(void)
1732 {
1733         int rc;
1734
1735         LASSERT(!test_bit(OBD_ZOMBIE_STOP, &obd_zombie_flags));
1736         spin_lock(&obd_zombie_impexp_lock);
1737         rc = (zombies_count == 0);
1738         spin_unlock(&obd_zombie_impexp_lock);
1739         return rc;
1740 }
1741
1742 /**
1743  * wait when obd_zombie import/export queues become empty
1744  */
1745 void obd_zombie_barrier(void)
1746 {
1747         struct l_wait_info lwi = { 0 };
1748
1749         if (obd_zombie_pid == current_pid())
1750                 /* don't wait for myself */
1751                 return;
1752         l_wait_event(obd_zombie_waitq, obd_zombie_is_idle(), &lwi);
1753 }
1754 EXPORT_SYMBOL(obd_zombie_barrier);
1755
1756
1757 struct obd_export *obd_stale_export_get(void)
1758 {
1759         struct obd_export *exp = NULL;
1760         ENTRY;
1761
1762         spin_lock(&obd_stale_export_lock);
1763         if (!list_empty(&obd_stale_exports)) {
1764                 exp = list_entry(obd_stale_exports.next,
1765                                  struct obd_export, exp_stale_list);
1766                 list_del_init(&exp->exp_stale_list);
1767         }
1768         spin_unlock(&obd_stale_export_lock);
1769
1770         if (exp) {
1771                 CDEBUG(D_DLMTRACE, "Get export %p: total %d\n", exp,
1772                        atomic_read(&obd_stale_export_num));
1773         }
1774         RETURN(exp);
1775 }
1776 EXPORT_SYMBOL(obd_stale_export_get);
1777
1778 void obd_stale_export_put(struct obd_export *exp)
1779 {
1780         ENTRY;
1781
1782         LASSERT(list_empty(&exp->exp_stale_list));
1783         if (exp->exp_lock_hash &&
1784             atomic_read(&exp->exp_lock_hash->hs_count)) {
1785                 CDEBUG(D_DLMTRACE, "Put export %p: total %d\n", exp,
1786                        atomic_read(&obd_stale_export_num));
1787
1788                 spin_lock_bh(&exp->exp_bl_list_lock);
1789                 spin_lock(&obd_stale_export_lock);
1790                 /* Add to the tail if there is no blocked locks,
1791                  * to the head otherwise. */
1792                 if (list_empty(&exp->exp_bl_list))
1793                         list_add_tail(&exp->exp_stale_list,
1794                                       &obd_stale_exports);
1795                 else
1796                         list_add(&exp->exp_stale_list,
1797                                  &obd_stale_exports);
1798
1799                 spin_unlock(&obd_stale_export_lock);
1800                 spin_unlock_bh(&exp->exp_bl_list_lock);
1801         } else {
1802                 class_export_put(exp);
1803         }
1804         EXIT;
1805 }
1806 EXPORT_SYMBOL(obd_stale_export_put);
1807
1808 /**
1809  * Adjust the position of the export in the stale list,
1810  * i.e. move to the head of the list if is needed.
1811  **/
1812 void obd_stale_export_adjust(struct obd_export *exp)
1813 {
1814         LASSERT(exp != NULL);
1815         spin_lock_bh(&exp->exp_bl_list_lock);
1816         spin_lock(&obd_stale_export_lock);
1817
1818         if (!list_empty(&exp->exp_stale_list) &&
1819             !list_empty(&exp->exp_bl_list))
1820                 list_move(&exp->exp_stale_list, &obd_stale_exports);
1821
1822         spin_unlock(&obd_stale_export_lock);
1823         spin_unlock_bh(&exp->exp_bl_list_lock);
1824 }
1825 EXPORT_SYMBOL(obd_stale_export_adjust);
1826
1827 /**
1828  * destroy zombie export/import thread.
1829  */
1830 static int obd_zombie_impexp_thread(void *unused)
1831 {
1832         unshare_fs_struct();
1833         complete(&obd_zombie_start);
1834
1835         obd_zombie_pid = current_pid();
1836
1837         while (!test_bit(OBD_ZOMBIE_STOP, &obd_zombie_flags)) {
1838                 struct l_wait_info lwi = { 0 };
1839
1840                 l_wait_event(obd_zombie_waitq,
1841                              !obd_zombie_impexp_check(NULL), &lwi);
1842                 obd_zombie_impexp_cull();
1843
1844                 /*
1845                  * Notify obd_zombie_barrier callers that queues
1846                  * may be empty.
1847                  */
1848                 wake_up(&obd_zombie_waitq);
1849         }
1850
1851         complete(&obd_zombie_stop);
1852
1853         RETURN(0);
1854 }
1855
1856
1857 /**
1858  * start destroy zombie import/export thread
1859  */
1860 int obd_zombie_impexp_init(void)
1861 {
1862         struct task_struct *task;
1863
1864         INIT_LIST_HEAD(&obd_zombie_imports);
1865
1866         INIT_LIST_HEAD(&obd_zombie_exports);
1867         spin_lock_init(&obd_zombie_impexp_lock);
1868         init_completion(&obd_zombie_start);
1869         init_completion(&obd_zombie_stop);
1870         init_waitqueue_head(&obd_zombie_waitq);
1871         obd_zombie_pid = 0;
1872
1873         task = kthread_run(obd_zombie_impexp_thread, NULL, "obd_zombid");
1874         if (IS_ERR(task))
1875                 RETURN(PTR_ERR(task));
1876
1877         wait_for_completion(&obd_zombie_start);
1878         RETURN(0);
1879 }
1880 /**
1881  * stop destroy zombie import/export thread
1882  */
1883 void obd_zombie_impexp_stop(void)
1884 {
1885         set_bit(OBD_ZOMBIE_STOP, &obd_zombie_flags);
1886         obd_zombie_impexp_notify();
1887         wait_for_completion(&obd_zombie_stop);
1888 }
1889
1890 /***** Kernel-userspace comm helpers *******/
1891
1892 /* Get length of entire message, including header */
1893 int kuc_len(int payload_len)
1894 {
1895         return sizeof(struct kuc_hdr) + payload_len;
1896 }
1897 EXPORT_SYMBOL(kuc_len);
1898
1899 /* Get a pointer to kuc header, given a ptr to the payload
1900  * @param p Pointer to payload area
1901  * @returns Pointer to kuc header
1902  */
1903 struct kuc_hdr * kuc_ptr(void *p)
1904 {
1905         struct kuc_hdr *lh = ((struct kuc_hdr *)p) - 1;
1906         LASSERT(lh->kuc_magic == KUC_MAGIC);
1907         return lh;
1908 }
1909 EXPORT_SYMBOL(kuc_ptr);
1910
1911 /* Test if payload is part of kuc message
1912  * @param p Pointer to payload area
1913  * @returns boolean
1914  */
1915 int kuc_ispayload(void *p)
1916 {
1917         struct kuc_hdr *kh = ((struct kuc_hdr *)p) - 1;
1918
1919         if (kh->kuc_magic == KUC_MAGIC)
1920                 return 1;
1921         else
1922                 return 0;
1923 }
1924 EXPORT_SYMBOL(kuc_ispayload);
1925
1926 /* Alloc space for a message, and fill in header
1927  * @return Pointer to payload area
1928  */
1929 void *kuc_alloc(int payload_len, int transport, int type)
1930 {
1931         struct kuc_hdr *lh;
1932         int len = kuc_len(payload_len);
1933
1934         OBD_ALLOC(lh, len);
1935         if (lh == NULL)
1936                 return ERR_PTR(-ENOMEM);
1937
1938         lh->kuc_magic = KUC_MAGIC;
1939         lh->kuc_transport = transport;
1940         lh->kuc_msgtype = type;
1941         lh->kuc_msglen = len;
1942
1943         return (void *)(lh + 1);
1944 }
1945 EXPORT_SYMBOL(kuc_alloc);
1946
1947 /* Takes pointer to payload area */
1948 inline void kuc_free(void *p, int payload_len)
1949 {
1950         struct kuc_hdr *lh = kuc_ptr(p);
1951         OBD_FREE(lh, kuc_len(payload_len));
1952 }
1953 EXPORT_SYMBOL(kuc_free);
1954
1955 struct obd_request_slot_waiter {
1956         struct list_head        orsw_entry;
1957         wait_queue_head_t       orsw_waitq;
1958         bool                    orsw_signaled;
1959 };
1960
1961 static bool obd_request_slot_avail(struct client_obd *cli,
1962                                    struct obd_request_slot_waiter *orsw)
1963 {
1964         bool avail;
1965
1966         spin_lock(&cli->cl_loi_list_lock);
1967         avail = !!list_empty(&orsw->orsw_entry);
1968         spin_unlock(&cli->cl_loi_list_lock);
1969
1970         return avail;
1971 };
1972
1973 /*
1974  * For network flow control, the RPC sponsor needs to acquire a credit
1975  * before sending the RPC. The credits count for a connection is defined
1976  * by the "cl_max_rpcs_in_flight". If all the credits are occpuied, then
1977  * the subsequent RPC sponsors need to wait until others released their
1978  * credits, or the administrator increased the "cl_max_rpcs_in_flight".
1979  */
1980 int obd_get_request_slot(struct client_obd *cli)
1981 {
1982         struct obd_request_slot_waiter   orsw;
1983         struct l_wait_info               lwi;
1984         int                              rc;
1985
1986         spin_lock(&cli->cl_loi_list_lock);
1987         if (cli->cl_r_in_flight < cli->cl_max_rpcs_in_flight) {
1988                 cli->cl_r_in_flight++;
1989                 spin_unlock(&cli->cl_loi_list_lock);
1990                 return 0;
1991         }
1992
1993         init_waitqueue_head(&orsw.orsw_waitq);
1994         list_add_tail(&orsw.orsw_entry, &cli->cl_loi_read_list);
1995         orsw.orsw_signaled = false;
1996         spin_unlock(&cli->cl_loi_list_lock);
1997
1998         lwi = LWI_INTR(LWI_ON_SIGNAL_NOOP, NULL);
1999         rc = l_wait_event(orsw.orsw_waitq,
2000                           obd_request_slot_avail(cli, &orsw) ||
2001                           orsw.orsw_signaled,
2002                           &lwi);
2003
2004         /* Here, we must take the lock to avoid the on-stack 'orsw' to be
2005          * freed but other (such as obd_put_request_slot) is using it. */
2006         spin_lock(&cli->cl_loi_list_lock);
2007         if (rc != 0) {
2008                 if (!orsw.orsw_signaled) {
2009                         if (list_empty(&orsw.orsw_entry))
2010                                 cli->cl_r_in_flight--;
2011                         else
2012                                 list_del(&orsw.orsw_entry);
2013                 }
2014         }
2015
2016         if (orsw.orsw_signaled) {
2017                 LASSERT(list_empty(&orsw.orsw_entry));
2018
2019                 rc = -EINTR;
2020         }
2021         spin_unlock(&cli->cl_loi_list_lock);
2022
2023         return rc;
2024 }
2025 EXPORT_SYMBOL(obd_get_request_slot);
2026
2027 void obd_put_request_slot(struct client_obd *cli)
2028 {
2029         struct obd_request_slot_waiter *orsw;
2030
2031         spin_lock(&cli->cl_loi_list_lock);
2032         cli->cl_r_in_flight--;
2033
2034         /* If there is free slot, wakeup the first waiter. */
2035         if (!list_empty(&cli->cl_loi_read_list) &&
2036             likely(cli->cl_r_in_flight < cli->cl_max_rpcs_in_flight)) {
2037                 orsw = list_entry(cli->cl_loi_read_list.next,
2038                                   struct obd_request_slot_waiter, orsw_entry);
2039                 list_del_init(&orsw->orsw_entry);
2040                 cli->cl_r_in_flight++;
2041                 wake_up(&orsw->orsw_waitq);
2042         }
2043         spin_unlock(&cli->cl_loi_list_lock);
2044 }
2045 EXPORT_SYMBOL(obd_put_request_slot);
2046
2047 __u32 obd_get_max_rpcs_in_flight(struct client_obd *cli)
2048 {
2049         return cli->cl_max_rpcs_in_flight;
2050 }
2051 EXPORT_SYMBOL(obd_get_max_rpcs_in_flight);
2052
2053 int obd_set_max_rpcs_in_flight(struct client_obd *cli, __u32 max)
2054 {
2055         struct obd_request_slot_waiter *orsw;
2056         __u32                           old;
2057         int                             diff;
2058         int                             i;
2059         char                            *typ_name;
2060         int                             rc;
2061
2062         if (max > OBD_MAX_RIF_MAX || max < 1)
2063                 return -ERANGE;
2064
2065         typ_name = cli->cl_import->imp_obd->obd_type->typ_name;
2066         if (strcmp(typ_name, LUSTRE_MDC_NAME) == 0) {
2067                 /* adjust max_mod_rpcs_in_flight to ensure it is always
2068                  * strictly lower that max_rpcs_in_flight */
2069                 if (max < 2) {
2070                         CERROR("%s: cannot set max_rpcs_in_flight to 1 "
2071                                "because it must be higher than "
2072                                "max_mod_rpcs_in_flight value",
2073                                cli->cl_import->imp_obd->obd_name);
2074                         return -ERANGE;
2075                 }
2076                 if (max <= cli->cl_max_mod_rpcs_in_flight) {
2077                         rc = obd_set_max_mod_rpcs_in_flight(cli, max - 1);
2078                         if (rc != 0)
2079                                 return rc;
2080                 }
2081         }
2082
2083         spin_lock(&cli->cl_loi_list_lock);
2084         old = cli->cl_max_rpcs_in_flight;
2085         cli->cl_max_rpcs_in_flight = max;
2086         diff = max - old;
2087
2088         /* We increase the max_rpcs_in_flight, then wakeup some waiters. */
2089         for (i = 0; i < diff; i++) {
2090                 if (list_empty(&cli->cl_loi_read_list))
2091                         break;
2092
2093                 orsw = list_entry(cli->cl_loi_read_list.next,
2094                                   struct obd_request_slot_waiter, orsw_entry);
2095                 list_del_init(&orsw->orsw_entry);
2096                 cli->cl_r_in_flight++;
2097                 wake_up(&orsw->orsw_waitq);
2098         }
2099         spin_unlock(&cli->cl_loi_list_lock);
2100
2101         return 0;
2102 }
2103 EXPORT_SYMBOL(obd_set_max_rpcs_in_flight);
2104
2105 __u16 obd_get_max_mod_rpcs_in_flight(struct client_obd *cli)
2106 {
2107         return cli->cl_max_mod_rpcs_in_flight;
2108 }
2109 EXPORT_SYMBOL(obd_get_max_mod_rpcs_in_flight);
2110
2111 int obd_set_max_mod_rpcs_in_flight(struct client_obd *cli, __u16 max)
2112 {
2113         struct obd_connect_data *ocd;
2114         __u16 maxmodrpcs;
2115         __u16 prev;
2116
2117         if (max > OBD_MAX_RIF_MAX || max < 1)
2118                 return -ERANGE;
2119
2120         /* cannot exceed or equal max_rpcs_in_flight */
2121         if (max >= cli->cl_max_rpcs_in_flight) {
2122                 CERROR("%s: can't set max_mod_rpcs_in_flight to a value (%hu) "
2123                        "higher or equal to max_rpcs_in_flight value (%u)\n",
2124                        cli->cl_import->imp_obd->obd_name,
2125                        max, cli->cl_max_rpcs_in_flight);
2126                 return -ERANGE;
2127         }
2128
2129         /* cannot exceed max modify RPCs in flight supported by the server */
2130         ocd = &cli->cl_import->imp_connect_data;
2131         if (ocd->ocd_connect_flags & OBD_CONNECT_MULTIMODRPCS)
2132                 maxmodrpcs = ocd->ocd_maxmodrpcs;
2133         else
2134                 maxmodrpcs = 1;
2135         if (max > maxmodrpcs) {
2136                 CERROR("%s: can't set max_mod_rpcs_in_flight to a value (%hu) "
2137                        "higher than max_mod_rpcs_per_client value (%hu) "
2138                        "returned by the server at connection\n",
2139                        cli->cl_import->imp_obd->obd_name,
2140                        max, maxmodrpcs);
2141                 return -ERANGE;
2142         }
2143
2144         spin_lock(&cli->cl_mod_rpcs_lock);
2145
2146         prev = cli->cl_max_mod_rpcs_in_flight;
2147         cli->cl_max_mod_rpcs_in_flight = max;
2148
2149         /* wakeup waiters if limit has been increased */
2150         if (cli->cl_max_mod_rpcs_in_flight > prev)
2151                 wake_up(&cli->cl_mod_rpcs_waitq);
2152
2153         spin_unlock(&cli->cl_mod_rpcs_lock);
2154
2155         return 0;
2156 }
2157 EXPORT_SYMBOL(obd_set_max_mod_rpcs_in_flight);
2158
2159
2160 #define pct(a, b) (b ? a * 100 / b : 0)
2161 int obd_mod_rpc_stats_seq_show(struct client_obd *cli,
2162                                struct seq_file *seq)
2163 {
2164         struct timeval now;
2165         unsigned long mod_tot = 0, mod_cum;
2166         int i;
2167
2168         do_gettimeofday(&now);
2169
2170         spin_lock(&cli->cl_mod_rpcs_lock);
2171
2172         seq_printf(seq, "snapshot_time:         %lu.%lu (secs.usecs)\n",
2173                    now.tv_sec, now.tv_usec);
2174         seq_printf(seq, "modify_RPCs_in_flight:  %hu\n",
2175                    cli->cl_mod_rpcs_in_flight);
2176
2177         seq_printf(seq, "\n\t\t\tmodify\n");
2178         seq_printf(seq, "rpcs in flight        rpcs   %% cum %%\n");
2179
2180         mod_tot = lprocfs_oh_sum(&cli->cl_mod_rpcs_hist);
2181
2182         mod_cum = 0;
2183         for (i = 0; i < OBD_HIST_MAX; i++) {
2184                 unsigned long mod = cli->cl_mod_rpcs_hist.oh_buckets[i];
2185                 mod_cum += mod;
2186                 seq_printf(seq, "%d:\t\t%10lu %3lu %3lu\n",
2187                                  i, mod, pct(mod, mod_tot),
2188                                  pct(mod_cum, mod_tot));
2189                 if (mod_cum == mod_tot)
2190                         break;
2191         }
2192
2193         spin_unlock(&cli->cl_mod_rpcs_lock);
2194
2195         return 0;
2196 }
2197 EXPORT_SYMBOL(obd_mod_rpc_stats_seq_show);
2198 #undef pct
2199
2200
2201 /* The number of modify RPCs sent in parallel is limited
2202  * because the server has a finite number of slots per client to
2203  * store request result and ensure reply reconstruction when needed.
2204  * On the client, this limit is stored in cl_max_mod_rpcs_in_flight
2205  * that takes into account server limit and cl_max_rpcs_in_flight
2206  * value.
2207  * On the MDC client, to avoid a potential deadlock (see Bugzilla 3462),
2208  * one close request is allowed above the maximum.
2209  */
2210 static inline bool obd_mod_rpc_slot_avail_locked(struct client_obd *cli,
2211                                                  bool close_req)
2212 {
2213         bool avail;
2214
2215         /* A slot is available if
2216          * - number of modify RPCs in flight is less than the max
2217          * - it's a close RPC and no other close request is in flight
2218          */
2219         avail = cli->cl_mod_rpcs_in_flight < cli->cl_max_mod_rpcs_in_flight ||
2220                 (close_req && cli->cl_close_rpcs_in_flight == 0);
2221
2222         return avail;
2223 }
2224
2225 static inline bool obd_mod_rpc_slot_avail(struct client_obd *cli,
2226                                          bool close_req)
2227 {
2228         bool avail;
2229
2230         spin_lock(&cli->cl_mod_rpcs_lock);
2231         avail = obd_mod_rpc_slot_avail_locked(cli, close_req);
2232         spin_unlock(&cli->cl_mod_rpcs_lock);
2233         return avail;
2234 }
2235
2236 /* Get a modify RPC slot from the obd client @cli according
2237  * to the kind of operation @opc that is going to be sent
2238  * and the intent @it of the operation if it applies.
2239  * If the maximum number of modify RPCs in flight is reached
2240  * the thread is put to sleep.
2241  * Returns the tag to be set in the request message. Tag 0
2242  * is reserved for non-modifying requests.
2243  */
2244 __u16 obd_get_mod_rpc_slot(struct client_obd *cli, __u32 opc,
2245                            struct lookup_intent *it)
2246 {
2247         struct l_wait_info      lwi = LWI_INTR(NULL, NULL);
2248         bool                    close_req = false;
2249         __u16                   i, max;
2250
2251         /* read-only metadata RPCs don't consume a slot on MDT
2252          * for reply reconstruction
2253          */
2254         if (it != NULL && (it->it_op == IT_GETATTR || it->it_op == IT_LOOKUP ||
2255                            it->it_op == IT_LAYOUT || it->it_op == IT_READDIR))
2256                 return 0;
2257
2258         if (opc == MDS_CLOSE)
2259                 close_req = true;
2260
2261         do {
2262                 spin_lock(&cli->cl_mod_rpcs_lock);
2263                 max = cli->cl_max_mod_rpcs_in_flight;
2264                 if (obd_mod_rpc_slot_avail_locked(cli, close_req)) {
2265                         /* there is a slot available */
2266                         cli->cl_mod_rpcs_in_flight++;
2267                         if (close_req)
2268                                 cli->cl_close_rpcs_in_flight++;
2269                         lprocfs_oh_tally(&cli->cl_mod_rpcs_hist,
2270                                          cli->cl_mod_rpcs_in_flight);
2271                         /* find a free tag */
2272                         i = find_first_zero_bit(cli->cl_mod_tag_bitmap,
2273                                                 max + 1);
2274                         LASSERT(i < OBD_MAX_RIF_MAX);
2275                         LASSERT(!test_and_set_bit(i, cli->cl_mod_tag_bitmap));
2276                         spin_unlock(&cli->cl_mod_rpcs_lock);
2277                         /* tag 0 is reserved for non-modify RPCs */
2278                         return i + 1;
2279                 }
2280                 spin_unlock(&cli->cl_mod_rpcs_lock);
2281
2282                 CDEBUG(D_RPCTRACE, "%s: sleeping for a modify RPC slot "
2283                        "opc %u, max %hu\n",
2284                        cli->cl_import->imp_obd->obd_name, opc, max);
2285
2286                 l_wait_event(cli->cl_mod_rpcs_waitq,
2287                              obd_mod_rpc_slot_avail(cli, close_req), &lwi);
2288         } while (true);
2289 }
2290 EXPORT_SYMBOL(obd_get_mod_rpc_slot);
2291
2292 /* Put a modify RPC slot from the obd client @cli according
2293  * to the kind of operation @opc that has been sent and the
2294  * intent @it of the operation if it applies.
2295  */
2296 void obd_put_mod_rpc_slot(struct client_obd *cli, __u32 opc,
2297                           struct lookup_intent *it, __u16 tag)
2298 {
2299         bool                    close_req = false;
2300
2301         if (it != NULL && (it->it_op == IT_GETATTR || it->it_op == IT_LOOKUP ||
2302                            it->it_op == IT_LAYOUT || it->it_op == IT_READDIR))
2303                 return;
2304
2305         if (opc == MDS_CLOSE)
2306                 close_req = true;
2307
2308         spin_lock(&cli->cl_mod_rpcs_lock);
2309         cli->cl_mod_rpcs_in_flight--;
2310         if (close_req)
2311                 cli->cl_close_rpcs_in_flight--;
2312         /* release the tag in the bitmap */
2313         LASSERT(tag - 1 < OBD_MAX_RIF_MAX);
2314         LASSERT(test_and_clear_bit(tag - 1, cli->cl_mod_tag_bitmap) != 0);
2315         spin_unlock(&cli->cl_mod_rpcs_lock);
2316         wake_up(&cli->cl_mod_rpcs_waitq);
2317 }
2318 EXPORT_SYMBOL(obd_put_mod_rpc_slot);
2319