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