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