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