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