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