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