Whamcloud - gitweb
ef21c696f493a738210061d12719420ef4918b2c
[fs/lustre-release.git] / lustre / ldlm / ldlm_resource.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) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2010, 2013, 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/ldlm/ldlm_resource.c
37  *
38  * Author: Phil Schwan <phil@clusterfs.com>
39  * Author: Peter Braam <braam@clusterfs.com>
40  */
41
42 #define DEBUG_SUBSYSTEM S_LDLM
43 #ifdef __KERNEL__
44 # include <lustre_dlm.h>
45 #else
46 # include <liblustre.h>
47 #endif
48
49 #include <lustre_fid.h>
50 #include <obd_class.h>
51 #include "ldlm_internal.h"
52
53 struct kmem_cache *ldlm_resource_slab, *ldlm_lock_slab;
54
55 int ldlm_srv_namespace_nr = 0;
56 int ldlm_cli_namespace_nr = 0;
57
58 struct mutex ldlm_srv_namespace_lock;
59 CFS_LIST_HEAD(ldlm_srv_namespace_list);
60
61 struct mutex ldlm_cli_namespace_lock;
62 /* Client Namespaces that have active resources in them.
63  * Once all resources go away, ldlm_poold moves such namespaces to the
64  * inactive list */
65 CFS_LIST_HEAD(ldlm_cli_active_namespace_list);
66 /* Client namespaces that don't have any locks in them */
67 CFS_LIST_HEAD(ldlm_cli_inactive_namespace_list);
68
69 struct proc_dir_entry *ldlm_type_proc_dir = NULL;
70 struct proc_dir_entry *ldlm_ns_proc_dir = NULL;
71 struct proc_dir_entry *ldlm_svc_proc_dir = NULL;
72
73 extern unsigned int ldlm_cancel_unused_locks_before_replay;
74
75 /* during debug dump certain amount of granted locks for one resource to avoid
76  * DDOS. */
77 unsigned int ldlm_dump_granted_max = 256;
78
79 #ifdef LPROCFS
80 static ssize_t
81 lprocfs_dump_ns_seq_write(struct file *file, const char *buffer,
82                           size_t count, loff_t *off)
83 {
84         ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
85         ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
86         RETURN(count);
87 }
88 LPROC_SEQ_FOPS_WO_TYPE(ldlm, dump_ns);
89
90 LPROC_SEQ_FOPS_RW_TYPE(ldlm_rw, uint);
91 LPROC_SEQ_FOPS_RO_TYPE(ldlm, uint);
92
93 int ldlm_proc_setup(void)
94 {
95         int rc;
96         struct lprocfs_seq_vars list[] = {
97                 { .name =       "dump_namespaces",
98                   .fops =       &ldlm_dump_ns_fops,
99                   .proc_mode =  0222 },
100                 { .name =       "dump_granted_max",
101                   .fops =       &ldlm_rw_uint_fops,
102                   .data =       &ldlm_dump_granted_max },
103                 { .name =       "cancel_unused_locks_before_replay",
104                   .fops =       &ldlm_rw_uint_fops,
105                   .data =       &ldlm_cancel_unused_locks_before_replay },
106                 { NULL }};
107         ENTRY;
108         LASSERT(ldlm_ns_proc_dir == NULL);
109
110         ldlm_type_proc_dir = lprocfs_seq_register(OBD_LDLM_DEVICENAME,
111                                                         proc_lustre_root,
112                                                         NULL, NULL);
113         if (IS_ERR(ldlm_type_proc_dir)) {
114                 CERROR("LProcFS failed in ldlm-init\n");
115                 rc = PTR_ERR(ldlm_type_proc_dir);
116                 GOTO(err, rc);
117         }
118
119         ldlm_ns_proc_dir = lprocfs_seq_register("namespaces",
120                                                 ldlm_type_proc_dir,
121                                                 NULL, NULL);
122         if (IS_ERR(ldlm_ns_proc_dir)) {
123                 CERROR("LProcFS failed in ldlm-init\n");
124                 rc = PTR_ERR(ldlm_ns_proc_dir);
125                 GOTO(err_type, rc);
126         }
127
128         ldlm_svc_proc_dir = lprocfs_seq_register("services",
129                                                 ldlm_type_proc_dir,
130                                                 NULL, NULL);
131         if (IS_ERR(ldlm_svc_proc_dir)) {
132                 CERROR("LProcFS failed in ldlm-init\n");
133                 rc = PTR_ERR(ldlm_svc_proc_dir);
134                 GOTO(err_ns, rc);
135         }
136
137         rc = lprocfs_seq_add_vars(ldlm_type_proc_dir, list, NULL);
138         if (rc != 0) {
139                 CERROR("LProcFS failed in ldlm-init\n");
140                 GOTO(err_svc, rc);
141         }
142
143         RETURN(0);
144
145 err_svc:
146         lprocfs_remove(&ldlm_svc_proc_dir);
147 err_ns:
148         lprocfs_remove(&ldlm_ns_proc_dir);
149 err_type:
150         lprocfs_remove(&ldlm_type_proc_dir);
151 err:
152         ldlm_svc_proc_dir = NULL;
153         RETURN(rc);
154 }
155
156 void ldlm_proc_cleanup(void)
157 {
158         if (ldlm_svc_proc_dir)
159                 lprocfs_remove(&ldlm_svc_proc_dir);
160
161         if (ldlm_ns_proc_dir)
162                 lprocfs_remove(&ldlm_ns_proc_dir);
163
164         if (ldlm_type_proc_dir)
165                 lprocfs_remove(&ldlm_type_proc_dir);
166 }
167
168 static int lprocfs_ns_resources_seq_show(struct seq_file *m, void *v)
169 {
170         struct ldlm_namespace   *ns  = m->private;
171         __u64                   res = 0;
172         cfs_hash_bd_t           bd;
173         int                     i;
174
175         /* result is not strictly consistant */
176         cfs_hash_for_each_bucket(ns->ns_rs_hash, &bd, i)
177                 res += cfs_hash_bd_count_get(&bd);
178         return lprocfs_u64_seq_show(m, &res);
179 }
180 LPROC_SEQ_FOPS_RO(lprocfs_ns_resources);
181
182 static int lprocfs_ns_locks_seq_show(struct seq_file *m, void *v)
183 {
184         struct ldlm_namespace   *ns = m->private;
185         __u64                   locks;
186
187         locks = lprocfs_stats_collector(ns->ns_stats, LDLM_NSS_LOCKS,
188                                         LPROCFS_FIELDS_FLAGS_SUM);
189         return lprocfs_u64_seq_show(m, &locks);
190 }
191 LPROC_SEQ_FOPS_RO(lprocfs_ns_locks);
192
193 static int lprocfs_lru_size_seq_show(struct seq_file *m, void *v)
194 {
195         struct ldlm_namespace *ns = m->private;
196         __u32 *nr = &ns->ns_max_unused;
197
198         if (ns_connect_lru_resize(ns))
199                 nr = &ns->ns_nr_unused;
200         return lprocfs_uint_seq_show(m, nr);
201 }
202
203 static ssize_t lprocfs_lru_size_seq_write(struct file *file, const char *buffer,
204                                           size_t count, loff_t *off)
205 {
206         struct ldlm_namespace *ns = ((struct seq_file *)file->private_data)->private;
207         char dummy[MAX_STRING_SIZE + 1], *end;
208         unsigned long tmp;
209         int lru_resize;
210
211         dummy[MAX_STRING_SIZE] = '\0';
212         if (copy_from_user(dummy, buffer, MAX_STRING_SIZE))
213                 return -EFAULT;
214
215         if (strncmp(dummy, "clear", 5) == 0) {
216                 CDEBUG(D_DLMTRACE,
217                        "dropping all unused locks from namespace %s\n",
218                        ldlm_ns_name(ns));
219                 if (ns_connect_lru_resize(ns)) {
220                         int canceled, unused  = ns->ns_nr_unused;
221
222                         /* Try to cancel all @ns_nr_unused locks. */
223                         canceled = ldlm_cancel_lru(ns, unused, 0,
224                                                    LDLM_CANCEL_PASSED);
225                         if (canceled < unused) {
226                                 CDEBUG(D_DLMTRACE,
227                                        "not all requested locks are canceled, "
228                                        "requested: %d, canceled: %d\n", unused,
229                                        canceled);
230                                 return -EINVAL;
231                         }
232                 } else {
233                         tmp = ns->ns_max_unused;
234                         ns->ns_max_unused = 0;
235                         ldlm_cancel_lru(ns, 0, 0, LDLM_CANCEL_PASSED);
236                         ns->ns_max_unused = tmp;
237                 }
238                 return count;
239         }
240
241         tmp = simple_strtoul(dummy, &end, 0);
242         if (dummy == end) {
243                 CERROR("invalid value written\n");
244                 return -EINVAL;
245         }
246         lru_resize = (tmp == 0);
247
248         if (ns_connect_lru_resize(ns)) {
249                 if (!lru_resize)
250                         ns->ns_max_unused = (unsigned int)tmp;
251
252                 if (tmp > ns->ns_nr_unused)
253                         tmp = ns->ns_nr_unused;
254                 tmp = ns->ns_nr_unused - tmp;
255
256                 CDEBUG(D_DLMTRACE,
257                        "changing namespace %s unused locks from %u to %u\n",
258                        ldlm_ns_name(ns), ns->ns_nr_unused,
259                        (unsigned int)tmp);
260                 ldlm_cancel_lru(ns, tmp, LCF_ASYNC, LDLM_CANCEL_PASSED);
261
262                 if (!lru_resize) {
263                         CDEBUG(D_DLMTRACE,
264                                "disable lru_resize for namespace %s\n",
265                                ldlm_ns_name(ns));
266                         ns->ns_connect_flags &= ~OBD_CONNECT_LRU_RESIZE;
267                 }
268         } else {
269                 CDEBUG(D_DLMTRACE,
270                        "changing namespace %s max_unused from %u to %u\n",
271                        ldlm_ns_name(ns), ns->ns_max_unused,
272                        (unsigned int)tmp);
273                 ns->ns_max_unused = (unsigned int)tmp;
274                 ldlm_cancel_lru(ns, 0, LCF_ASYNC, LDLM_CANCEL_PASSED);
275
276                 /* Make sure that LRU resize was originally supported before
277                  * turning it on here. */
278                 if (lru_resize &&
279                     (ns->ns_orig_connect_flags & OBD_CONNECT_LRU_RESIZE)) {
280                         CDEBUG(D_DLMTRACE,
281                                "enable lru_resize for namespace %s\n",
282                                ldlm_ns_name(ns));
283                         ns->ns_connect_flags |= OBD_CONNECT_LRU_RESIZE;
284                 }
285         }
286
287         return count;
288 }
289 LPROC_SEQ_FOPS(lprocfs_lru_size);
290
291 static int lprocfs_elc_seq_show(struct seq_file *m, void *v)
292 {
293         struct ldlm_namespace *ns = m->private;
294         unsigned int supp = ns_connect_cancelset(ns);
295
296         return lprocfs_uint_seq_show(m, &supp);
297 }
298
299 static ssize_t lprocfs_elc_seq_write(struct file *file, const char *buffer,
300                                      size_t count, loff_t *off)
301 {
302         struct ldlm_namespace *ns = ((struct seq_file *)file->private_data)->private;
303         unsigned int supp = -1;
304         int rc;
305
306         rc = lprocfs_wr_uint(file, buffer, count, &supp);
307         if (rc < 0)
308                 return rc;
309
310         if (supp == 0)
311                 ns->ns_connect_flags &= ~OBD_CONNECT_CANCELSET;
312         else if (ns->ns_orig_connect_flags & OBD_CONNECT_CANCELSET)
313                 ns->ns_connect_flags |= OBD_CONNECT_CANCELSET;
314         return count;
315 }
316 LPROC_SEQ_FOPS(lprocfs_elc);
317
318 void ldlm_namespace_proc_unregister(struct ldlm_namespace *ns)
319 {
320         if (ns->ns_proc_dir_entry == NULL)
321                 CERROR("dlm namespace %s has no procfs dir?\n",
322                        ldlm_ns_name(ns));
323         else
324                 lprocfs_remove(&ns->ns_proc_dir_entry);
325
326         if (ns->ns_stats != NULL)
327                 lprocfs_free_stats(&ns->ns_stats);
328 }
329
330 int ldlm_namespace_proc_register(struct ldlm_namespace *ns)
331 {
332         struct lprocfs_seq_vars lock_vars[2];
333         char lock_name[MAX_STRING_SIZE + 1];
334         struct proc_dir_entry *ns_pde;
335
336         LASSERT(ns != NULL);
337         LASSERT(ns->ns_rs_hash != NULL);
338
339         if (ns->ns_proc_dir_entry != NULL) {
340                 ns_pde = ns->ns_proc_dir_entry;
341         } else {
342                 ns_pde = proc_mkdir(ldlm_ns_name(ns), ldlm_ns_proc_dir);
343                 if (ns_pde == NULL)
344                         return -ENOMEM;
345                 ns->ns_proc_dir_entry = ns_pde;
346         }
347
348         ns->ns_stats = lprocfs_alloc_stats(LDLM_NSS_LAST, 0);
349         if (ns->ns_stats == NULL)
350                 return -ENOMEM;
351
352         lprocfs_counter_init(ns->ns_stats, LDLM_NSS_LOCKS,
353                              LPROCFS_CNTR_AVGMINMAX, "locks", "locks");
354
355         lock_name[MAX_STRING_SIZE] = '\0';
356
357         memset(lock_vars, 0, sizeof(lock_vars));
358         lock_vars[0].name = lock_name;
359
360         ldlm_add_var(&lock_vars[0], ns_pde, "resource_count", ns,
361                      &lprocfs_ns_resources_fops);
362         ldlm_add_var(&lock_vars[0], ns_pde, "lock_count", ns,
363                      &lprocfs_ns_locks_fops);
364
365         if (ns_is_client(ns)) {
366                 ldlm_add_var(&lock_vars[0], ns_pde, "lock_unused_count",
367                              &ns->ns_nr_unused, &ldlm_uint_fops);
368                 ldlm_add_var(&lock_vars[0], ns_pde, "lru_size", ns,
369                              &lprocfs_lru_size_fops);
370                 ldlm_add_var(&lock_vars[0], ns_pde, "lru_max_age",
371                              &ns->ns_max_age, &ldlm_rw_uint_fops);
372                 ldlm_add_var(&lock_vars[0], ns_pde, "early_lock_cancel",
373                              ns, &lprocfs_elc_fops);
374         } else {
375                 ldlm_add_var(&lock_vars[0], ns_pde, "ctime_age_limit",
376                              &ns->ns_ctime_age_limit, &ldlm_rw_uint_fops);
377                 ldlm_add_var(&lock_vars[0], ns_pde, "lock_timeouts",
378                              &ns->ns_timeouts, &ldlm_uint_fops);
379                 ldlm_add_var(&lock_vars[0], ns_pde, "max_nolock_bytes",
380                              &ns->ns_max_nolock_size, &ldlm_rw_uint_fops);
381                 ldlm_add_var(&lock_vars[0], ns_pde, "contention_seconds",
382                              &ns->ns_contention_time, &ldlm_rw_uint_fops);
383                 ldlm_add_var(&lock_vars[0], ns_pde, "contended_locks",
384                              &ns->ns_contended_locks, &ldlm_rw_uint_fops);
385                 ldlm_add_var(&lock_vars[0], ns_pde, "max_parallel_ast",
386                              &ns->ns_max_parallel_ast, &ldlm_rw_uint_fops);
387         }
388         return 0;
389 }
390 #undef MAX_STRING_SIZE
391 #else /* LPROCFS */
392
393 #define ldlm_namespace_proc_unregister(ns)      ({;})
394 #define ldlm_namespace_proc_register(ns)        ({0;})
395
396 #endif /* LPROCFS */
397
398 static unsigned ldlm_res_hop_hash(cfs_hash_t *hs,
399                                   const void *key, unsigned mask)
400 {
401         const struct ldlm_res_id     *id  = key;
402         unsigned                val = 0;
403         unsigned                i;
404
405         for (i = 0; i < RES_NAME_SIZE; i++)
406                 val += id->name[i];
407         return val & mask;
408 }
409
410 static unsigned ldlm_res_hop_fid_hash(cfs_hash_t *hs,
411                                       const void *key, unsigned mask)
412 {
413         const struct ldlm_res_id *id = key;
414         struct lu_fid       fid;
415         __u32               hash;
416         __u32               val;
417
418         fid.f_seq = id->name[LUSTRE_RES_ID_SEQ_OFF];
419         fid.f_oid = (__u32)id->name[LUSTRE_RES_ID_VER_OID_OFF];
420         fid.f_ver = (__u32)(id->name[LUSTRE_RES_ID_VER_OID_OFF] >> 32);
421
422         hash = fid_flatten32(&fid);
423         hash += (hash >> 4) + (hash << 12); /* mixing oid and seq */
424         if (id->name[LUSTRE_RES_ID_HSH_OFF] != 0) {
425                 val = id->name[LUSTRE_RES_ID_HSH_OFF];
426                 hash += (val >> 5) + (val << 11);
427         } else {
428                 val = fid_oid(&fid);
429         }
430         hash = hash_long(hash, hs->hs_bkt_bits);
431         /* give me another random factor */
432         hash -= hash_long((unsigned long)hs, val % 11 + 3);
433
434         hash <<= hs->hs_cur_bits - hs->hs_bkt_bits;
435         hash |= ldlm_res_hop_hash(hs, key, CFS_HASH_NBKT(hs) - 1);
436
437         return hash & mask;
438 }
439
440 static void *ldlm_res_hop_key(cfs_hlist_node_t *hnode)
441 {
442         struct ldlm_resource   *res;
443
444         res = cfs_hlist_entry(hnode, struct ldlm_resource, lr_hash);
445         return &res->lr_name;
446 }
447
448 static int ldlm_res_hop_keycmp(const void *key, cfs_hlist_node_t *hnode)
449 {
450         struct ldlm_resource   *res;
451
452         res = cfs_hlist_entry(hnode, struct ldlm_resource, lr_hash);
453         return ldlm_res_eq((const struct ldlm_res_id *)key,
454                            (const struct ldlm_res_id *)&res->lr_name);
455 }
456
457 static void *ldlm_res_hop_object(cfs_hlist_node_t *hnode)
458 {
459         return cfs_hlist_entry(hnode, struct ldlm_resource, lr_hash);
460 }
461
462 static void ldlm_res_hop_get_locked(cfs_hash_t *hs, cfs_hlist_node_t *hnode)
463 {
464         struct ldlm_resource *res;
465
466         res = cfs_hlist_entry(hnode, struct ldlm_resource, lr_hash);
467         ldlm_resource_getref(res);
468 }
469
470 static void ldlm_res_hop_put_locked(cfs_hash_t *hs, cfs_hlist_node_t *hnode)
471 {
472         struct ldlm_resource *res;
473
474         res = cfs_hlist_entry(hnode, struct ldlm_resource, lr_hash);
475         /* cfs_hash_for_each_nolock is the only chance we call it */
476         ldlm_resource_putref_locked(res);
477 }
478
479 static void ldlm_res_hop_put(cfs_hash_t *hs, cfs_hlist_node_t *hnode)
480 {
481         struct ldlm_resource *res;
482
483         res = cfs_hlist_entry(hnode, struct ldlm_resource, lr_hash);
484         ldlm_resource_putref(res);
485 }
486
487 cfs_hash_ops_t ldlm_ns_hash_ops = {
488         .hs_hash        = ldlm_res_hop_hash,
489         .hs_key         = ldlm_res_hop_key,
490         .hs_keycmp      = ldlm_res_hop_keycmp,
491         .hs_keycpy      = NULL,
492         .hs_object      = ldlm_res_hop_object,
493         .hs_get         = ldlm_res_hop_get_locked,
494         .hs_put_locked  = ldlm_res_hop_put_locked,
495         .hs_put         = ldlm_res_hop_put
496 };
497
498 cfs_hash_ops_t ldlm_ns_fid_hash_ops = {
499         .hs_hash        = ldlm_res_hop_fid_hash,
500         .hs_key         = ldlm_res_hop_key,
501         .hs_keycmp      = ldlm_res_hop_keycmp,
502         .hs_keycpy      = NULL,
503         .hs_object      = ldlm_res_hop_object,
504         .hs_get         = ldlm_res_hop_get_locked,
505         .hs_put_locked  = ldlm_res_hop_put_locked,
506         .hs_put         = ldlm_res_hop_put
507 };
508
509 typedef struct {
510         ldlm_ns_type_t  nsd_type;
511         /** hash bucket bits */
512         unsigned        nsd_bkt_bits;
513         /** hash bits */
514         unsigned        nsd_all_bits;
515         /** hash operations */
516         cfs_hash_ops_t *nsd_hops;
517 } ldlm_ns_hash_def_t;
518
519 ldlm_ns_hash_def_t ldlm_ns_hash_defs[] =
520 {
521         {
522                 .nsd_type       = LDLM_NS_TYPE_MDC,
523                 .nsd_bkt_bits   = 11,
524                 .nsd_all_bits   = 16,
525                 .nsd_hops       = &ldlm_ns_fid_hash_ops,
526         },
527         {
528                 .nsd_type       = LDLM_NS_TYPE_MDT,
529                 .nsd_bkt_bits   = 14,
530                 .nsd_all_bits   = 21,
531                 .nsd_hops       = &ldlm_ns_fid_hash_ops,
532         },
533         {
534                 .nsd_type       = LDLM_NS_TYPE_OSC,
535                 .nsd_bkt_bits   = 8,
536                 .nsd_all_bits   = 12,
537                 .nsd_hops       = &ldlm_ns_hash_ops,
538         },
539         {
540                 .nsd_type       = LDLM_NS_TYPE_OST,
541                 .nsd_bkt_bits   = 11,
542                 .nsd_all_bits   = 17,
543                 .nsd_hops       = &ldlm_ns_hash_ops,
544         },
545         {
546                 .nsd_type       = LDLM_NS_TYPE_MGC,
547                 .nsd_bkt_bits   = 4,
548                 .nsd_all_bits   = 4,
549                 .nsd_hops       = &ldlm_ns_hash_ops,
550         },
551         {
552                 .nsd_type       = LDLM_NS_TYPE_MGT,
553                 .nsd_bkt_bits   = 4,
554                 .nsd_all_bits   = 4,
555                 .nsd_hops       = &ldlm_ns_hash_ops,
556         },
557         {
558                 .nsd_type       = LDLM_NS_TYPE_UNKNOWN,
559         },
560 };
561
562 /**
563  * Create and initialize new empty namespace.
564  */
565 struct ldlm_namespace *ldlm_namespace_new(struct obd_device *obd, char *name,
566                                           ldlm_side_t client,
567                                           ldlm_appetite_t apt,
568                                           ldlm_ns_type_t ns_type)
569 {
570         struct ldlm_namespace *ns = NULL;
571         struct ldlm_ns_bucket *nsb;
572         ldlm_ns_hash_def_t    *nsd;
573         cfs_hash_bd_t          bd;
574         int                    idx;
575         int                    rc;
576         ENTRY;
577
578         LASSERT(obd != NULL);
579
580         rc = ldlm_get_ref();
581         if (rc) {
582                 CERROR("ldlm_get_ref failed: %d\n", rc);
583                 RETURN(NULL);
584         }
585
586         for (idx = 0;;idx++) {
587                 nsd = &ldlm_ns_hash_defs[idx];
588                 if (nsd->nsd_type == LDLM_NS_TYPE_UNKNOWN) {
589                         CERROR("Unknown type %d for ns %s\n", ns_type, name);
590                         GOTO(out_ref, NULL);
591                 }
592
593                 if (nsd->nsd_type == ns_type)
594                         break;
595         }
596
597         OBD_ALLOC_PTR(ns);
598         if (!ns)
599                 GOTO(out_ref, NULL);
600
601         ns->ns_rs_hash = cfs_hash_create(name,
602                                          nsd->nsd_all_bits, nsd->nsd_all_bits,
603                                          nsd->nsd_bkt_bits, sizeof(*nsb),
604                                          CFS_HASH_MIN_THETA,
605                                          CFS_HASH_MAX_THETA,
606                                          nsd->nsd_hops,
607                                          CFS_HASH_DEPTH |
608                                          CFS_HASH_BIGNAME |
609                                          CFS_HASH_SPIN_BKTLOCK |
610                                          CFS_HASH_NO_ITEMREF);
611         if (ns->ns_rs_hash == NULL)
612                 GOTO(out_ns, NULL);
613
614         cfs_hash_for_each_bucket(ns->ns_rs_hash, &bd, idx) {
615                 nsb = cfs_hash_bd_extra_get(ns->ns_rs_hash, &bd);
616                 at_init(&nsb->nsb_at_estimate, ldlm_enqueue_min, 0);
617                 nsb->nsb_namespace = ns;
618         }
619
620         ns->ns_obd      = obd;
621         ns->ns_appetite = apt;
622         ns->ns_client   = client;
623
624         CFS_INIT_LIST_HEAD(&ns->ns_list_chain);
625         CFS_INIT_LIST_HEAD(&ns->ns_unused_list);
626         spin_lock_init(&ns->ns_lock);
627         atomic_set(&ns->ns_bref, 0);
628         init_waitqueue_head(&ns->ns_waitq);
629
630         ns->ns_max_nolock_size    = NS_DEFAULT_MAX_NOLOCK_BYTES;
631         ns->ns_contention_time    = NS_DEFAULT_CONTENTION_SECONDS;
632         ns->ns_contended_locks    = NS_DEFAULT_CONTENDED_LOCKS;
633
634         ns->ns_max_parallel_ast   = LDLM_DEFAULT_PARALLEL_AST_LIMIT;
635         ns->ns_nr_unused          = 0;
636         ns->ns_max_unused         = LDLM_DEFAULT_LRU_SIZE;
637         ns->ns_max_age            = LDLM_DEFAULT_MAX_ALIVE;
638         ns->ns_ctime_age_limit    = LDLM_CTIME_AGE_LIMIT;
639         ns->ns_timeouts           = 0;
640         ns->ns_orig_connect_flags = 0;
641         ns->ns_connect_flags      = 0;
642         ns->ns_stopping           = 0;
643         rc = ldlm_namespace_proc_register(ns);
644         if (rc != 0) {
645                 CERROR("Can't initialize ns proc, rc %d\n", rc);
646                 GOTO(out_hash, rc);
647         }
648
649         idx = ldlm_namespace_nr_read(client);
650         rc = ldlm_pool_init(&ns->ns_pool, ns, idx, client);
651         if (rc) {
652                 CERROR("Can't initialize lock pool, rc %d\n", rc);
653                 GOTO(out_proc, rc);
654         }
655
656         ldlm_namespace_register(ns, client);
657         RETURN(ns);
658 out_proc:
659         ldlm_namespace_proc_unregister(ns);
660         ldlm_namespace_cleanup(ns, 0);
661 out_hash:
662         cfs_hash_putref(ns->ns_rs_hash);
663 out_ns:
664         OBD_FREE_PTR(ns);
665 out_ref:
666         ldlm_put_ref();
667         RETURN(NULL);
668 }
669 EXPORT_SYMBOL(ldlm_namespace_new);
670
671 extern struct ldlm_lock *ldlm_lock_get(struct ldlm_lock *lock);
672
673 /**
674  * Cancel and destroy all locks on a resource.
675  *
676  * If flags contains FL_LOCAL_ONLY, don't try to tell the server, just
677  * clean up.  This is currently only used for recovery, and we make
678  * certain assumptions as a result--notably, that we shouldn't cancel
679  * locks with refs.
680  */
681 static void cleanup_resource(struct ldlm_resource *res, cfs_list_t *q,
682                              __u64 flags)
683 {
684         cfs_list_t *tmp;
685         int rc = 0, client = ns_is_client(ldlm_res_to_ns(res));
686         bool local_only = !!(flags & LDLM_FL_LOCAL_ONLY);
687
688         do {
689                 struct ldlm_lock *lock = NULL;
690
691                 /* First, we look for non-cleaned-yet lock
692                  * all cleaned locks are marked by CLEANED flag. */
693                 lock_res(res);
694                 cfs_list_for_each(tmp, q) {
695                         lock = cfs_list_entry(tmp, struct ldlm_lock,
696                                               l_res_link);
697                         if (ldlm_is_cleaned(lock)) {
698                                 lock = NULL;
699                                 continue;
700                         }
701                         LDLM_LOCK_GET(lock);
702                         ldlm_set_cleaned(lock);
703                         break;
704                 }
705
706                 if (lock == NULL) {
707                         unlock_res(res);
708                         break;
709                 }
710
711                 /* Set CBPENDING so nothing in the cancellation path
712                  * can match this lock. */
713                 ldlm_set_cbpending(lock);
714                 ldlm_set_failed(lock);
715                 lock->l_flags |= flags;
716
717                 /* ... without sending a CANCEL message for local_only. */
718                 if (local_only)
719                         ldlm_set_local_only(lock);
720
721                 if (local_only && (lock->l_readers || lock->l_writers)) {
722                         /* This is a little bit gross, but much better than the
723                          * alternative: pretend that we got a blocking AST from
724                          * the server, so that when the lock is decref'd, it
725                          * will go away ... */
726                         unlock_res(res);
727                         LDLM_DEBUG(lock, "setting FL_LOCAL_ONLY");
728                         if (lock->l_completion_ast)
729                                 lock->l_completion_ast(lock, 0, NULL);
730                         LDLM_LOCK_RELEASE(lock);
731                         continue;
732                 }
733
734                 if (client) {
735                         struct lustre_handle lockh;
736
737                         unlock_res(res);
738                         ldlm_lock2handle(lock, &lockh);
739                         rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
740                         if (rc)
741                                 CERROR("ldlm_cli_cancel: %d\n", rc);
742                 } else {
743                         ldlm_resource_unlink_lock(lock);
744                         unlock_res(res);
745                         LDLM_DEBUG(lock, "Freeing a lock still held by a "
746                                    "client node");
747                         ldlm_lock_destroy(lock);
748                 }
749                 LDLM_LOCK_RELEASE(lock);
750         } while (1);
751 }
752
753 static int ldlm_resource_clean(cfs_hash_t *hs, cfs_hash_bd_t *bd,
754                                cfs_hlist_node_t *hnode, void *arg)
755 {
756         struct ldlm_resource *res = cfs_hash_object(hs, hnode);
757         __u64 flags = *(__u64 *)arg;
758
759         cleanup_resource(res, &res->lr_granted, flags);
760         cleanup_resource(res, &res->lr_converting, flags);
761         cleanup_resource(res, &res->lr_waiting, flags);
762
763         return 0;
764 }
765
766 static int ldlm_resource_complain(cfs_hash_t *hs, cfs_hash_bd_t *bd,
767                                   cfs_hlist_node_t *hnode, void *arg)
768 {
769         struct ldlm_resource  *res = cfs_hash_object(hs, hnode);
770
771         lock_res(res);
772         CERROR("%s: namespace resource "DLDLMRES" (%p) refcount nonzero "
773                "(%d) after lock cleanup; forcing cleanup.\n",
774                ldlm_ns_name(ldlm_res_to_ns(res)), PLDLMRES(res), res,
775                atomic_read(&res->lr_refcount) - 1);
776
777         ldlm_resource_dump(D_ERROR, res);
778         unlock_res(res);
779         return 0;
780 }
781
782 /**
783  * Cancel and destroy all locks in the namespace.
784  *
785  * Typically used during evictions when server notified client that it was
786  * evicted and all of its state needs to be destroyed.
787  * Also used during shutdown.
788  */
789 int ldlm_namespace_cleanup(struct ldlm_namespace *ns, __u64 flags)
790 {
791         if (ns == NULL) {
792                 CDEBUG(D_INFO, "NULL ns, skipping cleanup\n");
793                 return ELDLM_OK;
794         }
795
796         cfs_hash_for_each_nolock(ns->ns_rs_hash, ldlm_resource_clean, &flags);
797         cfs_hash_for_each_nolock(ns->ns_rs_hash, ldlm_resource_complain, NULL);
798         return ELDLM_OK;
799 }
800 EXPORT_SYMBOL(ldlm_namespace_cleanup);
801
802 /**
803  * Attempts to free namespace.
804  *
805  * Only used when namespace goes away, like during an unmount.
806  */
807 static int __ldlm_namespace_free(struct ldlm_namespace *ns, int force)
808 {
809         ENTRY;
810
811         /* At shutdown time, don't call the cancellation callback */
812         ldlm_namespace_cleanup(ns, force ? LDLM_FL_LOCAL_ONLY : 0);
813
814         if (atomic_read(&ns->ns_bref) > 0) {
815                 struct l_wait_info lwi = LWI_INTR(LWI_ON_SIGNAL_NOOP, NULL);
816                 int rc;
817                 CDEBUG(D_DLMTRACE,
818                        "dlm namespace %s free waiting on refcount %d\n",
819                        ldlm_ns_name(ns), atomic_read(&ns->ns_bref));
820 force_wait:
821                 if (force)
822                         lwi = LWI_TIMEOUT(obd_timeout * HZ / 4, NULL, NULL);
823
824                 rc = l_wait_event(ns->ns_waitq,
825                                   atomic_read(&ns->ns_bref) == 0, &lwi);
826
827                 /* Forced cleanups should be able to reclaim all references,
828                  * so it's safe to wait forever... we can't leak locks... */
829                 if (force && rc == -ETIMEDOUT) {
830                         LCONSOLE_ERROR("Forced cleanup waiting for %s "
831                                        "namespace with %d resources in use, "
832                                        "(rc=%d)\n", ldlm_ns_name(ns),
833                                        atomic_read(&ns->ns_bref), rc);
834                         GOTO(force_wait, rc);
835                 }
836
837                 if (atomic_read(&ns->ns_bref)) {
838                         LCONSOLE_ERROR("Cleanup waiting for %s namespace "
839                                        "with %d resources in use, (rc=%d)\n",
840                                        ldlm_ns_name(ns),
841                                        atomic_read(&ns->ns_bref), rc);
842                         RETURN(ELDLM_NAMESPACE_EXISTS);
843                 }
844                 CDEBUG(D_DLMTRACE, "dlm namespace %s free done waiting\n",
845                        ldlm_ns_name(ns));
846         }
847
848         RETURN(ELDLM_OK);
849 }
850
851 /**
852  * Performs various cleanups for passed \a ns to make it drop refc and be
853  * ready for freeing. Waits for refc == 0.
854  *
855  * The following is done:
856  * (0) Unregister \a ns from its list to make inaccessible for potential
857  * users like pools thread and others;
858  * (1) Clear all locks in \a ns.
859  */
860 void ldlm_namespace_free_prior(struct ldlm_namespace *ns,
861                                struct obd_import *imp,
862                                int force)
863 {
864         int rc;
865         ENTRY;
866         if (!ns) {
867                 EXIT;
868                 return;
869         }
870
871         spin_lock(&ns->ns_lock);
872         ns->ns_stopping = 1;
873         spin_unlock(&ns->ns_lock);
874
875         /*
876          * Can fail with -EINTR when force == 0 in which case try harder.
877          */
878         rc = __ldlm_namespace_free(ns, force);
879         if (rc != ELDLM_OK) {
880                 if (imp) {
881                         ptlrpc_disconnect_import(imp, 0);
882                         ptlrpc_invalidate_import(imp);
883                 }
884
885                 /*
886                  * With all requests dropped and the import inactive
887                  * we are gaurenteed all reference will be dropped.
888                  */
889                 rc = __ldlm_namespace_free(ns, 1);
890                 LASSERT(rc == 0);
891         }
892         EXIT;
893 }
894
895 /**
896  * Performs freeing memory structures related to \a ns. This is only done
897  * when ldlm_namespce_free_prior() successfully removed all resources
898  * referencing \a ns and its refc == 0.
899  */
900 void ldlm_namespace_free_post(struct ldlm_namespace *ns)
901 {
902         ENTRY;
903         if (!ns) {
904                 EXIT;
905                 return;
906         }
907
908         /* Make sure that nobody can find this ns in its list. */
909         ldlm_namespace_unregister(ns, ns->ns_client);
910         /* Fini pool _before_ parent proc dir is removed. This is important as
911          * ldlm_pool_fini() removes own proc dir which is child to @dir.
912          * Removing it after @dir may cause oops. */
913         ldlm_pool_fini(&ns->ns_pool);
914
915         ldlm_namespace_proc_unregister(ns);
916         cfs_hash_putref(ns->ns_rs_hash);
917         /* Namespace \a ns should be not on list at this time, otherwise
918          * this will cause issues related to using freed \a ns in poold
919          * thread. */
920         LASSERT(cfs_list_empty(&ns->ns_list_chain));
921         OBD_FREE_PTR(ns);
922         ldlm_put_ref();
923         EXIT;
924 }
925
926 /**
927  * Cleanup the resource, and free namespace.
928  * bug 12864:
929  * Deadlock issue:
930  * proc1: destroy import
931  *        class_disconnect_export(grab cl_sem) ->
932  *              -> ldlm_namespace_free ->
933  *              -> lprocfs_remove(grab _lprocfs_lock).
934  * proc2: read proc info
935  *        lprocfs_fops_read(grab _lprocfs_lock) ->
936  *              -> osc_rd_active, etc(grab cl_sem).
937  *
938  * So that I have to split the ldlm_namespace_free into two parts - the first
939  * part ldlm_namespace_free_prior is used to cleanup the resource which is
940  * being used; the 2nd part ldlm_namespace_free_post is used to unregister the
941  * lprocfs entries, and then free memory. It will be called w/o cli->cl_sem
942  * held.
943  */
944 void ldlm_namespace_free(struct ldlm_namespace *ns,
945                          struct obd_import *imp,
946                          int force)
947 {
948         ldlm_namespace_free_prior(ns, imp, force);
949         ldlm_namespace_free_post(ns);
950 }
951 EXPORT_SYMBOL(ldlm_namespace_free);
952
953 void ldlm_namespace_get(struct ldlm_namespace *ns)
954 {
955         atomic_inc(&ns->ns_bref);
956 }
957 EXPORT_SYMBOL(ldlm_namespace_get);
958
959 /* This is only for callers that care about refcount */
960 int ldlm_namespace_get_return(struct ldlm_namespace *ns)
961 {
962         return atomic_inc_return(&ns->ns_bref);
963 }
964
965 void ldlm_namespace_put(struct ldlm_namespace *ns)
966 {
967         if (atomic_dec_and_lock(&ns->ns_bref, &ns->ns_lock)) {
968                 wake_up(&ns->ns_waitq);
969                 spin_unlock(&ns->ns_lock);
970         }
971 }
972 EXPORT_SYMBOL(ldlm_namespace_put);
973
974 /** Register \a ns in the list of namespaces */
975 void ldlm_namespace_register(struct ldlm_namespace *ns, ldlm_side_t client)
976 {
977         mutex_lock(ldlm_namespace_lock(client));
978         LASSERT(cfs_list_empty(&ns->ns_list_chain));
979         cfs_list_add(&ns->ns_list_chain, ldlm_namespace_inactive_list(client));
980         ldlm_namespace_nr_inc(client);
981         mutex_unlock(ldlm_namespace_lock(client));
982 }
983
984 /** Unregister \a ns from the list of namespaces. */
985 void ldlm_namespace_unregister(struct ldlm_namespace *ns, ldlm_side_t client)
986 {
987         mutex_lock(ldlm_namespace_lock(client));
988         LASSERT(!cfs_list_empty(&ns->ns_list_chain));
989         /* Some asserts and possibly other parts of the code are still
990          * using list_empty(&ns->ns_list_chain). This is why it is
991          * important to use list_del_init() here. */
992         cfs_list_del_init(&ns->ns_list_chain);
993         ldlm_namespace_nr_dec(client);
994         mutex_unlock(ldlm_namespace_lock(client));
995 }
996
997 /** Should be called with ldlm_namespace_lock(client) taken. */
998 void ldlm_namespace_move_to_active_locked(struct ldlm_namespace *ns,
999                                        ldlm_side_t client)
1000 {
1001         LASSERT(!cfs_list_empty(&ns->ns_list_chain));
1002         LASSERT(mutex_is_locked(ldlm_namespace_lock(client)));
1003         cfs_list_move_tail(&ns->ns_list_chain, ldlm_namespace_list(client));
1004 }
1005
1006 /** Should be called with ldlm_namespace_lock(client) taken. */
1007 void ldlm_namespace_move_to_inactive_locked(struct ldlm_namespace *ns,
1008                                          ldlm_side_t client)
1009 {
1010         LASSERT(!cfs_list_empty(&ns->ns_list_chain));
1011         LASSERT(mutex_is_locked(ldlm_namespace_lock(client)));
1012         cfs_list_move_tail(&ns->ns_list_chain,
1013                            ldlm_namespace_inactive_list(client));
1014 }
1015
1016 /** Should be called with ldlm_namespace_lock(client) taken. */
1017 struct ldlm_namespace *ldlm_namespace_first_locked(ldlm_side_t client)
1018 {
1019         LASSERT(mutex_is_locked(ldlm_namespace_lock(client)));
1020         LASSERT(!cfs_list_empty(ldlm_namespace_list(client)));
1021         return container_of(ldlm_namespace_list(client)->next,
1022                             struct ldlm_namespace, ns_list_chain);
1023 }
1024
1025 /** Create and initialize new resource. */
1026 static struct ldlm_resource *ldlm_resource_new(void)
1027 {
1028         struct ldlm_resource *res;
1029         int idx;
1030
1031         OBD_SLAB_ALLOC_PTR_GFP(res, ldlm_resource_slab, __GFP_IO);
1032         if (res == NULL)
1033                 return NULL;
1034
1035         CFS_INIT_LIST_HEAD(&res->lr_granted);
1036         CFS_INIT_LIST_HEAD(&res->lr_converting);
1037         CFS_INIT_LIST_HEAD(&res->lr_waiting);
1038
1039         /* Initialize interval trees for each lock mode. */
1040         for (idx = 0; idx < LCK_MODE_NUM; idx++) {
1041                 res->lr_itree[idx].lit_size = 0;
1042                 res->lr_itree[idx].lit_mode = 1 << idx;
1043                 res->lr_itree[idx].lit_root = NULL;
1044         }
1045
1046         atomic_set(&res->lr_refcount, 1);
1047         spin_lock_init(&res->lr_lock);
1048         lu_ref_init(&res->lr_reference);
1049
1050         /* The creator of the resource must unlock the mutex after LVB
1051          * initialization. */
1052         mutex_init(&res->lr_lvb_mutex);
1053         mutex_lock(&res->lr_lvb_mutex);
1054
1055         return res;
1056 }
1057
1058 /**
1059  * Return a reference to resource with given name, creating it if necessary.
1060  * Args: namespace with ns_lock unlocked
1061  * Locks: takes and releases NS hash-lock and res->lr_lock
1062  * Returns: referenced, unlocked ldlm_resource or NULL
1063  */
1064 struct ldlm_resource *
1065 ldlm_resource_get(struct ldlm_namespace *ns, struct ldlm_resource *parent,
1066                   const struct ldlm_res_id *name, ldlm_type_t type, int create)
1067 {
1068         cfs_hlist_node_t     *hnode;
1069         struct ldlm_resource *res;
1070         cfs_hash_bd_t         bd;
1071         __u64                 version;
1072         int                   ns_refcount = 0;
1073
1074         LASSERT(ns != NULL);
1075         LASSERT(parent == NULL);
1076         LASSERT(ns->ns_rs_hash != NULL);
1077         LASSERT(name->name[0] != 0);
1078
1079         cfs_hash_bd_get_and_lock(ns->ns_rs_hash, (void *)name, &bd, 0);
1080         hnode = cfs_hash_bd_lookup_locked(ns->ns_rs_hash, &bd, (void *)name);
1081         if (hnode != NULL) {
1082                 cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 0);
1083                 res = cfs_hlist_entry(hnode, struct ldlm_resource, lr_hash);
1084                 /* Synchronize with regard to resource creation. */
1085                 if (ns->ns_lvbo && ns->ns_lvbo->lvbo_init) {
1086                         mutex_lock(&res->lr_lvb_mutex);
1087                         mutex_unlock(&res->lr_lvb_mutex);
1088                 }
1089
1090                 if (unlikely(res->lr_lvb_len < 0)) {
1091                         ldlm_resource_putref(res);
1092                         res = NULL;
1093                 }
1094                 return res;
1095         }
1096
1097         version = cfs_hash_bd_version_get(&bd);
1098         cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 0);
1099
1100         if (create == 0)
1101                 return NULL;
1102
1103         LASSERTF(type >= LDLM_MIN_TYPE && type < LDLM_MAX_TYPE,
1104                  "type: %d\n", type);
1105         res = ldlm_resource_new();
1106         if (!res)
1107                 return NULL;
1108
1109         res->lr_ns_bucket  = cfs_hash_bd_extra_get(ns->ns_rs_hash, &bd);
1110         res->lr_name       = *name;
1111         res->lr_type       = type;
1112         res->lr_most_restr = LCK_NL;
1113
1114         cfs_hash_bd_lock(ns->ns_rs_hash, &bd, 1);
1115         hnode = (version == cfs_hash_bd_version_get(&bd)) ?  NULL :
1116                 cfs_hash_bd_lookup_locked(ns->ns_rs_hash, &bd, (void *)name);
1117
1118         if (hnode != NULL) {
1119                 /* Someone won the race and already added the resource. */
1120                 cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 1);
1121                 /* Clean lu_ref for failed resource. */
1122                 lu_ref_fini(&res->lr_reference);
1123                 /* We have taken lr_lvb_mutex. Drop it. */
1124                 mutex_unlock(&res->lr_lvb_mutex);
1125                 OBD_SLAB_FREE(res, ldlm_resource_slab, sizeof *res);
1126
1127                 res = cfs_hlist_entry(hnode, struct ldlm_resource, lr_hash);
1128                 /* Synchronize with regard to resource creation. */
1129                 if (ns->ns_lvbo && ns->ns_lvbo->lvbo_init) {
1130                         mutex_lock(&res->lr_lvb_mutex);
1131                         mutex_unlock(&res->lr_lvb_mutex);
1132                 }
1133
1134                 if (unlikely(res->lr_lvb_len < 0)) {
1135                         ldlm_resource_putref(res);
1136                         res = NULL;
1137                 }
1138                 return res;
1139         }
1140         /* We won! Let's add the resource. */
1141         cfs_hash_bd_add_locked(ns->ns_rs_hash, &bd, &res->lr_hash);
1142         if (cfs_hash_bd_count_get(&bd) == 1)
1143                 ns_refcount = ldlm_namespace_get_return(ns);
1144
1145         cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 1);
1146         if (ns->ns_lvbo && ns->ns_lvbo->lvbo_init) {
1147                 int rc;
1148
1149                 OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_CREATE_RESOURCE, 2);
1150                 rc = ns->ns_lvbo->lvbo_init(res);
1151                 if (rc < 0) {
1152                         CERROR("%s: lvbo_init failed for resource "LPX64":"
1153                                LPX64": rc = %d\n", ns->ns_obd->obd_name,
1154                                name->name[0], name->name[1], rc);
1155                         if (res->lr_lvb_data) {
1156                                 OBD_FREE(res->lr_lvb_data, res->lr_lvb_len);
1157                                 res->lr_lvb_data = NULL;
1158                         }
1159                         res->lr_lvb_len = rc;
1160                         mutex_unlock(&res->lr_lvb_mutex);
1161                         ldlm_resource_putref(res);
1162                         return NULL;
1163                 }
1164         }
1165
1166         /* We create resource with locked lr_lvb_mutex. */
1167         mutex_unlock(&res->lr_lvb_mutex);
1168
1169         /* Let's see if we happened to be the very first resource in this
1170          * namespace. If so, and this is a client namespace, we need to move
1171          * the namespace into the active namespaces list to be patrolled by
1172          * the ldlm_poold. */
1173         if (ns_is_client(ns) && ns_refcount == 1) {
1174                 mutex_lock(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
1175                 ldlm_namespace_move_to_active_locked(ns, LDLM_NAMESPACE_CLIENT);
1176                 mutex_unlock(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
1177         }
1178
1179         return res;
1180 }
1181 EXPORT_SYMBOL(ldlm_resource_get);
1182
1183 struct ldlm_resource *ldlm_resource_getref(struct ldlm_resource *res)
1184 {
1185         LASSERT(res != NULL);
1186         LASSERT(res != LP_POISON);
1187         atomic_inc(&res->lr_refcount);
1188         CDEBUG(D_INFO, "getref res: %p count: %d\n", res,
1189                atomic_read(&res->lr_refcount));
1190         return res;
1191 }
1192
1193 static void __ldlm_resource_putref_final(cfs_hash_bd_t *bd,
1194                                          struct ldlm_resource *res)
1195 {
1196         struct ldlm_ns_bucket *nsb = res->lr_ns_bucket;
1197
1198         if (!cfs_list_empty(&res->lr_granted)) {
1199                 ldlm_resource_dump(D_ERROR, res);
1200                 LBUG();
1201         }
1202
1203         if (!cfs_list_empty(&res->lr_converting)) {
1204                 ldlm_resource_dump(D_ERROR, res);
1205                 LBUG();
1206         }
1207
1208         if (!cfs_list_empty(&res->lr_waiting)) {
1209                 ldlm_resource_dump(D_ERROR, res);
1210                 LBUG();
1211         }
1212
1213         cfs_hash_bd_del_locked(nsb->nsb_namespace->ns_rs_hash,
1214                                bd, &res->lr_hash);
1215         lu_ref_fini(&res->lr_reference);
1216         if (cfs_hash_bd_count_get(bd) == 0)
1217                 ldlm_namespace_put(nsb->nsb_namespace);
1218 }
1219
1220 /* Returns 1 if the resource was freed, 0 if it remains. */
1221 int ldlm_resource_putref(struct ldlm_resource *res)
1222 {
1223         struct ldlm_namespace *ns = ldlm_res_to_ns(res);
1224         cfs_hash_bd_t   bd;
1225
1226         LASSERT_ATOMIC_GT_LT(&res->lr_refcount, 0, LI_POISON);
1227         CDEBUG(D_INFO, "putref res: %p count: %d\n",
1228                res, atomic_read(&res->lr_refcount) - 1);
1229
1230         cfs_hash_bd_get(ns->ns_rs_hash, &res->lr_name, &bd);
1231         if (cfs_hash_bd_dec_and_lock(ns->ns_rs_hash, &bd, &res->lr_refcount)) {
1232                 __ldlm_resource_putref_final(&bd, res);
1233                 cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 1);
1234                 if (ns->ns_lvbo && ns->ns_lvbo->lvbo_free)
1235                         ns->ns_lvbo->lvbo_free(res);
1236                 OBD_SLAB_FREE(res, ldlm_resource_slab, sizeof *res);
1237                 return 1;
1238         }
1239         return 0;
1240 }
1241 EXPORT_SYMBOL(ldlm_resource_putref);
1242
1243 /* Returns 1 if the resource was freed, 0 if it remains. */
1244 int ldlm_resource_putref_locked(struct ldlm_resource *res)
1245 {
1246         struct ldlm_namespace *ns = ldlm_res_to_ns(res);
1247
1248         LASSERT_ATOMIC_GT_LT(&res->lr_refcount, 0, LI_POISON);
1249         CDEBUG(D_INFO, "putref res: %p count: %d\n",
1250                res, atomic_read(&res->lr_refcount) - 1);
1251
1252         if (atomic_dec_and_test(&res->lr_refcount)) {
1253                 cfs_hash_bd_t bd;
1254
1255                 cfs_hash_bd_get(ldlm_res_to_ns(res)->ns_rs_hash,
1256                                 &res->lr_name, &bd);
1257                 __ldlm_resource_putref_final(&bd, res);
1258                 cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 1);
1259                 /* NB: ns_rs_hash is created with CFS_HASH_NO_ITEMREF,
1260                  * so we should never be here while calling cfs_hash_del,
1261                  * cfs_hash_for_each_nolock is the only case we can get
1262                  * here, which is safe to release cfs_hash_bd_lock.
1263                  */
1264                 if (ns->ns_lvbo && ns->ns_lvbo->lvbo_free)
1265                         ns->ns_lvbo->lvbo_free(res);
1266                 OBD_SLAB_FREE(res, ldlm_resource_slab, sizeof *res);
1267
1268                 cfs_hash_bd_lock(ns->ns_rs_hash, &bd, 1);
1269                 return 1;
1270         }
1271         return 0;
1272 }
1273
1274 /**
1275  * Add a lock into a given resource into specified lock list.
1276  */
1277 void ldlm_resource_add_lock(struct ldlm_resource *res, cfs_list_t *head,
1278                             struct ldlm_lock *lock)
1279 {
1280         check_res_locked(res);
1281
1282         LDLM_DEBUG(lock, "About to add this lock:\n");
1283
1284         if (ldlm_is_destroyed(lock)) {
1285                 CDEBUG(D_OTHER, "Lock destroyed, not adding to resource\n");
1286                 return;
1287         }
1288
1289         LASSERT(cfs_list_empty(&lock->l_res_link));
1290
1291         cfs_list_add_tail(&lock->l_res_link, head);
1292 }
1293
1294 /**
1295  * Insert a lock into resource after specified lock.
1296  *
1297  * Obtain resource description from the lock we are inserting after.
1298  */
1299 void ldlm_resource_insert_lock_after(struct ldlm_lock *original,
1300                                      struct ldlm_lock *new)
1301 {
1302         struct ldlm_resource *res = original->l_resource;
1303
1304         check_res_locked(res);
1305
1306         ldlm_resource_dump(D_INFO, res);
1307         LDLM_DEBUG(new, "About to insert this lock after %p:\n", original);
1308
1309         if (ldlm_is_destroyed(new)) {
1310                 CDEBUG(D_OTHER, "Lock destroyed, not adding to resource\n");
1311                 goto out;
1312         }
1313
1314         LASSERT(cfs_list_empty(&new->l_res_link));
1315
1316         cfs_list_add(&new->l_res_link, &original->l_res_link);
1317  out:;
1318 }
1319
1320 void ldlm_resource_unlink_lock(struct ldlm_lock *lock)
1321 {
1322         int type = lock->l_resource->lr_type;
1323
1324         check_res_locked(lock->l_resource);
1325         if (type == LDLM_IBITS || type == LDLM_PLAIN)
1326                 ldlm_unlink_lock_skiplist(lock);
1327         else if (type == LDLM_EXTENT)
1328                 ldlm_extent_unlink_lock(lock);
1329         cfs_list_del_init(&lock->l_res_link);
1330 }
1331 EXPORT_SYMBOL(ldlm_resource_unlink_lock);
1332
1333 void ldlm_res2desc(struct ldlm_resource *res, struct ldlm_resource_desc *desc)
1334 {
1335         desc->lr_type = res->lr_type;
1336         desc->lr_name = res->lr_name;
1337 }
1338
1339 /**
1340  * Print information about all locks in all namespaces on this node to debug
1341  * log.
1342  */
1343 void ldlm_dump_all_namespaces(ldlm_side_t client, int level)
1344 {
1345         cfs_list_t *tmp;
1346
1347         if (!((libcfs_debug | D_ERROR) & level))
1348                 return;
1349
1350         mutex_lock(ldlm_namespace_lock(client));
1351
1352         cfs_list_for_each(tmp, ldlm_namespace_list(client)) {
1353                 struct ldlm_namespace *ns;
1354                 ns = cfs_list_entry(tmp, struct ldlm_namespace, ns_list_chain);
1355                 ldlm_namespace_dump(level, ns);
1356         }
1357
1358         mutex_unlock(ldlm_namespace_lock(client));
1359 }
1360 EXPORT_SYMBOL(ldlm_dump_all_namespaces);
1361
1362 static int ldlm_res_hash_dump(cfs_hash_t *hs, cfs_hash_bd_t *bd,
1363                               cfs_hlist_node_t *hnode, void *arg)
1364 {
1365         struct ldlm_resource *res = cfs_hash_object(hs, hnode);
1366         int    level = (int)(unsigned long)arg;
1367
1368         lock_res(res);
1369         ldlm_resource_dump(level, res);
1370         unlock_res(res);
1371
1372         return 0;
1373 }
1374
1375 /**
1376  * Print information about all locks in this namespace on this node to debug
1377  * log.
1378  */
1379 void ldlm_namespace_dump(int level, struct ldlm_namespace *ns)
1380 {
1381         if (!((libcfs_debug | D_ERROR) & level))
1382                 return;
1383
1384         CDEBUG(level, "--- Namespace: %s (rc: %d, side: %s)\n",
1385                ldlm_ns_name(ns), atomic_read(&ns->ns_bref),
1386                ns_is_client(ns) ? "client" : "server");
1387
1388         if (cfs_time_before(cfs_time_current(), ns->ns_next_dump))
1389                 return;
1390
1391         cfs_hash_for_each_nolock(ns->ns_rs_hash,
1392                                  ldlm_res_hash_dump,
1393                                  (void *)(unsigned long)level);
1394         spin_lock(&ns->ns_lock);
1395         ns->ns_next_dump = cfs_time_shift(10);
1396         spin_unlock(&ns->ns_lock);
1397 }
1398 EXPORT_SYMBOL(ldlm_namespace_dump);
1399
1400 /**
1401  * Print information about all locks in this resource to debug log.
1402  */
1403 void ldlm_resource_dump(int level, struct ldlm_resource *res)
1404 {
1405         struct ldlm_lock *lock;
1406         unsigned int granted = 0;
1407
1408         CLASSERT(RES_NAME_SIZE == 4);
1409
1410         if (!((libcfs_debug | D_ERROR) & level))
1411                 return;
1412
1413         CDEBUG(level, "--- Resource: "DLDLMRES" (%p) refcount = %d\n",
1414                PLDLMRES(res), res, atomic_read(&res->lr_refcount));
1415
1416         if (!cfs_list_empty(&res->lr_granted)) {
1417                 CDEBUG(level, "Granted locks (in reverse order):\n");
1418                 cfs_list_for_each_entry_reverse(lock, &res->lr_granted,
1419                                                 l_res_link) {
1420                         LDLM_DEBUG_LIMIT(level, lock, "###");
1421                         if (!(level & D_CANTMASK) &&
1422                             ++granted > ldlm_dump_granted_max) {
1423                                 CDEBUG(level, "only dump %d granted locks to "
1424                                        "avoid DDOS.\n", granted);
1425                                 break;
1426                         }
1427                 }
1428         }
1429         if (!cfs_list_empty(&res->lr_converting)) {
1430                 CDEBUG(level, "Converting locks:\n");
1431                 cfs_list_for_each_entry(lock, &res->lr_converting, l_res_link)
1432                         LDLM_DEBUG_LIMIT(level, lock, "###");
1433         }
1434         if (!cfs_list_empty(&res->lr_waiting)) {
1435                 CDEBUG(level, "Waiting locks:\n");
1436                 cfs_list_for_each_entry(lock, &res->lr_waiting, l_res_link)
1437                         LDLM_DEBUG_LIMIT(level, lock, "###");
1438         }
1439 }