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