Whamcloud - gitweb
LU-147 hash code cleanup
[fs/lustre-release.git] / lustre / ldlm / ldlm_lockd.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
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_lockd.c
37  *
38  * Author: Peter Braam <braam@clusterfs.com>
39  * Author: Phil Schwan <phil@clusterfs.com>
40  */
41
42 #ifndef EXPORT_SYMTAB
43 # define EXPORT_SYMTAB
44 #endif
45 #define DEBUG_SUBSYSTEM S_LDLM
46
47 #ifdef __KERNEL__
48 # include <libcfs/libcfs.h>
49 #else
50 # include <liblustre.h>
51 #endif
52
53 #include <lustre_dlm.h>
54 #include <obd_class.h>
55 #include <libcfs/list.h>
56 #include "ldlm_internal.h"
57
58 #ifdef __KERNEL__
59 static int ldlm_num_threads;
60 CFS_MODULE_PARM(ldlm_num_threads, "i", int, 0444,
61                 "number of DLM service threads to start");
62 #endif
63
64 extern cfs_mem_cache_t *ldlm_resource_slab;
65 extern cfs_mem_cache_t *ldlm_lock_slab;
66 static cfs_semaphore_t  ldlm_ref_sem;
67 static int ldlm_refcount;
68
69 struct ldlm_cb_async_args {
70         struct ldlm_cb_set_arg *ca_set_arg;
71         struct ldlm_lock       *ca_lock;
72 };
73
74 /* LDLM state */
75
76 static struct ldlm_state *ldlm_state;
77
78 inline cfs_time_t round_timeout(cfs_time_t timeout)
79 {
80         return cfs_time_seconds((int)cfs_duration_sec(cfs_time_sub(timeout, 0)) + 1);
81 }
82
83 /* timeout for initial callback (AST) reply (bz10399) */
84 static inline unsigned int ldlm_get_rq_timeout(void)
85 {
86         /* Non-AT value */
87         unsigned int timeout = min(ldlm_timeout, obd_timeout / 3);
88
89         return timeout < 1 ? 1 : timeout;
90 }
91
92 #ifdef __KERNEL__
93 /* w_l_spinlock protects both waiting_locks_list and expired_lock_thread */
94 static cfs_spinlock_t waiting_locks_spinlock;   /* BH lock (timer) */
95 static cfs_list_t waiting_locks_list;
96 static cfs_timer_t waiting_locks_timer;
97
98 static struct expired_lock_thread {
99         cfs_waitq_t               elt_waitq;
100         int                       elt_state;
101         int                       elt_dump;
102         cfs_list_t                elt_expired_locks;
103 } expired_lock_thread;
104 #endif
105
106 #define ELT_STOPPED   0
107 #define ELT_READY     1
108 #define ELT_TERMINATE 2
109
110 struct ldlm_bl_pool {
111         cfs_spinlock_t          blp_lock;
112
113         /*
114          * blp_prio_list is used for callbacks that should be handled
115          * as a priority. It is used for LDLM_FL_DISCARD_DATA requests.
116          * see bug 13843
117          */
118         cfs_list_t              blp_prio_list;
119
120         /*
121          * blp_list is used for all other callbacks which are likely
122          * to take longer to process.
123          */
124         cfs_list_t              blp_list;
125
126         cfs_waitq_t             blp_waitq;
127         cfs_completion_t        blp_comp;
128         cfs_atomic_t            blp_num_threads;
129         cfs_atomic_t            blp_busy_threads;
130         int                     blp_min_threads;
131         int                     blp_max_threads;
132 };
133
134 struct ldlm_bl_work_item {
135         cfs_list_t              blwi_entry;
136         struct ldlm_namespace  *blwi_ns;
137         struct ldlm_lock_desc   blwi_ld;
138         struct ldlm_lock       *blwi_lock;
139         cfs_list_t              blwi_head;
140         int                     blwi_count;
141         cfs_completion_t        blwi_comp;
142         int                     blwi_mode;
143         int                     blwi_mem_pressure;
144 };
145
146 #ifdef __KERNEL__
147
148 static inline int have_expired_locks(void)
149 {
150         int need_to_run;
151
152         ENTRY;
153         cfs_spin_lock_bh(&waiting_locks_spinlock);
154         need_to_run = !cfs_list_empty(&expired_lock_thread.elt_expired_locks);
155         cfs_spin_unlock_bh(&waiting_locks_spinlock);
156
157         RETURN(need_to_run);
158 }
159
160 static int expired_lock_main(void *arg)
161 {
162         cfs_list_t *expired = &expired_lock_thread.elt_expired_locks;
163         struct l_wait_info lwi = { 0 };
164         int do_dump;
165
166         ENTRY;
167         cfs_daemonize("ldlm_elt");
168
169         expired_lock_thread.elt_state = ELT_READY;
170         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
171
172         while (1) {
173                 l_wait_event(expired_lock_thread.elt_waitq,
174                              have_expired_locks() ||
175                              expired_lock_thread.elt_state == ELT_TERMINATE,
176                              &lwi);
177
178                 cfs_spin_lock_bh(&waiting_locks_spinlock);
179                 if (expired_lock_thread.elt_dump) {
180                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
181
182                         /* from waiting_locks_callback, but not in timer */
183                         libcfs_debug_dumplog();
184                         libcfs_run_lbug_upcall(__FILE__,
185                                                 "waiting_locks_callback",
186                                                 expired_lock_thread.elt_dump);
187
188                         cfs_spin_lock_bh(&waiting_locks_spinlock);
189                         expired_lock_thread.elt_dump = 0;
190                 }
191
192                 do_dump = 0;
193
194                 while (!cfs_list_empty(expired)) {
195                         struct obd_export *export;
196                         struct ldlm_lock *lock;
197
198                         lock = cfs_list_entry(expired->next, struct ldlm_lock,
199                                           l_pending_chain);
200                         if ((void *)lock < LP_POISON + CFS_PAGE_SIZE &&
201                             (void *)lock >= LP_POISON) {
202                                 cfs_spin_unlock_bh(&waiting_locks_spinlock);
203                                 CERROR("free lock on elt list %p\n", lock);
204                                 LBUG();
205                         }
206                         cfs_list_del_init(&lock->l_pending_chain);
207                         if ((void *)lock->l_export < LP_POISON + CFS_PAGE_SIZE &&
208                             (void *)lock->l_export >= LP_POISON) {
209                                 CERROR("lock with free export on elt list %p\n",
210                                        lock->l_export);
211                                 lock->l_export = NULL;
212                                 LDLM_ERROR(lock, "free export");
213                                 /* release extra ref grabbed by
214                                  * ldlm_add_waiting_lock() or
215                                  * ldlm_failed_ast() */
216                                 LDLM_LOCK_RELEASE(lock);
217                                 continue;
218                         }
219                         export = class_export_lock_get(lock->l_export, lock);
220                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
221
222                         do_dump++;
223                         class_fail_export(export);
224                         class_export_lock_put(export, lock);
225
226                         /* release extra ref grabbed by ldlm_add_waiting_lock()
227                          * or ldlm_failed_ast() */
228                         LDLM_LOCK_RELEASE(lock);
229
230                         cfs_spin_lock_bh(&waiting_locks_spinlock);
231                 }
232                 cfs_spin_unlock_bh(&waiting_locks_spinlock);
233
234                 if (do_dump && obd_dump_on_eviction) {
235                         CERROR("dump the log upon eviction\n");
236                         libcfs_debug_dumplog();
237                 }
238
239                 if (expired_lock_thread.elt_state == ELT_TERMINATE)
240                         break;
241         }
242
243         expired_lock_thread.elt_state = ELT_STOPPED;
244         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
245         RETURN(0);
246 }
247
248 static int ldlm_add_waiting_lock(struct ldlm_lock *lock);
249
250 /**
251  * Check if there is a request in the export request list
252  * which prevents the lock canceling.
253  */
254 static int ldlm_lock_busy(struct ldlm_lock *lock)
255 {
256         struct ptlrpc_request *req;
257         int match = 0;
258         ENTRY;
259
260         if (lock->l_export == NULL)
261                 return 0;
262
263         cfs_spin_lock_bh(&lock->l_export->exp_rpc_lock);
264         cfs_list_for_each_entry(req, &lock->l_export->exp_queued_rpc,
265                                 rq_exp_list) {
266                 if (req->rq_ops->hpreq_lock_match) {
267                         match = req->rq_ops->hpreq_lock_match(req, lock);
268                         if (match)
269                                 break;
270                 }
271         }
272         cfs_spin_unlock_bh(&lock->l_export->exp_rpc_lock);
273         RETURN(match);
274 }
275
276 /* This is called from within a timer interrupt and cannot schedule */
277 static void waiting_locks_callback(unsigned long unused)
278 {
279         struct ldlm_lock *lock, *last = NULL;
280
281 repeat:
282         cfs_spin_lock_bh(&waiting_locks_spinlock);
283         while (!cfs_list_empty(&waiting_locks_list)) {
284                 lock = cfs_list_entry(waiting_locks_list.next, struct ldlm_lock,
285                                       l_pending_chain);
286                 if (cfs_time_after(lock->l_callback_timeout,
287                                    cfs_time_current()) ||
288                     (lock->l_req_mode == LCK_GROUP))
289                         break;
290
291                 if (ptlrpc_check_suspend()) {
292                         /* there is a case when we talk to one mds, holding
293                          * lock from another mds. this way we easily can get
294                          * here, if second mds is being recovered. so, we
295                          * suspend timeouts. bug 6019 */
296
297                         LDLM_ERROR(lock, "recharge timeout: %s@%s nid %s ",
298                                    lock->l_export->exp_client_uuid.uuid,
299                                    lock->l_export->exp_connection->c_remote_uuid.uuid,
300                                    libcfs_nid2str(lock->l_export->exp_connection->c_peer.nid));
301
302                         cfs_list_del_init(&lock->l_pending_chain);
303                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
304                         ldlm_add_waiting_lock(lock);
305                         goto repeat;
306                 }
307
308                 /* if timeout overlaps the activation time of suspended timeouts
309                  * then extend it to give a chance for client to reconnect */
310                 if (cfs_time_before(cfs_time_sub(lock->l_callback_timeout,
311                                                  cfs_time_seconds(obd_timeout)/2),
312                                     ptlrpc_suspend_wakeup_time())) {
313                         LDLM_ERROR(lock, "extend timeout due to recovery: %s@%s nid %s ",
314                                    lock->l_export->exp_client_uuid.uuid,
315                                    lock->l_export->exp_connection->c_remote_uuid.uuid,
316                                    libcfs_nid2str(lock->l_export->exp_connection->c_peer.nid));
317
318                         cfs_list_del_init(&lock->l_pending_chain);
319                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
320                         ldlm_add_waiting_lock(lock);
321                         goto repeat;
322                 }
323
324                 /* Check if we need to prolong timeout */
325                 if (!OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT) &&
326                     ldlm_lock_busy(lock)) {
327                         int cont = 1;
328
329                         if (lock->l_pending_chain.next == &waiting_locks_list)
330                                 cont = 0;
331
332                         LDLM_LOCK_GET(lock);
333
334                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
335                         LDLM_DEBUG(lock, "prolong the busy lock");
336                         ldlm_refresh_waiting_lock(lock,
337                                                   ldlm_get_enq_timeout(lock));
338                         cfs_spin_lock_bh(&waiting_locks_spinlock);
339
340                         if (!cont) {
341                                 LDLM_LOCK_RELEASE(lock);
342                                 break;
343                         }
344
345                         LDLM_LOCK_RELEASE(lock);
346                         continue;
347                 }
348                 ldlm_lock_to_ns(lock)->ns_timeouts++;
349                 LDLM_ERROR(lock, "lock callback timer expired after %lds: "
350                            "evicting client at %s ",
351                            cfs_time_current_sec()- lock->l_last_activity,
352                            libcfs_nid2str(
353                                    lock->l_export->exp_connection->c_peer.nid));
354
355                 last = lock;
356
357                 /* no needs to take an extra ref on the lock since it was in
358                  * the waiting_locks_list and ldlm_add_waiting_lock()
359                  * already grabbed a ref */
360                 cfs_list_del(&lock->l_pending_chain);
361                 cfs_list_add(&lock->l_pending_chain,
362                              &expired_lock_thread.elt_expired_locks);
363         }
364
365         if (!cfs_list_empty(&expired_lock_thread.elt_expired_locks)) {
366                 if (obd_dump_on_timeout)
367                         expired_lock_thread.elt_dump = __LINE__;
368
369                 cfs_waitq_signal(&expired_lock_thread.elt_waitq);
370         }
371
372         /*
373          * Make sure the timer will fire again if we have any locks
374          * left.
375          */
376         if (!cfs_list_empty(&waiting_locks_list)) {
377                 cfs_time_t timeout_rounded;
378                 lock = cfs_list_entry(waiting_locks_list.next, struct ldlm_lock,
379                                       l_pending_chain);
380                 timeout_rounded = (cfs_time_t)round_timeout(lock->l_callback_timeout);
381                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
382         }
383         cfs_spin_unlock_bh(&waiting_locks_spinlock);
384 }
385
386 /*
387  * Indicate that we're waiting for a client to call us back cancelling a given
388  * lock.  We add it to the pending-callback chain, and schedule the lock-timeout
389  * timer to fire appropriately.  (We round up to the next second, to avoid
390  * floods of timer firings during periods of high lock contention and traffic).
391  * As done by ldlm_add_waiting_lock(), the caller must grab a lock reference
392  * if it has been added to the waiting list (1 is returned).
393  *
394  * Called with the namespace lock held.
395  */
396 static int __ldlm_add_waiting_lock(struct ldlm_lock *lock, int seconds)
397 {
398         cfs_time_t timeout;
399         cfs_time_t timeout_rounded;
400
401         if (!cfs_list_empty(&lock->l_pending_chain))
402                 return 0;
403
404         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT) ||
405             OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
406                 seconds = 1;
407
408         timeout = cfs_time_shift(seconds);
409         if (likely(cfs_time_after(timeout, lock->l_callback_timeout)))
410                 lock->l_callback_timeout = timeout;
411
412         timeout_rounded = round_timeout(lock->l_callback_timeout);
413
414         if (cfs_time_before(timeout_rounded,
415                             cfs_timer_deadline(&waiting_locks_timer)) ||
416             !cfs_timer_is_armed(&waiting_locks_timer)) {
417                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
418         }
419         /* if the new lock has a shorter timeout than something earlier on
420            the list, we'll wait the longer amount of time; no big deal. */
421         /* FIFO */
422         cfs_list_add_tail(&lock->l_pending_chain, &waiting_locks_list);
423         return 1;
424 }
425
426 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
427 {
428         int ret;
429         int timeout = ldlm_get_enq_timeout(lock);
430
431         LASSERT(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK));
432
433         cfs_spin_lock_bh(&waiting_locks_spinlock);
434         if (lock->l_destroyed) {
435                 static cfs_time_t next;
436                 cfs_spin_unlock_bh(&waiting_locks_spinlock);
437                 LDLM_ERROR(lock, "not waiting on destroyed lock (bug 5653)");
438                 if (cfs_time_after(cfs_time_current(), next)) {
439                         next = cfs_time_shift(14400);
440                         libcfs_debug_dumpstack(NULL);
441                 }
442                 return 0;
443         }
444
445         ret = __ldlm_add_waiting_lock(lock, timeout);
446         if (ret)
447                 /* grab ref on the lock if it has been added to the
448                  * waiting list */
449                 LDLM_LOCK_GET(lock);
450         cfs_spin_unlock_bh(&waiting_locks_spinlock);
451
452         LDLM_DEBUG(lock, "%sadding to wait list(timeout: %d, AT: %s)",
453                    ret == 0 ? "not re-" : "", timeout,
454                    AT_OFF ? "off" : "on");
455         return ret;
456 }
457
458 /*
459  * Remove a lock from the pending list, likely because it had its cancellation
460  * callback arrive without incident.  This adjusts the lock-timeout timer if
461  * needed.  Returns 0 if the lock wasn't pending after all, 1 if it was.
462  * As done by ldlm_del_waiting_lock(), the caller must release the lock
463  * reference when the lock is removed from any list (1 is returned).
464  *
465  * Called with namespace lock held.
466  */
467 static int __ldlm_del_waiting_lock(struct ldlm_lock *lock)
468 {
469         cfs_list_t *list_next;
470
471         if (cfs_list_empty(&lock->l_pending_chain))
472                 return 0;
473
474         list_next = lock->l_pending_chain.next;
475         if (lock->l_pending_chain.prev == &waiting_locks_list) {
476                 /* Removing the head of the list, adjust timer. */
477                 if (list_next == &waiting_locks_list) {
478                         /* No more, just cancel. */
479                         cfs_timer_disarm(&waiting_locks_timer);
480                 } else {
481                         struct ldlm_lock *next;
482                         next = cfs_list_entry(list_next, struct ldlm_lock,
483                                               l_pending_chain);
484                         cfs_timer_arm(&waiting_locks_timer,
485                                       round_timeout(next->l_callback_timeout));
486                 }
487         }
488         cfs_list_del_init(&lock->l_pending_chain);
489
490         return 1;
491 }
492
493 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
494 {
495         int ret;
496
497         if (lock->l_export == NULL) {
498                 /* We don't have a "waiting locks list" on clients. */
499                 CDEBUG(D_DLMTRACE, "Client lock %p : no-op\n", lock);
500                 return 0;
501         }
502
503         cfs_spin_lock_bh(&waiting_locks_spinlock);
504         ret = __ldlm_del_waiting_lock(lock);
505         cfs_spin_unlock_bh(&waiting_locks_spinlock);
506         if (ret)
507                 /* release lock ref if it has indeed been removed
508                  * from a list */
509                 LDLM_LOCK_RELEASE(lock);
510
511         LDLM_DEBUG(lock, "%s", ret == 0 ? "wasn't waiting" : "removed");
512         return ret;
513 }
514
515 /*
516  * Prolong the lock
517  *
518  * Called with namespace lock held.
519  */
520 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock, int timeout)
521 {
522         if (lock->l_export == NULL) {
523                 /* We don't have a "waiting locks list" on clients. */
524                 LDLM_DEBUG(lock, "client lock: no-op");
525                 return 0;
526         }
527
528         cfs_spin_lock_bh(&waiting_locks_spinlock);
529
530         if (cfs_list_empty(&lock->l_pending_chain)) {
531                 cfs_spin_unlock_bh(&waiting_locks_spinlock);
532                 LDLM_DEBUG(lock, "wasn't waiting");
533                 return 0;
534         }
535
536         /* we remove/add the lock to the waiting list, so no needs to
537          * release/take a lock reference */
538         __ldlm_del_waiting_lock(lock);
539         __ldlm_add_waiting_lock(lock, timeout);
540         cfs_spin_unlock_bh(&waiting_locks_spinlock);
541
542         LDLM_DEBUG(lock, "refreshed");
543         return 1;
544 }
545 #else /* !__KERNEL__ */
546
547 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
548 {
549         LASSERT(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK));
550         RETURN(1);
551 }
552
553 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
554 {
555         RETURN(0);
556 }
557
558 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock, int timeout)
559 {
560         RETURN(0);
561 }
562 #endif /* __KERNEL__ */
563
564 static void ldlm_failed_ast(struct ldlm_lock *lock, int rc,
565                             const char *ast_type)
566 {
567         LCONSOLE_ERROR_MSG(0x138, "%s: A client on nid %s was evicted due "
568                            "to a lock %s callback time out: rc %d\n",
569                            lock->l_export->exp_obd->obd_name,
570                            obd_export_nid2str(lock->l_export), ast_type, rc);
571
572         if (obd_dump_on_timeout)
573                 libcfs_debug_dumplog();
574 #ifdef __KERNEL__
575         cfs_spin_lock_bh(&waiting_locks_spinlock);
576         if (__ldlm_del_waiting_lock(lock) == 0)
577                 /* the lock was not in any list, grab an extra ref before adding
578                  * the lock to the expired list */
579                 LDLM_LOCK_GET(lock);
580         cfs_list_add(&lock->l_pending_chain,
581                      &expired_lock_thread.elt_expired_locks);
582         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
583         cfs_spin_unlock_bh(&waiting_locks_spinlock);
584 #else
585         class_fail_export(lock->l_export);
586 #endif
587 }
588
589 static int ldlm_handle_ast_error(struct ldlm_lock *lock,
590                                  struct ptlrpc_request *req, int rc,
591                                  const char *ast_type)
592 {
593         lnet_process_id_t peer = req->rq_import->imp_connection->c_peer;
594
595         if (rc == -ETIMEDOUT || rc == -EINTR || rc == -ENOTCONN) {
596                 LASSERT(lock->l_export);
597                 if (lock->l_export->exp_libclient) {
598                         LDLM_DEBUG(lock, "%s AST to liblustre client (nid %s)"
599                                    " timeout, just cancelling lock", ast_type,
600                                    libcfs_nid2str(peer.nid));
601                         ldlm_lock_cancel(lock);
602                         rc = -ERESTART;
603                 } else if (lock->l_flags & LDLM_FL_CANCEL) {
604                         LDLM_DEBUG(lock, "%s AST timeout from nid %s, but "
605                                    "cancel was received (AST reply lost?)",
606                                    ast_type, libcfs_nid2str(peer.nid));
607                         ldlm_lock_cancel(lock);
608                         rc = -ERESTART;
609                 } else {
610                         ldlm_del_waiting_lock(lock);
611                         ldlm_failed_ast(lock, rc, ast_type);
612                 }
613         } else if (rc) {
614                 if (rc == -EINVAL) {
615                         struct ldlm_resource *res = lock->l_resource;
616                         LDLM_DEBUG(lock, "client (nid %s) returned %d"
617                                " from %s AST - normal race",
618                                libcfs_nid2str(peer.nid),
619                                req->rq_repmsg ?
620                                lustre_msg_get_status(req->rq_repmsg) : -1,
621                                ast_type);
622                         if (res) {
623                                 /* update lvbo to return proper attributes.
624                                  * see bug 23174 */
625                                 ldlm_resource_getref(res);
626                                 ldlm_res_lvbo_update(res, NULL, 1);
627                                 ldlm_resource_putref(res);
628                         }
629
630                 } else {
631                         LDLM_ERROR(lock, "client (nid %s) returned %d "
632                                    "from %s AST", libcfs_nid2str(peer.nid),
633                                    (req->rq_repmsg != NULL) ?
634                                    lustre_msg_get_status(req->rq_repmsg) : 0,
635                                    ast_type);
636                 }
637                 ldlm_lock_cancel(lock);
638                 /* Server-side AST functions are called from ldlm_reprocess_all,
639                  * which needs to be told to please restart its reprocessing. */
640                 rc = -ERESTART;
641         }
642
643         return rc;
644 }
645
646 static int ldlm_cb_interpret(const struct lu_env *env,
647                              struct ptlrpc_request *req, void *data, int rc)
648 {
649         struct ldlm_cb_async_args *ca = data;
650         struct ldlm_cb_set_arg *arg = ca->ca_set_arg;
651         struct ldlm_lock *lock = ca->ca_lock;
652         ENTRY;
653
654         LASSERT(lock != NULL);
655         if (rc != 0) {
656                 rc = ldlm_handle_ast_error(lock, req, rc,
657                                            arg->type == LDLM_BL_CALLBACK
658                                            ? "blocking" : "completion");
659         }
660
661         LDLM_LOCK_RELEASE(lock);
662
663         if (rc == -ERESTART)
664                 cfs_atomic_set(&arg->restart, 1);
665
666         RETURN(0);
667 }
668
669 static inline int ldlm_bl_and_cp_ast_fini(struct ptlrpc_request *req,
670                                           struct ldlm_cb_set_arg *arg,
671                                           struct ldlm_lock *lock,
672                                           int instant_cancel)
673 {
674         int rc = 0;
675         ENTRY;
676
677         if (unlikely(instant_cancel)) {
678                 rc = ptl_send_rpc(req, 1);
679                 ptlrpc_req_finished(req);
680                 if (rc == 0)
681                         /* If we cancelled the lock, we need to restart
682                          * ldlm_reprocess_queue */
683                         cfs_atomic_set(&arg->restart, 1);
684         } else {
685                 LDLM_LOCK_GET(lock);
686                 ptlrpc_set_add_req(arg->set, req);
687         }
688
689         RETURN(rc);
690 }
691
692 /**
693  * Check if there are requests in the export request list which prevent
694  * the lock canceling and make these requests high priority ones.
695  */
696 static void ldlm_lock_reorder_req(struct ldlm_lock *lock)
697 {
698         struct ptlrpc_request *req;
699         ENTRY;
700
701         if (lock->l_export == NULL) {
702                 LDLM_DEBUG(lock, "client lock: no-op");
703                 RETURN_EXIT;
704         }
705
706         cfs_spin_lock_bh(&lock->l_export->exp_rpc_lock);
707         cfs_list_for_each_entry(req, &lock->l_export->exp_queued_rpc,
708                                 rq_exp_list) {
709                 if (!req->rq_hp && req->rq_ops->hpreq_lock_match &&
710                     req->rq_ops->hpreq_lock_match(req, lock))
711                         ptlrpc_hpreq_reorder(req);
712         }
713         cfs_spin_unlock_bh(&lock->l_export->exp_rpc_lock);
714         EXIT;
715 }
716
717 /*
718  * ->l_blocking_ast() method for server-side locks. This is invoked when newly
719  * enqueued server lock conflicts with given one.
720  *
721  * Sends blocking ast rpc to the client owning that lock; arms timeout timer
722  * to wait for client response.
723  */
724 int ldlm_server_blocking_ast(struct ldlm_lock *lock,
725                              struct ldlm_lock_desc *desc,
726                              void *data, int flag)
727 {
728         struct ldlm_cb_async_args *ca;
729         struct ldlm_cb_set_arg *arg = data;
730         struct ldlm_request    *body;
731         struct ptlrpc_request  *req;
732         int                     instant_cancel = 0;
733         int                     rc = 0;
734         ENTRY;
735
736         if (flag == LDLM_CB_CANCELING)
737                 /* Don't need to do anything here. */
738                 RETURN(0);
739
740         LASSERT(lock);
741         LASSERT(data != NULL);
742         if (lock->l_export->exp_obd->obd_recovering != 0) {
743                 LDLM_ERROR(lock, "BUG 6063: lock collide during recovery");
744                 ldlm_lock_dump(D_ERROR, lock, 0);
745         }
746
747         ldlm_lock_reorder_req(lock);
748
749         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
750                                         &RQF_LDLM_BL_CALLBACK,
751                                         LUSTRE_DLM_VERSION, LDLM_BL_CALLBACK);
752         if (req == NULL)
753                 RETURN(-ENOMEM);
754
755         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
756         ca = ptlrpc_req_async_args(req);
757         ca->ca_set_arg = arg;
758         ca->ca_lock = lock;
759
760         req->rq_interpret_reply = ldlm_cb_interpret;
761         req->rq_no_resend = 1;
762
763         lock_res(lock->l_resource);
764         if (lock->l_granted_mode != lock->l_req_mode) {
765                 /* this blocking AST will be communicated as part of the
766                  * completion AST instead */
767                 unlock_res(lock->l_resource);
768                 ptlrpc_req_finished(req);
769                 LDLM_DEBUG(lock, "lock not granted, not sending blocking AST");
770                 RETURN(0);
771         }
772
773         if (lock->l_destroyed) {
774                 /* What's the point? */
775                 unlock_res(lock->l_resource);
776                 ptlrpc_req_finished(req);
777                 RETURN(0);
778         }
779
780         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
781                 instant_cancel = 1;
782
783         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
784         body->lock_handle[0] = lock->l_remote_handle;
785         body->lock_desc = *desc;
786         body->lock_flags |= (lock->l_flags & LDLM_AST_FLAGS);
787
788         LDLM_DEBUG(lock, "server preparing blocking AST");
789
790         ptlrpc_request_set_replen(req);
791         if (instant_cancel) {
792                 unlock_res(lock->l_resource);
793                 ldlm_lock_cancel(lock);
794         } else {
795                 LASSERT(lock->l_granted_mode == lock->l_req_mode);
796                 ldlm_add_waiting_lock(lock);
797                 unlock_res(lock->l_resource);
798         }
799
800         req->rq_send_state = LUSTRE_IMP_FULL;
801         /* ptlrpc_request_alloc_pack already set timeout */
802         if (AT_OFF)
803                 req->rq_timeout = ldlm_get_rq_timeout();
804
805         if (lock->l_export && lock->l_export->exp_nid_stats &&
806             lock->l_export->exp_nid_stats->nid_ldlm_stats)
807                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
808                                      LDLM_BL_CALLBACK - LDLM_FIRST_OPC);
809
810         rc = ldlm_bl_and_cp_ast_fini(req, arg, lock, instant_cancel);
811
812         RETURN(rc);
813 }
814
815 int ldlm_server_completion_ast(struct ldlm_lock *lock, int flags, void *data)
816 {
817         struct ldlm_cb_set_arg *arg = data;
818         struct ldlm_request    *body;
819         struct ptlrpc_request  *req;
820         struct ldlm_cb_async_args *ca;
821         long                    total_enqueue_wait;
822         int                     instant_cancel = 0;
823         int                     rc = 0;
824         ENTRY;
825
826         LASSERT(lock != NULL);
827         LASSERT(data != NULL);
828
829         total_enqueue_wait = cfs_time_sub(cfs_time_current_sec(),
830                                           lock->l_last_activity);
831
832         req = ptlrpc_request_alloc(lock->l_export->exp_imp_reverse,
833                                     &RQF_LDLM_CP_CALLBACK);
834         if (req == NULL)
835                 RETURN(-ENOMEM);
836
837         /* server namespace, doesn't need lock */
838         if (lock->l_resource->lr_lvb_len) {
839                  req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_CLIENT,
840                                       lock->l_resource->lr_lvb_len);
841         }
842
843         rc = ptlrpc_request_pack(req, LUSTRE_DLM_VERSION, LDLM_CP_CALLBACK);
844         if (rc) {
845                 ptlrpc_request_free(req);
846                 RETURN(rc);
847         }
848
849         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
850         ca = ptlrpc_req_async_args(req);
851         ca->ca_set_arg = arg;
852         ca->ca_lock = lock;
853
854         req->rq_interpret_reply = ldlm_cb_interpret;
855         req->rq_no_resend = 1;
856         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
857
858         body->lock_handle[0] = lock->l_remote_handle;
859         body->lock_flags = flags;
860         ldlm_lock2desc(lock, &body->lock_desc);
861         if (lock->l_resource->lr_lvb_len) {
862                 void *lvb = req_capsule_client_get(&req->rq_pill, &RMF_DLM_LVB);
863
864                 lock_res(lock->l_resource);
865                 memcpy(lvb, lock->l_resource->lr_lvb_data,
866                        lock->l_resource->lr_lvb_len);
867                 unlock_res(lock->l_resource);
868         }
869
870         LDLM_DEBUG(lock, "server preparing completion AST (after %lds wait)",
871                    total_enqueue_wait);
872
873         /* Server-side enqueue wait time estimate, used in
874             __ldlm_add_waiting_lock to set future enqueue timers */
875         if (total_enqueue_wait < ldlm_get_enq_timeout(lock))
876                 at_measured(ldlm_lock_to_ns_at(lock),
877                             total_enqueue_wait);
878         else
879                 /* bz18618. Don't add lock enqueue time we spend waiting for a
880                    previous callback to fail. Locks waiting legitimately will
881                    get extended by ldlm_refresh_waiting_lock regardless of the
882                    estimate, so it's okay to underestimate here. */
883                 LDLM_DEBUG(lock, "lock completed after %lus; estimate was %ds. "
884                        "It is likely that a previous callback timed out.",
885                        total_enqueue_wait,
886                        at_get(ldlm_lock_to_ns_at(lock)));
887
888         ptlrpc_request_set_replen(req);
889
890         req->rq_send_state = LUSTRE_IMP_FULL;
891         /* ptlrpc_request_pack already set timeout */
892         if (AT_OFF)
893                 req->rq_timeout = ldlm_get_rq_timeout();
894
895         /* We only send real blocking ASTs after the lock is granted */
896         lock_res_and_lock(lock);
897         if (lock->l_flags & LDLM_FL_AST_SENT) {
898                 body->lock_flags |= LDLM_FL_AST_SENT;
899                 /* copy ast flags like LDLM_FL_DISCARD_DATA */
900                 body->lock_flags |= (lock->l_flags & LDLM_AST_FLAGS);
901
902                 /* We might get here prior to ldlm_handle_enqueue setting
903                  * LDLM_FL_CANCEL_ON_BLOCK flag. Then we will put this lock
904                  * into waiting list, but this is safe and similar code in
905                  * ldlm_handle_enqueue will call ldlm_lock_cancel() still,
906                  * that would not only cancel the lock, but will also remove
907                  * it from waiting list */
908                 if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
909                         unlock_res_and_lock(lock);
910                         ldlm_lock_cancel(lock);
911                         instant_cancel = 1;
912                         lock_res_and_lock(lock);
913                 } else {
914                         /* start the lock-timeout clock */
915                         ldlm_add_waiting_lock(lock);
916                 }
917         }
918         unlock_res_and_lock(lock);
919
920         if (lock->l_export && lock->l_export->exp_nid_stats &&
921             lock->l_export->exp_nid_stats->nid_ldlm_stats)
922                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
923                                      LDLM_CP_CALLBACK - LDLM_FIRST_OPC);
924
925         rc = ldlm_bl_and_cp_ast_fini(req, arg, lock, instant_cancel);
926
927         RETURN(rc);
928 }
929
930 int ldlm_server_glimpse_ast(struct ldlm_lock *lock, void *data)
931 {
932         struct ldlm_resource  *res = lock->l_resource;
933         struct ldlm_request   *body;
934         struct ptlrpc_request *req;
935         int                    rc;
936         ENTRY;
937
938         LASSERT(lock != NULL);
939
940         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
941                                         &RQF_LDLM_GL_CALLBACK,
942                                         LUSTRE_DLM_VERSION, LDLM_GL_CALLBACK);
943
944         if (req == NULL)
945                 RETURN(-ENOMEM);
946
947         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
948         body->lock_handle[0] = lock->l_remote_handle;
949         ldlm_lock2desc(lock, &body->lock_desc);
950
951         /* server namespace, doesn't need lock */
952         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
953                              lock->l_resource->lr_lvb_len);
954         res = lock->l_resource;
955         ptlrpc_request_set_replen(req);
956
957
958         req->rq_send_state = LUSTRE_IMP_FULL;
959         /* ptlrpc_request_alloc_pack already set timeout */
960         if (AT_OFF)
961                 req->rq_timeout = ldlm_get_rq_timeout();
962
963         if (lock->l_export && lock->l_export->exp_nid_stats &&
964             lock->l_export->exp_nid_stats->nid_ldlm_stats)
965                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
966                                      LDLM_GL_CALLBACK - LDLM_FIRST_OPC);
967
968         rc = ptlrpc_queue_wait(req);
969         if (rc == -ELDLM_NO_LOCK_DATA)
970                 LDLM_DEBUG(lock, "lost race - client has a lock but no inode");
971         else if (rc != 0)
972                 rc = ldlm_handle_ast_error(lock, req, rc, "glimpse");
973         else
974                 rc = ldlm_res_lvbo_update(res, req, 1);
975
976         ptlrpc_req_finished(req);
977         if (rc == -ERESTART)
978                 ldlm_reprocess_all(res);
979
980         RETURN(rc);
981 }
982
983 #ifdef __KERNEL__
984 extern unsigned long long lu_time_stamp_get(void);
985 #else
986 #define lu_time_stamp_get() time(NULL)
987 #endif
988
989 static void ldlm_svc_get_eopc(const struct ldlm_request *dlm_req,
990                        struct lprocfs_stats *srv_stats)
991 {
992         int lock_type = 0, op = 0;
993
994         lock_type = dlm_req->lock_desc.l_resource.lr_type;
995
996         switch (lock_type) {
997         case LDLM_PLAIN:
998                 op = PTLRPC_LAST_CNTR + LDLM_PLAIN_ENQUEUE;
999                 break;
1000         case LDLM_EXTENT:
1001                 if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT)
1002                         op = PTLRPC_LAST_CNTR + LDLM_GLIMPSE_ENQUEUE;
1003                 else
1004                         op = PTLRPC_LAST_CNTR + LDLM_EXTENT_ENQUEUE;
1005                 break;
1006         case LDLM_FLOCK:
1007                 op = PTLRPC_LAST_CNTR + LDLM_FLOCK_ENQUEUE;
1008                 break;
1009         case LDLM_IBITS:
1010                 op = PTLRPC_LAST_CNTR + LDLM_IBITS_ENQUEUE;
1011                 break;
1012         default:
1013                 op = 0;
1014                 break;
1015         }
1016
1017         if (op)
1018                 lprocfs_counter_incr(srv_stats, op);
1019
1020         return;
1021 }
1022
1023 /*
1024  * Main server-side entry point into LDLM. This is called by ptlrpc service
1025  * threads to carry out client lock enqueueing requests.
1026  */
1027 int ldlm_handle_enqueue0(struct ldlm_namespace *ns,
1028                          struct ptlrpc_request *req,
1029                          const struct ldlm_request *dlm_req,
1030                          const struct ldlm_callback_suite *cbs)
1031 {
1032         struct ldlm_reply *dlm_rep;
1033         __u32 flags;
1034         ldlm_error_t err = ELDLM_OK;
1035         struct ldlm_lock *lock = NULL;
1036         void *cookie = NULL;
1037         int rc = 0;
1038         ENTRY;
1039
1040         LDLM_DEBUG_NOLOCK("server-side enqueue handler START");
1041
1042         ldlm_request_cancel(req, dlm_req, LDLM_ENQUEUE_CANCEL_OFF);
1043         flags = dlm_req->lock_flags;
1044
1045         LASSERT(req->rq_export);
1046
1047         if (req->rq_rqbd->rqbd_service->srv_stats)
1048                 ldlm_svc_get_eopc(dlm_req,
1049                                   req->rq_rqbd->rqbd_service->srv_stats);
1050
1051         if (req->rq_export && req->rq_export->exp_nid_stats &&
1052             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1053                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1054                                      LDLM_ENQUEUE - LDLM_FIRST_OPC);
1055
1056         if (unlikely(dlm_req->lock_desc.l_resource.lr_type < LDLM_MIN_TYPE ||
1057                      dlm_req->lock_desc.l_resource.lr_type >= LDLM_MAX_TYPE)) {
1058                 DEBUG_REQ(D_ERROR, req, "invalid lock request type %d",
1059                           dlm_req->lock_desc.l_resource.lr_type);
1060                 GOTO(out, rc = -EFAULT);
1061         }
1062
1063         if (unlikely(dlm_req->lock_desc.l_req_mode <= LCK_MINMODE ||
1064                      dlm_req->lock_desc.l_req_mode >= LCK_MAXMODE ||
1065                      dlm_req->lock_desc.l_req_mode &
1066                      (dlm_req->lock_desc.l_req_mode-1))) {
1067                 DEBUG_REQ(D_ERROR, req, "invalid lock request mode %d",
1068                           dlm_req->lock_desc.l_req_mode);
1069                 GOTO(out, rc = -EFAULT);
1070         }
1071
1072         if (req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) {
1073                 if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1074                              LDLM_PLAIN)) {
1075                         DEBUG_REQ(D_ERROR, req,
1076                                   "PLAIN lock request from IBITS client?");
1077                         GOTO(out, rc = -EPROTO);
1078                 }
1079         } else if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1080                             LDLM_IBITS)) {
1081                 DEBUG_REQ(D_ERROR, req,
1082                           "IBITS lock request from unaware client?");
1083                 GOTO(out, rc = -EPROTO);
1084         }
1085
1086 #if 0
1087         /* FIXME this makes it impossible to use LDLM_PLAIN locks -- check
1088            against server's _CONNECT_SUPPORTED flags? (I don't want to use
1089            ibits for mgc/mgs) */
1090
1091         /* INODEBITS_INTEROP: Perform conversion from plain lock to
1092          * inodebits lock if client does not support them. */
1093         if (!(req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) &&
1094             (dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN)) {
1095                 dlm_req->lock_desc.l_resource.lr_type = LDLM_IBITS;
1096                 dlm_req->lock_desc.l_policy_data.l_inodebits.bits =
1097                         MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
1098                 if (dlm_req->lock_desc.l_req_mode == LCK_PR)
1099                         dlm_req->lock_desc.l_req_mode = LCK_CR;
1100         }
1101 #endif
1102
1103         if (unlikely(flags & LDLM_FL_REPLAY)) {
1104                 /* Find an existing lock in the per-export lock hash */
1105                 lock = cfs_hash_lookup(req->rq_export->exp_lock_hash,
1106                                        (void *)&dlm_req->lock_handle[0]);
1107                 if (lock != NULL) {
1108                         DEBUG_REQ(D_DLMTRACE, req, "found existing lock cookie "
1109                                   LPX64, lock->l_handle.h_cookie);
1110                         GOTO(existing_lock, rc = 0);
1111                 }
1112         }
1113
1114         /* The lock's callback data might be set in the policy function */
1115         lock = ldlm_lock_create(ns, &dlm_req->lock_desc.l_resource.lr_name,
1116                                 dlm_req->lock_desc.l_resource.lr_type,
1117                                 dlm_req->lock_desc.l_req_mode,
1118                                 cbs, NULL, 0);
1119
1120         if (!lock)
1121                 GOTO(out, rc = -ENOMEM);
1122
1123         lock->l_last_activity = cfs_time_current_sec();
1124         lock->l_remote_handle = dlm_req->lock_handle[0];
1125         LDLM_DEBUG(lock, "server-side enqueue handler, new lock created");
1126
1127         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_ENQUEUE_BLOCKED, obd_timeout * 2);
1128         /* Don't enqueue a lock onto the export if it is been disonnected
1129          * due to eviction (bug 3822) or server umount (bug 24324).
1130          * Cancel it now instead. */
1131         if (req->rq_export->exp_disconnected) {
1132                 LDLM_ERROR(lock, "lock on disconnected export %p",
1133                            req->rq_export);
1134                 GOTO(out, rc = -ENOTCONN);
1135         }
1136
1137         lock->l_export = class_export_lock_get(req->rq_export, lock);
1138         if (lock->l_export->exp_lock_hash)
1139                 cfs_hash_add(lock->l_export->exp_lock_hash,
1140                              &lock->l_remote_handle,
1141                              &lock->l_exp_hash);
1142
1143 existing_lock:
1144
1145         if (flags & LDLM_FL_HAS_INTENT) {
1146                 /* In this case, the reply buffer is allocated deep in
1147                  * local_lock_enqueue by the policy function. */
1148                 cookie = req;
1149         } else {
1150                 /* based on the assumption that lvb size never changes during
1151                  * resource life time otherwise it need resource->lr_lock's
1152                  * protection */
1153                 if (lock->l_resource->lr_lvb_len) {
1154                         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB,
1155                                              RCL_SERVER,
1156                                              lock->l_resource->lr_lvb_len);
1157                 }
1158
1159                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_EXTENT_ERR))
1160                         GOTO(out, rc = -ENOMEM);
1161
1162                 rc = req_capsule_server_pack(&req->rq_pill);
1163                 if (rc)
1164                         GOTO(out, rc);
1165         }
1166
1167         if (dlm_req->lock_desc.l_resource.lr_type != LDLM_PLAIN)
1168                 lock->l_policy_data = dlm_req->lock_desc.l_policy_data;
1169         if (dlm_req->lock_desc.l_resource.lr_type == LDLM_EXTENT)
1170                 lock->l_req_extent = lock->l_policy_data.l_extent;
1171
1172         err = ldlm_lock_enqueue(ns, &lock, cookie, (int *)&flags);
1173         if (err)
1174                 GOTO(out, err);
1175
1176         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1177         dlm_rep->lock_flags = flags;
1178
1179         ldlm_lock2desc(lock, &dlm_rep->lock_desc);
1180         ldlm_lock2handle(lock, &dlm_rep->lock_handle);
1181
1182         /* We never send a blocking AST until the lock is granted, but
1183          * we can tell it right now */
1184         lock_res_and_lock(lock);
1185
1186         /* Now take into account flags to be inherited from original lock
1187            request both in reply to client and in our own lock flags. */
1188         dlm_rep->lock_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1189         lock->l_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1190
1191         /* Don't move a pending lock onto the export if it has already been
1192          * disconnected due to eviction (bug 5683) or server umount (bug 24324).
1193          * Cancel it now instead. */
1194         if (unlikely(req->rq_export->exp_disconnected ||
1195                      OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT))) {
1196                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
1197                 rc = -ENOTCONN;
1198         } else if (lock->l_flags & LDLM_FL_AST_SENT) {
1199                 dlm_rep->lock_flags |= LDLM_FL_AST_SENT;
1200                 if (lock->l_granted_mode == lock->l_req_mode) {
1201                         /*
1202                          * Only cancel lock if it was granted, because it would
1203                          * be destroyed immediately and would never be granted
1204                          * in the future, causing timeouts on client.  Not
1205                          * granted lock will be cancelled immediately after
1206                          * sending completion AST.
1207                          */
1208                         if (dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1209                                 unlock_res_and_lock(lock);
1210                                 ldlm_lock_cancel(lock);
1211                                 lock_res_and_lock(lock);
1212                         } else
1213                                 ldlm_add_waiting_lock(lock);
1214                 }
1215         }
1216         /* Make sure we never ever grant usual metadata locks to liblustre
1217            clients */
1218         if ((dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN ||
1219             dlm_req->lock_desc.l_resource.lr_type == LDLM_IBITS) &&
1220              req->rq_export->exp_libclient) {
1221                 if (unlikely(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) ||
1222                              !(dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK))){
1223                         CERROR("Granting sync lock to libclient. "
1224                                "req fl %d, rep fl %d, lock fl "LPX64"\n",
1225                                dlm_req->lock_flags, dlm_rep->lock_flags,
1226                                lock->l_flags);
1227                         LDLM_ERROR(lock, "sync lock");
1228                         if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT) {
1229                                 struct ldlm_intent *it;
1230
1231                                 it = req_capsule_client_get(&req->rq_pill,
1232                                                             &RMF_LDLM_INTENT);
1233                                 if (it != NULL) {
1234                                         CERROR("This is intent %s ("LPU64")\n",
1235                                                ldlm_it2str(it->opc), it->opc);
1236                                 }
1237                         }
1238                 }
1239         }
1240
1241         unlock_res_and_lock(lock);
1242
1243         EXIT;
1244  out:
1245         req->rq_status = rc ?: err; /* return either error - bug 11190 */
1246         if (!req->rq_packed_final) {
1247                 err = lustre_pack_reply(req, 1, NULL, NULL);
1248                 if (rc == 0)
1249                         rc = err;
1250         }
1251
1252         /* The LOCK_CHANGED code in ldlm_lock_enqueue depends on this
1253          * ldlm_reprocess_all.  If this moves, revisit that code. -phil */
1254         if (lock) {
1255                 LDLM_DEBUG(lock, "server-side enqueue handler, sending reply"
1256                            "(err=%d, rc=%d)", err, rc);
1257
1258                 if (rc == 0) {
1259                         if (lock->l_resource->lr_lvb_len > 0) {
1260                                 /* MDT path won't handle lr_lvb_data, so
1261                                  * lock/unlock better be contained in the
1262                                  * if block */
1263                                 void *lvb;
1264
1265                                 lvb = req_capsule_server_get(&req->rq_pill,
1266                                                              &RMF_DLM_LVB);
1267                                 LASSERTF(lvb != NULL, "req %p, lock %p\n",
1268                                          req, lock);
1269                                 lock_res(lock->l_resource);
1270                                 memcpy(lvb, lock->l_resource->lr_lvb_data,
1271                                        lock->l_resource->lr_lvb_len);
1272                                 unlock_res(lock->l_resource);
1273                         }
1274                 } else {
1275                         lock_res_and_lock(lock);
1276                         ldlm_resource_unlink_lock(lock);
1277                         ldlm_lock_destroy_nolock(lock);
1278                         unlock_res_and_lock(lock);
1279                 }
1280
1281                 if (!err && dlm_req->lock_desc.l_resource.lr_type != LDLM_FLOCK)
1282                         ldlm_reprocess_all(lock->l_resource);
1283
1284                 LDLM_LOCK_RELEASE(lock);
1285         }
1286
1287         LDLM_DEBUG_NOLOCK("server-side enqueue handler END (lock %p, rc %d)",
1288                           lock, rc);
1289
1290         return rc;
1291 }
1292
1293 int ldlm_handle_enqueue(struct ptlrpc_request *req,
1294                         ldlm_completion_callback completion_callback,
1295                         ldlm_blocking_callback blocking_callback,
1296                         ldlm_glimpse_callback glimpse_callback)
1297 {
1298         struct ldlm_request *dlm_req;
1299         struct ldlm_callback_suite cbs = {
1300                 .lcs_completion = completion_callback,
1301                 .lcs_blocking   = blocking_callback,
1302                 .lcs_glimpse    = glimpse_callback
1303         };
1304         int rc;
1305
1306         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1307         if (dlm_req != NULL) {
1308                 rc = ldlm_handle_enqueue0(req->rq_export->exp_obd->obd_namespace,
1309                                           req, dlm_req, &cbs);
1310         } else {
1311                 rc = -EFAULT;
1312         }
1313         return rc;
1314 }
1315
1316 int ldlm_handle_convert0(struct ptlrpc_request *req,
1317                          const struct ldlm_request *dlm_req)
1318 {
1319         struct ldlm_reply *dlm_rep;
1320         struct ldlm_lock *lock;
1321         int rc;
1322         ENTRY;
1323
1324         if (req->rq_export && req->rq_export->exp_nid_stats &&
1325             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1326                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1327                                      LDLM_CONVERT - LDLM_FIRST_OPC);
1328
1329         rc = req_capsule_server_pack(&req->rq_pill);
1330         if (rc)
1331                 RETURN(rc);
1332
1333         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1334         dlm_rep->lock_flags = dlm_req->lock_flags;
1335
1336         lock = ldlm_handle2lock(&dlm_req->lock_handle[0]);
1337         if (!lock) {
1338                 req->rq_status = EINVAL;
1339         } else {
1340                 void *res = NULL;
1341
1342                 LDLM_DEBUG(lock, "server-side convert handler START");
1343
1344                 lock->l_last_activity = cfs_time_current_sec();
1345                 res = ldlm_lock_convert(lock, dlm_req->lock_desc.l_req_mode,
1346                                         &dlm_rep->lock_flags);
1347                 if (res) {
1348                         if (ldlm_del_waiting_lock(lock))
1349                                 LDLM_DEBUG(lock, "converted waiting lock");
1350                         req->rq_status = 0;
1351                 } else {
1352                         req->rq_status = EDEADLOCK;
1353                 }
1354         }
1355
1356         if (lock) {
1357                 if (!req->rq_status)
1358                         ldlm_reprocess_all(lock->l_resource);
1359                 LDLM_DEBUG(lock, "server-side convert handler END");
1360                 LDLM_LOCK_PUT(lock);
1361         } else
1362                 LDLM_DEBUG_NOLOCK("server-side convert handler END");
1363
1364         RETURN(0);
1365 }
1366
1367 int ldlm_handle_convert(struct ptlrpc_request *req)
1368 {
1369         int rc;
1370         struct ldlm_request *dlm_req;
1371
1372         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1373         if (dlm_req != NULL) {
1374                 rc = ldlm_handle_convert0(req, dlm_req);
1375         } else {
1376                 CERROR ("Can't unpack dlm_req\n");
1377                 rc = -EFAULT;
1378         }
1379         return rc;
1380 }
1381
1382 /* Cancel all the locks whos handles are packed into ldlm_request */
1383 int ldlm_request_cancel(struct ptlrpc_request *req,
1384                         const struct ldlm_request *dlm_req, int first)
1385 {
1386         struct ldlm_resource *res, *pres = NULL;
1387         struct ldlm_lock *lock;
1388         int i, count, done = 0;
1389         ENTRY;
1390
1391         count = dlm_req->lock_count ? dlm_req->lock_count : 1;
1392         if (first >= count)
1393                 RETURN(0);
1394
1395         /* There is no lock on the server at the replay time,
1396          * skip lock cancelling to make replay tests to pass. */
1397         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1398                 RETURN(0);
1399
1400         LDLM_DEBUG_NOLOCK("server-side cancel handler START: %d locks, "
1401                           "starting at %d", count, first);
1402
1403         for (i = first; i < count; i++) {
1404                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
1405                 if (!lock) {
1406                         LDLM_DEBUG_NOLOCK("server-side cancel handler stale "
1407                                           "lock (cookie "LPU64")",
1408                                           dlm_req->lock_handle[i].cookie);
1409                         continue;
1410                 }
1411
1412                 res = lock->l_resource;
1413                 done++;
1414
1415                 if (res != pres) {
1416                         if (pres != NULL) {
1417                                 ldlm_reprocess_all(pres);
1418                                 LDLM_RESOURCE_DELREF(pres);
1419                                 ldlm_resource_putref(pres);
1420                         }
1421                         if (res != NULL) {
1422                                 ldlm_resource_getref(res);
1423                                 LDLM_RESOURCE_ADDREF(res);
1424                                 ldlm_res_lvbo_update(res, NULL, 1);
1425                         }
1426                         pres = res;
1427                 }
1428                 ldlm_lock_cancel(lock);
1429                 LDLM_LOCK_PUT(lock);
1430         }
1431         if (pres != NULL) {
1432                 ldlm_reprocess_all(pres);
1433                 LDLM_RESOURCE_DELREF(pres);
1434                 ldlm_resource_putref(pres);
1435         }
1436         LDLM_DEBUG_NOLOCK("server-side cancel handler END");
1437         RETURN(done);
1438 }
1439
1440 int ldlm_handle_cancel(struct ptlrpc_request *req)
1441 {
1442         struct ldlm_request *dlm_req;
1443         int rc;
1444         ENTRY;
1445
1446         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1447         if (dlm_req == NULL) {
1448                 CDEBUG(D_INFO, "bad request buffer for cancel\n");
1449                 RETURN(-EFAULT);
1450         }
1451
1452         if (req->rq_export && req->rq_export->exp_nid_stats &&
1453             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1454                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1455                                      LDLM_CANCEL - LDLM_FIRST_OPC);
1456
1457         rc = req_capsule_server_pack(&req->rq_pill);
1458         if (rc)
1459                 RETURN(rc);
1460
1461         if (!ldlm_request_cancel(req, dlm_req, 0))
1462                 req->rq_status = ESTALE;
1463
1464         RETURN(ptlrpc_reply(req));
1465 }
1466
1467 void ldlm_handle_bl_callback(struct ldlm_namespace *ns,
1468                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock)
1469 {
1470         int do_ast;
1471         ENTRY;
1472
1473         LDLM_DEBUG(lock, "client blocking AST callback handler");
1474
1475         lock_res_and_lock(lock);
1476         lock->l_flags |= LDLM_FL_CBPENDING;
1477
1478         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
1479                 lock->l_flags |= LDLM_FL_CANCEL;
1480
1481         do_ast = (!lock->l_readers && !lock->l_writers);
1482         unlock_res_and_lock(lock);
1483
1484         if (do_ast) {
1485                 CDEBUG(D_DLMTRACE, "Lock %p already unused, calling callback (%p)\n",
1486                        lock, lock->l_blocking_ast);
1487                 if (lock->l_blocking_ast != NULL)
1488                         lock->l_blocking_ast(lock, ld, lock->l_ast_data,
1489                                              LDLM_CB_BLOCKING);
1490         } else {
1491                 CDEBUG(D_DLMTRACE, "Lock %p is referenced, will be cancelled later\n",
1492                        lock);
1493         }
1494
1495         LDLM_DEBUG(lock, "client blocking callback handler END");
1496         LDLM_LOCK_RELEASE(lock);
1497         EXIT;
1498 }
1499
1500 static void ldlm_handle_cp_callback(struct ptlrpc_request *req,
1501                                     struct ldlm_namespace *ns,
1502                                     struct ldlm_request *dlm_req,
1503                                     struct ldlm_lock *lock)
1504 {
1505         CFS_LIST_HEAD(ast_list);
1506         ENTRY;
1507
1508         LDLM_DEBUG(lock, "client completion callback handler START");
1509
1510         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE)) {
1511                 int to = cfs_time_seconds(1);
1512                 while (to > 0) {
1513                         cfs_schedule_timeout_and_set_state(
1514                                 CFS_TASK_INTERRUPTIBLE, to);
1515                         if (lock->l_granted_mode == lock->l_req_mode ||
1516                             lock->l_destroyed)
1517                                 break;
1518                 }
1519         }
1520
1521         lock_res_and_lock(lock);
1522         if (lock->l_destroyed ||
1523             lock->l_granted_mode == lock->l_req_mode) {
1524                 /* bug 11300: the lock has already been granted */
1525                 unlock_res_and_lock(lock);
1526                 LDLM_DEBUG(lock, "Double grant race happened");
1527                 LDLM_LOCK_RELEASE(lock);
1528                 EXIT;
1529                 return;
1530         }
1531
1532         /* If we receive the completion AST before the actual enqueue returned,
1533          * then we might need to switch lock modes, resources, or extents. */
1534         if (dlm_req->lock_desc.l_granted_mode != lock->l_req_mode) {
1535                 lock->l_req_mode = dlm_req->lock_desc.l_granted_mode;
1536                 LDLM_DEBUG(lock, "completion AST, new lock mode");
1537         }
1538
1539         if (lock->l_resource->lr_type != LDLM_PLAIN) {
1540                 lock->l_policy_data = dlm_req->lock_desc.l_policy_data;
1541                 LDLM_DEBUG(lock, "completion AST, new policy data");
1542         }
1543
1544         ldlm_resource_unlink_lock(lock);
1545         if (memcmp(&dlm_req->lock_desc.l_resource.lr_name,
1546                    &lock->l_resource->lr_name,
1547                    sizeof(lock->l_resource->lr_name)) != 0) {
1548                 unlock_res_and_lock(lock);
1549                 if (ldlm_lock_change_resource(ns, lock,
1550                                 &dlm_req->lock_desc.l_resource.lr_name) != 0) {
1551                         LDLM_ERROR(lock, "Failed to allocate resource");
1552                         LDLM_LOCK_RELEASE(lock);
1553                         EXIT;
1554                         return;
1555                 }
1556                 LDLM_DEBUG(lock, "completion AST, new resource");
1557                 CERROR("change resource!\n");
1558                 lock_res_and_lock(lock);
1559         }
1560
1561         if (dlm_req->lock_flags & LDLM_FL_AST_SENT) {
1562                 /* BL_AST locks are not needed in lru.
1563                  * let ldlm_cancel_lru() be fast. */
1564                 ldlm_lock_remove_from_lru(lock);
1565                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_BL_AST;
1566                 LDLM_DEBUG(lock, "completion AST includes blocking AST");
1567         }
1568
1569         if (lock->l_lvb_len) {
1570                 if (req_capsule_get_size(&req->rq_pill, &RMF_DLM_LVB,
1571                                          RCL_CLIENT) < lock->l_lvb_len) {
1572                         LDLM_ERROR(lock, "completion AST did not contain "
1573                                    "expected LVB!");
1574                 } else {
1575                         void *lvb = req_capsule_client_get(&req->rq_pill,
1576                                                            &RMF_DLM_LVB);
1577                         memcpy(lock->l_lvb_data, lvb, lock->l_lvb_len);
1578                 }
1579         }
1580
1581         ldlm_grant_lock(lock, &ast_list);
1582         unlock_res_and_lock(lock);
1583
1584         LDLM_DEBUG(lock, "callback handler finished, about to run_ast_work");
1585
1586         /* Let Enqueue to call osc_lock_upcall() and initialize
1587          * l_ast_data */
1588         OBD_FAIL_TIMEOUT(OBD_FAIL_OSC_CP_ENQ_RACE, 2);
1589
1590         ldlm_run_ast_work(&ast_list, LDLM_WORK_CP_AST);
1591
1592         LDLM_DEBUG_NOLOCK("client completion callback handler END (lock %p)",
1593                           lock);
1594         LDLM_LOCK_RELEASE(lock);
1595         EXIT;
1596 }
1597
1598 static void ldlm_handle_gl_callback(struct ptlrpc_request *req,
1599                                     struct ldlm_namespace *ns,
1600                                     struct ldlm_request *dlm_req,
1601                                     struct ldlm_lock *lock)
1602 {
1603         int rc = -ENOSYS;
1604         ENTRY;
1605
1606         LDLM_DEBUG(lock, "client glimpse AST callback handler");
1607
1608         if (lock->l_glimpse_ast != NULL)
1609                 rc = lock->l_glimpse_ast(lock, req);
1610
1611         if (req->rq_repmsg != NULL) {
1612                 ptlrpc_reply(req);
1613         } else {
1614                 req->rq_status = rc;
1615                 ptlrpc_error(req);
1616         }
1617
1618         lock_res_and_lock(lock);
1619         if (lock->l_granted_mode == LCK_PW &&
1620             !lock->l_readers && !lock->l_writers &&
1621             cfs_time_after(cfs_time_current(),
1622                            cfs_time_add(lock->l_last_used,
1623                                         cfs_time_seconds(10)))) {
1624                 unlock_res_and_lock(lock);
1625                 if (ldlm_bl_to_thread_lock(ns, NULL, lock))
1626                         ldlm_handle_bl_callback(ns, NULL, lock);
1627
1628                 EXIT;
1629                 return;
1630         }
1631         unlock_res_and_lock(lock);
1632         LDLM_LOCK_RELEASE(lock);
1633         EXIT;
1634 }
1635
1636 static int ldlm_callback_reply(struct ptlrpc_request *req, int rc)
1637 {
1638         if (req->rq_no_reply)
1639                 return 0;
1640
1641         req->rq_status = rc;
1642         if (!req->rq_packed_final) {
1643                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1644                 if (rc)
1645                         return rc;
1646         }
1647         return ptlrpc_reply(req);
1648 }
1649
1650 #ifdef __KERNEL__
1651 static int __ldlm_bl_to_thread(struct ldlm_bl_work_item *blwi, int mode)
1652 {
1653         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1654         ENTRY;
1655
1656         cfs_spin_lock(&blp->blp_lock);
1657         if (blwi->blwi_lock && blwi->blwi_lock->l_flags & LDLM_FL_DISCARD_DATA) {
1658                 /* add LDLM_FL_DISCARD_DATA requests to the priority list */
1659                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_prio_list);
1660         } else {
1661                 /* other blocking callbacks are added to the regular list */
1662                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_list);
1663         }
1664         cfs_spin_unlock(&blp->blp_lock);
1665
1666         cfs_waitq_signal(&blp->blp_waitq);
1667
1668         /* can not use blwi->blwi_mode as blwi could be already freed in
1669            LDLM_ASYNC mode */
1670         if (mode == LDLM_SYNC)
1671                 cfs_wait_for_completion(&blwi->blwi_comp);
1672
1673         RETURN(0);
1674 }
1675
1676 static inline void init_blwi(struct ldlm_bl_work_item *blwi,
1677                              struct ldlm_namespace *ns,
1678                              struct ldlm_lock_desc *ld,
1679                              cfs_list_t *cancels, int count,
1680                              struct ldlm_lock *lock,
1681                              int mode)
1682 {
1683         cfs_init_completion(&blwi->blwi_comp);
1684         CFS_INIT_LIST_HEAD(&blwi->blwi_head);
1685
1686         if (cfs_memory_pressure_get())
1687                 blwi->blwi_mem_pressure = 1;
1688
1689         blwi->blwi_ns = ns;
1690         blwi->blwi_mode = mode;
1691         if (ld != NULL)
1692                 blwi->blwi_ld = *ld;
1693         if (count) {
1694                 cfs_list_add(&blwi->blwi_head, cancels);
1695                 cfs_list_del_init(cancels);
1696                 blwi->blwi_count = count;
1697         } else {
1698                 blwi->blwi_lock = lock;
1699         }
1700 }
1701
1702 static int ldlm_bl_to_thread(struct ldlm_namespace *ns,
1703                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock,
1704                              cfs_list_t *cancels, int count, int mode)
1705 {
1706         ENTRY;
1707
1708         if (cancels && count == 0)
1709                 RETURN(0);
1710
1711         if (mode == LDLM_SYNC) {
1712                 /* if it is synchronous call do minimum mem alloc, as it could
1713                  * be triggered from kernel shrinker
1714                  */
1715                 struct ldlm_bl_work_item blwi;
1716                 memset(&blwi, 0, sizeof(blwi));
1717                 init_blwi(&blwi, ns, ld, cancels, count, lock, LDLM_SYNC);
1718                 RETURN(__ldlm_bl_to_thread(&blwi, LDLM_SYNC));
1719         } else {
1720                 struct ldlm_bl_work_item *blwi;
1721                 OBD_ALLOC(blwi, sizeof(*blwi));
1722                 if (blwi == NULL)
1723                         RETURN(-ENOMEM);
1724                 init_blwi(blwi, ns, ld, cancels, count, lock, LDLM_ASYNC);
1725
1726                 RETURN(__ldlm_bl_to_thread(blwi, LDLM_ASYNC));
1727         }
1728 }
1729
1730 #endif
1731
1732 int ldlm_bl_to_thread_lock(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1733                            struct ldlm_lock *lock)
1734 {
1735 #ifdef __KERNEL__
1736         RETURN(ldlm_bl_to_thread(ns, ld, lock, NULL, 0, LDLM_ASYNC));
1737 #else
1738         RETURN(-ENOSYS);
1739 #endif
1740 }
1741
1742 int ldlm_bl_to_thread_list(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1743                            cfs_list_t *cancels, int count, int mode)
1744 {
1745 #ifdef __KERNEL__
1746         RETURN(ldlm_bl_to_thread(ns, ld, NULL, cancels, count, mode));
1747 #else
1748         RETURN(-ENOSYS);
1749 #endif
1750 }
1751
1752 /* Setinfo coming from Server (eg MDT) to Client (eg MDC)! */
1753 static int ldlm_handle_setinfo(struct ptlrpc_request *req)
1754 {
1755         struct obd_device *obd = req->rq_export->exp_obd;
1756         char *key;
1757         void *val;
1758         int keylen, vallen;
1759         int rc = -ENOSYS;
1760         ENTRY;
1761
1762         DEBUG_REQ(D_HSM, req, "%s: handle setinfo\n", obd->obd_name);
1763
1764         req_capsule_set(&req->rq_pill, &RQF_OBD_SET_INFO);
1765
1766         key = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_KEY);
1767         if (key == NULL) {
1768                 DEBUG_REQ(D_IOCTL, req, "no set_info key");
1769                 RETURN(-EFAULT);
1770         }
1771         keylen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_KEY,
1772                                       RCL_CLIENT);
1773         val = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_VAL);
1774         if (val == NULL) {
1775                 DEBUG_REQ(D_IOCTL, req, "no set_info val");
1776                 RETURN(-EFAULT);
1777         }
1778         vallen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_VAL,
1779                                       RCL_CLIENT);
1780
1781         /* We are responsible for swabbing contents of val */
1782
1783         if (KEY_IS(KEY_HSM_COPYTOOL_SEND))
1784                 /* Pass it on to mdc (the "export" in this case) */
1785                 rc = obd_set_info_async(req->rq_export,
1786                                         sizeof(KEY_HSM_COPYTOOL_SEND),
1787                                         KEY_HSM_COPYTOOL_SEND,
1788                                         vallen, val, NULL);
1789         else
1790                 DEBUG_REQ(D_WARNING, req, "ignoring unknown key %s", key);
1791
1792         return rc;
1793 }
1794
1795 static inline void ldlm_callback_errmsg(struct ptlrpc_request *req,
1796                                         const char *msg, int rc,
1797                                         struct lustre_handle *handle)
1798 {
1799         DEBUG_REQ((req->rq_no_reply || rc) ? D_WARNING : D_DLMTRACE, req,
1800                   "%s: [nid %s] [rc %d] [lock "LPX64"]",
1801                   msg, libcfs_id2str(req->rq_peer), rc,
1802                   handle ? handle->cookie : 0);
1803         if (req->rq_no_reply)
1804                 CWARN("No reply was sent, maybe cause bug 21636.\n");
1805         else if (rc)
1806                 CWARN("Send reply failed, maybe cause bug 21636.\n");
1807 }
1808
1809 /* TODO: handle requests in a similar way as MDT: see mdt_handle_common() */
1810 static int ldlm_callback_handler(struct ptlrpc_request *req)
1811 {
1812         struct ldlm_namespace *ns;
1813         struct ldlm_request *dlm_req;
1814         struct ldlm_lock *lock;
1815         int rc;
1816         ENTRY;
1817
1818         /* Requests arrive in sender's byte order.  The ptlrpc service
1819          * handler has already checked and, if necessary, byte-swapped the
1820          * incoming request message body, but I am responsible for the
1821          * message buffers. */
1822
1823         /* do nothing for sec context finalize */
1824         if (lustre_msg_get_opc(req->rq_reqmsg) == SEC_CTX_FINI)
1825                 RETURN(0);
1826
1827         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
1828
1829         if (req->rq_export == NULL) {
1830                 rc = ldlm_callback_reply(req, -ENOTCONN);
1831                 ldlm_callback_errmsg(req, "Operate on unconnected server",
1832                                      rc, NULL);
1833                 RETURN(0);
1834         }
1835
1836         LASSERT(req->rq_export != NULL);
1837         LASSERT(req->rq_export->exp_obd != NULL);
1838
1839         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1840         case LDLM_BL_CALLBACK:
1841                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_BL_CALLBACK))
1842                         RETURN(0);
1843                 break;
1844         case LDLM_CP_CALLBACK:
1845                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CP_CALLBACK))
1846                         RETURN(0);
1847                 break;
1848         case LDLM_GL_CALLBACK:
1849                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_GL_CALLBACK))
1850                         RETURN(0);
1851                 break;
1852         case LDLM_SET_INFO:
1853                 rc = ldlm_handle_setinfo(req);
1854                 ldlm_callback_reply(req, rc);
1855                 RETURN(0);
1856         case OBD_LOG_CANCEL: /* remove this eventually - for 1.4.0 compat */
1857                 CERROR("shouldn't be handling OBD_LOG_CANCEL on DLM thread\n");
1858                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
1859                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
1860                         RETURN(0);
1861                 rc = llog_origin_handle_cancel(req);
1862                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
1863                         RETURN(0);
1864                 ldlm_callback_reply(req, rc);
1865                 RETURN(0);
1866         case OBD_QC_CALLBACK:
1867                 req_capsule_set(&req->rq_pill, &RQF_QC_CALLBACK);
1868                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_QC_CALLBACK_NET))
1869                         RETURN(0);
1870                 rc = target_handle_qc_callback(req);
1871                 ldlm_callback_reply(req, rc);
1872                 RETURN(0);
1873         case QUOTA_DQACQ:
1874         case QUOTA_DQREL:
1875                 /* reply in handler */
1876                 req_capsule_set(&req->rq_pill, &RQF_MDS_QUOTA_DQACQ);
1877                 rc = target_handle_dqacq_callback(req);
1878                 RETURN(0);
1879         case LLOG_ORIGIN_HANDLE_CREATE:
1880                 req_capsule_set(&req->rq_pill, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
1881                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1882                         RETURN(0);
1883                 rc = llog_origin_handle_create(req);
1884                 ldlm_callback_reply(req, rc);
1885                 RETURN(0);
1886         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
1887                 req_capsule_set(&req->rq_pill,
1888                                 &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
1889                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1890                         RETURN(0);
1891                 rc = llog_origin_handle_next_block(req);
1892                 ldlm_callback_reply(req, rc);
1893                 RETURN(0);
1894         case LLOG_ORIGIN_HANDLE_READ_HEADER:
1895                 req_capsule_set(&req->rq_pill,
1896                                 &RQF_LLOG_ORIGIN_HANDLE_READ_HEADER);
1897                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1898                         RETURN(0);
1899                 rc = llog_origin_handle_read_header(req);
1900                 ldlm_callback_reply(req, rc);
1901                 RETURN(0);
1902         case LLOG_ORIGIN_HANDLE_CLOSE:
1903                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1904                         RETURN(0);
1905                 rc = llog_origin_handle_close(req);
1906                 ldlm_callback_reply(req, rc);
1907                 RETURN(0);
1908         default:
1909                 CERROR("unknown opcode %u\n",
1910                        lustre_msg_get_opc(req->rq_reqmsg));
1911                 ldlm_callback_reply(req, -EPROTO);
1912                 RETURN(0);
1913         }
1914
1915         ns = req->rq_export->exp_obd->obd_namespace;
1916         LASSERT(ns != NULL);
1917
1918         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
1919
1920         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1921         if (dlm_req == NULL) {
1922                 rc = ldlm_callback_reply(req, -EPROTO);
1923                 ldlm_callback_errmsg(req, "Operate without parameter", rc,
1924                                      NULL);
1925                 RETURN(0);
1926         }
1927
1928         /* Force a known safe race, send a cancel to the server for a lock
1929          * which the server has already started a blocking callback on. */
1930         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE) &&
1931             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1932                 rc = ldlm_cli_cancel(&dlm_req->lock_handle[0]);
1933                 if (rc < 0)
1934                         CERROR("ldlm_cli_cancel: %d\n", rc);
1935         }
1936
1937         lock = ldlm_handle2lock_long(&dlm_req->lock_handle[0], 0);
1938         if (!lock) {
1939                 CDEBUG(D_DLMTRACE, "callback on lock "LPX64" - lock "
1940                        "disappeared\n", dlm_req->lock_handle[0].cookie);
1941                 rc = ldlm_callback_reply(req, -EINVAL);
1942                 ldlm_callback_errmsg(req, "Operate with invalid parameter", rc,
1943                                      &dlm_req->lock_handle[0]);
1944                 RETURN(0);
1945         }
1946
1947         if ((lock->l_flags & LDLM_FL_FAIL_LOC) &&
1948             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK)
1949                 OBD_RACE(OBD_FAIL_LDLM_CP_BL_RACE);
1950
1951         /* Copy hints/flags (e.g. LDLM_FL_DISCARD_DATA) from AST. */
1952         lock_res_and_lock(lock);
1953         lock->l_flags |= (dlm_req->lock_flags & LDLM_AST_FLAGS);
1954         if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1955                 /* If somebody cancels lock and cache is already dropped,
1956                  * or lock is failed before cp_ast received on client,
1957                  * we can tell the server we have no lock. Otherwise, we
1958                  * should send cancel after dropping the cache. */
1959                 if (((lock->l_flags & LDLM_FL_CANCELING) &&
1960                     (lock->l_flags & LDLM_FL_BL_DONE)) ||
1961                     (lock->l_flags & LDLM_FL_FAILED)) {
1962                         LDLM_DEBUG(lock, "callback on lock "
1963                                    LPX64" - lock disappeared\n",
1964                                    dlm_req->lock_handle[0].cookie);
1965                         unlock_res_and_lock(lock);
1966                         LDLM_LOCK_RELEASE(lock);
1967                         rc = ldlm_callback_reply(req, -EINVAL);
1968                         ldlm_callback_errmsg(req, "Operate on stale lock", rc,
1969                                              &dlm_req->lock_handle[0]);
1970                         RETURN(0);
1971                 }
1972                 /* BL_AST locks are not needed in lru.
1973                  * let ldlm_cancel_lru() be fast. */
1974                 ldlm_lock_remove_from_lru(lock);
1975                 lock->l_flags |= LDLM_FL_BL_AST;
1976         }
1977         unlock_res_and_lock(lock);
1978
1979         /* We want the ost thread to get this reply so that it can respond
1980          * to ost requests (write cache writeback) that might be triggered
1981          * in the callback.
1982          *
1983          * But we'd also like to be able to indicate in the reply that we're
1984          * cancelling right now, because it's unused, or have an intent result
1985          * in the reply, so we might have to push the responsibility for sending
1986          * the reply down into the AST handlers, alas. */
1987
1988         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1989         case LDLM_BL_CALLBACK:
1990                 CDEBUG(D_INODE, "blocking ast\n");
1991                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_BL_CALLBACK);
1992                 if (!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)) {
1993                         rc = ldlm_callback_reply(req, 0);
1994                         if (req->rq_no_reply || rc)
1995                                 ldlm_callback_errmsg(req, "Normal process", rc,
1996                                                      &dlm_req->lock_handle[0]);
1997                 }
1998                 if (ldlm_bl_to_thread_lock(ns, &dlm_req->lock_desc, lock))
1999                         ldlm_handle_bl_callback(ns, &dlm_req->lock_desc, lock);
2000                 break;
2001         case LDLM_CP_CALLBACK:
2002                 CDEBUG(D_INODE, "completion ast\n");
2003                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_CP_CALLBACK);
2004                 ldlm_callback_reply(req, 0);
2005                 ldlm_handle_cp_callback(req, ns, dlm_req, lock);
2006                 break;
2007         case LDLM_GL_CALLBACK:
2008                 CDEBUG(D_INODE, "glimpse ast\n");
2009                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_GL_CALLBACK);
2010                 ldlm_handle_gl_callback(req, ns, dlm_req, lock);
2011                 break;
2012         default:
2013                 LBUG();                         /* checked above */
2014         }
2015
2016         RETURN(0);
2017 }
2018
2019 static int ldlm_cancel_handler(struct ptlrpc_request *req)
2020 {
2021         int rc;
2022         ENTRY;
2023
2024         /* Requests arrive in sender's byte order.  The ptlrpc service
2025          * handler has already checked and, if necessary, byte-swapped the
2026          * incoming request message body, but I am responsible for the
2027          * message buffers. */
2028
2029         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2030
2031         if (req->rq_export == NULL) {
2032                 struct ldlm_request *dlm_req;
2033
2034                 CERROR("%s from %s arrived at %lu with bad export cookie "
2035                        LPU64"\n",
2036                        ll_opcode2str(lustre_msg_get_opc(req->rq_reqmsg)),
2037                        libcfs_nid2str(req->rq_peer.nid),
2038                        req->rq_arrival_time.tv_sec,
2039                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
2040
2041                 if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_CANCEL) {
2042                         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2043                         dlm_req = req_capsule_client_get(&req->rq_pill,
2044                                                          &RMF_DLM_REQ);
2045                         if (dlm_req != NULL)
2046                                 ldlm_lock_dump_handle(D_ERROR,
2047                                                       &dlm_req->lock_handle[0]);
2048                 }
2049                 ldlm_callback_reply(req, -ENOTCONN);
2050                 RETURN(0);
2051         }
2052
2053         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2054
2055         /* XXX FIXME move this back to mds/handler.c, bug 249 */
2056         case LDLM_CANCEL:
2057                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CANCEL);
2058                 CDEBUG(D_INODE, "cancel\n");
2059                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL))
2060                         RETURN(0);
2061                 rc = ldlm_handle_cancel(req);
2062                 if (rc)
2063                         break;
2064                 RETURN(0);
2065         case OBD_LOG_CANCEL:
2066                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
2067                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
2068                         RETURN(0);
2069                 rc = llog_origin_handle_cancel(req);
2070                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
2071                         RETURN(0);
2072                 ldlm_callback_reply(req, rc);
2073                 RETURN(0);
2074         default:
2075                 CERROR("invalid opcode %d\n",
2076                        lustre_msg_get_opc(req->rq_reqmsg));
2077                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2078                 ldlm_callback_reply(req, -EINVAL);
2079         }
2080
2081         RETURN(0);
2082 }
2083
2084 int ldlm_revoke_lock_cb(cfs_hash_t *hs, cfs_hash_bd_t *bd,
2085                         cfs_hlist_node_t *hnode, void *data)
2086
2087 {
2088         cfs_list_t         *rpc_list = data;
2089         struct ldlm_lock   *lock = cfs_hash_object(hs, hnode);
2090
2091         lock_res_and_lock(lock);
2092
2093         if (lock->l_req_mode != lock->l_granted_mode) {
2094                 unlock_res_and_lock(lock);
2095                 return 0;
2096         }
2097
2098         LASSERT(lock->l_resource);
2099         if (lock->l_resource->lr_type != LDLM_IBITS &&
2100             lock->l_resource->lr_type != LDLM_PLAIN) {
2101                 unlock_res_and_lock(lock);
2102                 return 0;
2103         }
2104
2105         if (lock->l_flags & LDLM_FL_AST_SENT) {
2106                 unlock_res_and_lock(lock);
2107                 return 0;
2108         }
2109
2110         LASSERT(lock->l_blocking_ast);
2111         LASSERT(!lock->l_blocking_lock);
2112
2113         lock->l_flags |= LDLM_FL_AST_SENT;
2114         if (lock->l_export && lock->l_export->exp_lock_hash &&
2115             !cfs_hlist_unhashed(&lock->l_exp_hash))
2116                 cfs_hash_del(lock->l_export->exp_lock_hash,
2117                              &lock->l_remote_handle, &lock->l_exp_hash);
2118         cfs_list_add_tail(&lock->l_rk_ast, rpc_list);
2119         LDLM_LOCK_GET(lock);
2120
2121         unlock_res_and_lock(lock);
2122         return 0;
2123 }
2124
2125 void ldlm_revoke_export_locks(struct obd_export *exp)
2126 {
2127         cfs_list_t  rpc_list;
2128         ENTRY;
2129
2130         CFS_INIT_LIST_HEAD(&rpc_list);
2131         cfs_hash_for_each_empty(exp->exp_lock_hash,
2132                                 ldlm_revoke_lock_cb, &rpc_list);
2133         ldlm_run_ast_work(&rpc_list, LDLM_WORK_REVOKE_AST);
2134
2135         EXIT;
2136 }
2137
2138 #ifdef __KERNEL__
2139 static struct ldlm_bl_work_item *ldlm_bl_get_work(struct ldlm_bl_pool *blp)
2140 {
2141         struct ldlm_bl_work_item *blwi = NULL;
2142         static unsigned int num_bl = 0;
2143
2144         cfs_spin_lock(&blp->blp_lock);
2145         /* process a request from the blp_list at least every blp_num_threads */
2146         if (!cfs_list_empty(&blp->blp_list) &&
2147             (cfs_list_empty(&blp->blp_prio_list) || num_bl == 0))
2148                 blwi = cfs_list_entry(blp->blp_list.next,
2149                                       struct ldlm_bl_work_item, blwi_entry);
2150         else
2151                 if (!cfs_list_empty(&blp->blp_prio_list))
2152                         blwi = cfs_list_entry(blp->blp_prio_list.next,
2153                                               struct ldlm_bl_work_item,
2154                                               blwi_entry);
2155
2156         if (blwi) {
2157                 if (++num_bl >= cfs_atomic_read(&blp->blp_num_threads))
2158                         num_bl = 0;
2159                 cfs_list_del(&blwi->blwi_entry);
2160         }
2161         cfs_spin_unlock(&blp->blp_lock);
2162
2163         return blwi;
2164 }
2165
2166 /* This only contains temporary data until the thread starts */
2167 struct ldlm_bl_thread_data {
2168         char                    bltd_name[CFS_CURPROC_COMM_MAX];
2169         struct ldlm_bl_pool     *bltd_blp;
2170         cfs_completion_t        bltd_comp;
2171         int                     bltd_num;
2172 };
2173
2174 static int ldlm_bl_thread_main(void *arg);
2175
2176 static int ldlm_bl_thread_start(struct ldlm_bl_pool *blp)
2177 {
2178         struct ldlm_bl_thread_data bltd = { .bltd_blp = blp };
2179         int rc;
2180
2181         cfs_init_completion(&bltd.bltd_comp);
2182         rc = cfs_kernel_thread(ldlm_bl_thread_main, &bltd, 0);
2183         if (rc < 0) {
2184                 CERROR("cannot start LDLM thread ldlm_bl_%02d: rc %d\n",
2185                        cfs_atomic_read(&blp->blp_num_threads), rc);
2186                 return rc;
2187         }
2188         cfs_wait_for_completion(&bltd.bltd_comp);
2189
2190         return 0;
2191 }
2192
2193 static int ldlm_bl_thread_main(void *arg)
2194 {
2195         struct ldlm_bl_pool *blp;
2196         ENTRY;
2197
2198         {
2199                 struct ldlm_bl_thread_data *bltd = arg;
2200
2201                 blp = bltd->bltd_blp;
2202
2203                 bltd->bltd_num =
2204                         cfs_atomic_inc_return(&blp->blp_num_threads) - 1;
2205                 cfs_atomic_inc(&blp->blp_busy_threads);
2206
2207                 snprintf(bltd->bltd_name, sizeof(bltd->bltd_name) - 1,
2208                         "ldlm_bl_%02d", bltd->bltd_num);
2209                 cfs_daemonize(bltd->bltd_name);
2210
2211                 cfs_complete(&bltd->bltd_comp);
2212                 /* cannot use bltd after this, it is only on caller's stack */
2213         }
2214
2215         while (1) {
2216                 struct l_wait_info lwi = { 0 };
2217                 struct ldlm_bl_work_item *blwi = NULL;
2218
2219                 blwi = ldlm_bl_get_work(blp);
2220
2221                 if (blwi == NULL) {
2222                         int busy;
2223
2224                         cfs_atomic_dec(&blp->blp_busy_threads);
2225                         l_wait_event_exclusive(blp->blp_waitq,
2226                                          (blwi = ldlm_bl_get_work(blp)) != NULL,
2227                                          &lwi);
2228                         busy = cfs_atomic_inc_return(&blp->blp_busy_threads);
2229
2230                         if (blwi->blwi_ns == NULL)
2231                                 /* added by ldlm_cleanup() */
2232                                 break;
2233
2234                         /* Not fatal if racy and have a few too many threads */
2235                         if (unlikely(busy < blp->blp_max_threads &&
2236                             busy >= cfs_atomic_read(&blp->blp_num_threads) &&
2237                             !blwi->blwi_mem_pressure))
2238                                 /* discard the return value, we tried */
2239                                 ldlm_bl_thread_start(blp);
2240                 } else {
2241                         if (blwi->blwi_ns == NULL)
2242                                 /* added by ldlm_cleanup() */
2243                                 break;
2244                 }
2245                 if (blwi->blwi_mem_pressure)
2246                         cfs_memory_pressure_set();
2247
2248                 if (blwi->blwi_count) {
2249                         int count;
2250                         /* The special case when we cancel locks in lru
2251                          * asynchronously, we pass the list of locks here.
2252                          * Thus locks are marked LDLM_FL_CANCELING, but NOT
2253                          * canceled locally yet. */
2254                         count = ldlm_cli_cancel_list_local(&blwi->blwi_head,
2255                                                            blwi->blwi_count,
2256                                                            LCF_BL_AST);
2257                         ldlm_cli_cancel_list(&blwi->blwi_head, count, NULL, 0);
2258                 } else {
2259                         ldlm_handle_bl_callback(blwi->blwi_ns, &blwi->blwi_ld,
2260                                                 blwi->blwi_lock);
2261                 }
2262                 if (blwi->blwi_mem_pressure)
2263                         cfs_memory_pressure_clr();
2264
2265                 if (blwi->blwi_mode == LDLM_ASYNC)
2266                         OBD_FREE(blwi, sizeof(*blwi));
2267                 else
2268                         cfs_complete(&blwi->blwi_comp);
2269         }
2270
2271         cfs_atomic_dec(&blp->blp_busy_threads);
2272         cfs_atomic_dec(&blp->blp_num_threads);
2273         cfs_complete(&blp->blp_comp);
2274         RETURN(0);
2275 }
2276
2277 #endif
2278
2279 static int ldlm_setup(void);
2280 static int ldlm_cleanup(void);
2281
2282 int ldlm_get_ref(void)
2283 {
2284         int rc = 0;
2285         ENTRY;
2286         cfs_mutex_down(&ldlm_ref_sem);
2287         if (++ldlm_refcount == 1) {
2288                 rc = ldlm_setup();
2289                 if (rc)
2290                         ldlm_refcount--;
2291         }
2292         cfs_mutex_up(&ldlm_ref_sem);
2293
2294         RETURN(rc);
2295 }
2296
2297 void ldlm_put_ref(void)
2298 {
2299         ENTRY;
2300         cfs_mutex_down(&ldlm_ref_sem);
2301         if (ldlm_refcount == 1) {
2302                 int rc = ldlm_cleanup();
2303                 if (rc)
2304                         CERROR("ldlm_cleanup failed: %d\n", rc);
2305                 else
2306                         ldlm_refcount--;
2307         } else {
2308                 ldlm_refcount--;
2309         }
2310         cfs_mutex_up(&ldlm_ref_sem);
2311
2312         EXIT;
2313 }
2314
2315 /*
2316  * Export handle<->lock hash operations.
2317  */
2318 static unsigned
2319 ldlm_export_lock_hash(cfs_hash_t *hs, const void *key, unsigned mask)
2320 {
2321         return cfs_hash_u64_hash(((struct lustre_handle *)key)->cookie, mask);
2322 }
2323
2324 static void *
2325 ldlm_export_lock_key(cfs_hlist_node_t *hnode)
2326 {
2327         struct ldlm_lock *lock;
2328
2329         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2330         return &lock->l_remote_handle;
2331 }
2332
2333 static void
2334 ldlm_export_lock_keycpy(cfs_hlist_node_t *hnode, void *key)
2335 {
2336         struct ldlm_lock     *lock;
2337
2338         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2339         lock->l_remote_handle = *(struct lustre_handle *)key;
2340 }
2341
2342 static int
2343 ldlm_export_lock_keycmp(const void *key, cfs_hlist_node_t *hnode)
2344 {
2345         return lustre_handle_equal(ldlm_export_lock_key(hnode), key);
2346 }
2347
2348 static void *
2349 ldlm_export_lock_object(cfs_hlist_node_t *hnode)
2350 {
2351         return cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2352 }
2353
2354 static void
2355 ldlm_export_lock_get(cfs_hash_t *hs, cfs_hlist_node_t *hnode)
2356 {
2357         struct ldlm_lock *lock;
2358
2359         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2360         LDLM_LOCK_GET(lock);
2361 }
2362
2363 static void
2364 ldlm_export_lock_put(cfs_hash_t *hs, cfs_hlist_node_t *hnode)
2365 {
2366         struct ldlm_lock *lock;
2367
2368         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2369         LDLM_LOCK_RELEASE(lock);
2370 }
2371
2372 static cfs_hash_ops_t ldlm_export_lock_ops = {
2373         .hs_hash        = ldlm_export_lock_hash,
2374         .hs_key         = ldlm_export_lock_key,
2375         .hs_keycmp      = ldlm_export_lock_keycmp,
2376         .hs_keycpy      = ldlm_export_lock_keycpy,
2377         .hs_object      = ldlm_export_lock_object,
2378         .hs_get         = ldlm_export_lock_get,
2379         .hs_put         = ldlm_export_lock_put,
2380         .hs_put_locked  = ldlm_export_lock_put,
2381 };
2382
2383 int ldlm_init_export(struct obd_export *exp)
2384 {
2385         ENTRY;
2386
2387         exp->exp_lock_hash =
2388                 cfs_hash_create(obd_uuid2str(&exp->exp_client_uuid),
2389                                 HASH_EXP_LOCK_CUR_BITS,
2390                                 HASH_EXP_LOCK_MAX_BITS,
2391                                 HASH_EXP_LOCK_BKT_BITS, 0,
2392                                 CFS_HASH_MIN_THETA, CFS_HASH_MAX_THETA,
2393                                 &ldlm_export_lock_ops,
2394                                 CFS_HASH_DEFAULT | CFS_HASH_REHASH_KEY |
2395                                 CFS_HASH_NBLK_CHANGE);
2396
2397         if (!exp->exp_lock_hash)
2398                 RETURN(-ENOMEM);
2399
2400         RETURN(0);
2401 }
2402 EXPORT_SYMBOL(ldlm_init_export);
2403
2404 void ldlm_destroy_export(struct obd_export *exp)
2405 {
2406         ENTRY;
2407         cfs_hash_putref(exp->exp_lock_hash);
2408         exp->exp_lock_hash = NULL;
2409         EXIT;
2410 }
2411 EXPORT_SYMBOL(ldlm_destroy_export);
2412
2413 static int ldlm_setup(void)
2414 {
2415         struct ldlm_bl_pool *blp;
2416         int rc = 0;
2417         int ldlm_min_threads = LDLM_THREADS_AUTO_MIN;
2418         int ldlm_max_threads = LDLM_THREADS_AUTO_MAX;
2419 #ifdef __KERNEL__
2420         int i;
2421 #endif
2422         ENTRY;
2423
2424         if (ldlm_state != NULL)
2425                 RETURN(-EALREADY);
2426
2427         OBD_ALLOC(ldlm_state, sizeof(*ldlm_state));
2428         if (ldlm_state == NULL)
2429                 RETURN(-ENOMEM);
2430
2431 #ifdef LPROCFS
2432         rc = ldlm_proc_setup();
2433         if (rc != 0)
2434                 GOTO(out_free, rc);
2435 #endif
2436
2437 #ifdef __KERNEL__
2438         if (ldlm_num_threads) {
2439                 /* If ldlm_num_threads is set, it is the min and the max. */
2440                 if (ldlm_num_threads > LDLM_THREADS_AUTO_MAX)
2441                         ldlm_num_threads = LDLM_THREADS_AUTO_MAX;
2442                 if (ldlm_num_threads < LDLM_THREADS_AUTO_MIN)
2443                         ldlm_num_threads = LDLM_THREADS_AUTO_MIN;
2444                 ldlm_min_threads = ldlm_max_threads = ldlm_num_threads;
2445         }
2446 #endif
2447
2448         ldlm_state->ldlm_cb_service =
2449                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
2450                                 LDLM_MAXREPSIZE, LDLM_CB_REQUEST_PORTAL,
2451                                 LDLM_CB_REPLY_PORTAL, 2,
2452                                 ldlm_callback_handler, "ldlm_cbd",
2453                                 ldlm_svc_proc_dir, NULL,
2454                                 ldlm_min_threads, ldlm_max_threads,
2455                                 "ldlm_cb",
2456                                 LCT_MD_THREAD|LCT_DT_THREAD, NULL);
2457
2458         if (!ldlm_state->ldlm_cb_service) {
2459                 CERROR("failed to start service\n");
2460                 GOTO(out_proc, rc = -ENOMEM);
2461         }
2462
2463         ldlm_state->ldlm_cancel_service =
2464                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
2465                                 LDLM_MAXREPSIZE, LDLM_CANCEL_REQUEST_PORTAL,
2466                                 LDLM_CANCEL_REPLY_PORTAL, 6,
2467                                 ldlm_cancel_handler, "ldlm_canceld",
2468                                 ldlm_svc_proc_dir, NULL,
2469                                 ldlm_min_threads, ldlm_max_threads,
2470                                 "ldlm_cn",
2471                                 LCT_MD_THREAD|LCT_DT_THREAD|LCT_CL_THREAD,
2472                                 NULL);
2473
2474         if (!ldlm_state->ldlm_cancel_service) {
2475                 CERROR("failed to start service\n");
2476                 GOTO(out_proc, rc = -ENOMEM);
2477         }
2478
2479         OBD_ALLOC(blp, sizeof(*blp));
2480         if (blp == NULL)
2481                 GOTO(out_proc, rc = -ENOMEM);
2482         ldlm_state->ldlm_bl_pool = blp;
2483
2484         cfs_spin_lock_init(&blp->blp_lock);
2485         CFS_INIT_LIST_HEAD(&blp->blp_list);
2486         CFS_INIT_LIST_HEAD(&blp->blp_prio_list);
2487         cfs_waitq_init(&blp->blp_waitq);
2488         cfs_atomic_set(&blp->blp_num_threads, 0);
2489         cfs_atomic_set(&blp->blp_busy_threads, 0);
2490         blp->blp_min_threads = ldlm_min_threads;
2491         blp->blp_max_threads = ldlm_max_threads;
2492
2493 #ifdef __KERNEL__
2494         for (i = 0; i < blp->blp_min_threads; i++) {
2495                 rc = ldlm_bl_thread_start(blp);
2496                 if (rc < 0)
2497                         GOTO(out_thread, rc);
2498         }
2499
2500         rc = ptlrpc_start_threads(ldlm_state->ldlm_cancel_service);
2501         if (rc)
2502                 GOTO(out_thread, rc);
2503
2504         rc = ptlrpc_start_threads(ldlm_state->ldlm_cb_service);
2505         if (rc)
2506                 GOTO(out_thread, rc);
2507
2508         CFS_INIT_LIST_HEAD(&expired_lock_thread.elt_expired_locks);
2509         expired_lock_thread.elt_state = ELT_STOPPED;
2510         cfs_waitq_init(&expired_lock_thread.elt_waitq);
2511
2512         CFS_INIT_LIST_HEAD(&waiting_locks_list);
2513         cfs_spin_lock_init(&waiting_locks_spinlock);
2514         cfs_timer_init(&waiting_locks_timer, waiting_locks_callback, 0);
2515
2516         rc = cfs_kernel_thread(expired_lock_main, NULL, CLONE_VM | CLONE_FILES);
2517         if (rc < 0) {
2518                 CERROR("Cannot start ldlm expired-lock thread: %d\n", rc);
2519                 GOTO(out_thread, rc);
2520         }
2521
2522         cfs_wait_event(expired_lock_thread.elt_waitq,
2523                        expired_lock_thread.elt_state == ELT_READY);
2524 #endif
2525
2526 #ifdef __KERNEL__
2527         rc = ldlm_pools_init();
2528         if (rc)
2529                 GOTO(out_thread, rc);
2530 #endif
2531         RETURN(0);
2532
2533 #ifdef __KERNEL__
2534  out_thread:
2535         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2536         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2537 #endif
2538
2539  out_proc:
2540 #ifdef LPROCFS
2541         ldlm_proc_cleanup();
2542  out_free:
2543 #endif
2544         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
2545         ldlm_state = NULL;
2546         return rc;
2547 }
2548
2549 static int ldlm_cleanup(void)
2550 {
2551 #ifdef __KERNEL__
2552         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
2553 #endif
2554         ENTRY;
2555
2556         if (!cfs_list_empty(ldlm_namespace_list(LDLM_NAMESPACE_SERVER)) ||
2557             !cfs_list_empty(ldlm_namespace_list(LDLM_NAMESPACE_CLIENT))) {
2558                 CERROR("ldlm still has namespaces; clean these up first.\n");
2559                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
2560                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
2561                 RETURN(-EBUSY);
2562         }
2563
2564 #ifdef __KERNEL__
2565         ldlm_pools_fini();
2566 #endif
2567
2568 #ifdef __KERNEL__
2569         while (cfs_atomic_read(&blp->blp_num_threads) > 0) {
2570                 struct ldlm_bl_work_item blwi = { .blwi_ns = NULL };
2571
2572                 cfs_init_completion(&blp->blp_comp);
2573
2574                 cfs_spin_lock(&blp->blp_lock);
2575                 cfs_list_add_tail(&blwi.blwi_entry, &blp->blp_list);
2576                 cfs_waitq_signal(&blp->blp_waitq);
2577                 cfs_spin_unlock(&blp->blp_lock);
2578
2579                 cfs_wait_for_completion(&blp->blp_comp);
2580         }
2581         OBD_FREE(blp, sizeof(*blp));
2582
2583         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2584         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2585         ldlm_proc_cleanup();
2586
2587         expired_lock_thread.elt_state = ELT_TERMINATE;
2588         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
2589         cfs_wait_event(expired_lock_thread.elt_waitq,
2590                        expired_lock_thread.elt_state == ELT_STOPPED);
2591 #else
2592         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2593         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2594 #endif
2595
2596         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
2597         ldlm_state = NULL;
2598
2599         RETURN(0);
2600 }
2601
2602 int __init ldlm_init(void)
2603 {
2604         cfs_init_mutex(&ldlm_ref_sem);
2605         cfs_init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_SERVER));
2606         cfs_init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
2607         ldlm_resource_slab = cfs_mem_cache_create("ldlm_resources",
2608                                                sizeof(struct ldlm_resource), 0,
2609                                                CFS_SLAB_HWCACHE_ALIGN);
2610         if (ldlm_resource_slab == NULL)
2611                 return -ENOMEM;
2612
2613         ldlm_lock_slab = cfs_mem_cache_create("ldlm_locks",
2614                               sizeof(struct ldlm_lock), 0,
2615                               CFS_SLAB_HWCACHE_ALIGN | CFS_SLAB_DESTROY_BY_RCU);
2616         if (ldlm_lock_slab == NULL) {
2617                 cfs_mem_cache_destroy(ldlm_resource_slab);
2618                 return -ENOMEM;
2619         }
2620
2621         ldlm_interval_slab = cfs_mem_cache_create("interval_node",
2622                                         sizeof(struct ldlm_interval),
2623                                         0, CFS_SLAB_HWCACHE_ALIGN);
2624         if (ldlm_interval_slab == NULL) {
2625                 cfs_mem_cache_destroy(ldlm_resource_slab);
2626                 cfs_mem_cache_destroy(ldlm_lock_slab);
2627                 return -ENOMEM;
2628         }
2629 #if LUSTRE_TRACKS_LOCK_EXP_REFS
2630         class_export_dump_hook = ldlm_dump_export_locks;
2631 #endif
2632         return 0;
2633 }
2634
2635 void __exit ldlm_exit(void)
2636 {
2637         int rc;
2638         if (ldlm_refcount)
2639                 CERROR("ldlm_refcount is %d in ldlm_exit!\n", ldlm_refcount);
2640         rc = cfs_mem_cache_destroy(ldlm_resource_slab);
2641         LASSERTF(rc == 0, "couldn't free ldlm resource slab\n");
2642 #ifdef __KERNEL__
2643         /* ldlm_lock_put() use RCU to call ldlm_lock_free, so need call
2644          * synchronize_rcu() to wait a grace period elapsed, so that
2645          * ldlm_lock_free() get a chance to be called. */
2646         synchronize_rcu();
2647 #endif
2648         rc = cfs_mem_cache_destroy(ldlm_lock_slab);
2649         LASSERTF(rc == 0, "couldn't free ldlm lock slab\n");
2650         rc = cfs_mem_cache_destroy(ldlm_interval_slab);
2651         LASSERTF(rc == 0, "couldn't free interval node slab\n");
2652 }
2653
2654 /* ldlm_extent.c */
2655 EXPORT_SYMBOL(ldlm_extent_shift_kms);
2656
2657 /* ldlm_lock.c */
2658 EXPORT_SYMBOL(ldlm_get_processing_policy);
2659 EXPORT_SYMBOL(ldlm_lock2desc);
2660 EXPORT_SYMBOL(ldlm_register_intent);
2661 EXPORT_SYMBOL(ldlm_lockname);
2662 EXPORT_SYMBOL(ldlm_typename);
2663 EXPORT_SYMBOL(ldlm_lock2handle);
2664 EXPORT_SYMBOL(__ldlm_handle2lock);
2665 EXPORT_SYMBOL(ldlm_lock_get);
2666 EXPORT_SYMBOL(ldlm_lock_put);
2667 EXPORT_SYMBOL(ldlm_lock_match);
2668 EXPORT_SYMBOL(ldlm_lock_cancel);
2669 EXPORT_SYMBOL(ldlm_lock_addref);
2670 EXPORT_SYMBOL(ldlm_lock_addref_try);
2671 EXPORT_SYMBOL(ldlm_lock_decref);
2672 EXPORT_SYMBOL(ldlm_lock_decref_and_cancel);
2673 EXPORT_SYMBOL(ldlm_lock_change_resource);
2674 EXPORT_SYMBOL(ldlm_it2str);
2675 EXPORT_SYMBOL(ldlm_lock_dump);
2676 EXPORT_SYMBOL(ldlm_lock_dump_handle);
2677 EXPORT_SYMBOL(ldlm_reprocess_all_ns);
2678 EXPORT_SYMBOL(ldlm_lock_allow_match_locked);
2679 EXPORT_SYMBOL(ldlm_lock_allow_match);
2680 EXPORT_SYMBOL(ldlm_lock_downgrade);
2681 EXPORT_SYMBOL(ldlm_lock_convert);
2682
2683 /* ldlm_request.c */
2684 EXPORT_SYMBOL(ldlm_completion_ast_async);
2685 EXPORT_SYMBOL(ldlm_blocking_ast_nocheck);
2686 EXPORT_SYMBOL(ldlm_completion_ast);
2687 EXPORT_SYMBOL(ldlm_blocking_ast);
2688 EXPORT_SYMBOL(ldlm_glimpse_ast);
2689 EXPORT_SYMBOL(ldlm_expired_completion_wait);
2690 EXPORT_SYMBOL(ldlm_prep_enqueue_req);
2691 EXPORT_SYMBOL(ldlm_prep_elc_req);
2692 EXPORT_SYMBOL(ldlm_cli_convert);
2693 EXPORT_SYMBOL(ldlm_cli_enqueue);
2694 EXPORT_SYMBOL(ldlm_cli_enqueue_fini);
2695 EXPORT_SYMBOL(ldlm_cli_enqueue_local);
2696 EXPORT_SYMBOL(ldlm_cli_cancel);
2697 EXPORT_SYMBOL(ldlm_cli_cancel_unused);
2698 EXPORT_SYMBOL(ldlm_cli_cancel_unused_resource);
2699 EXPORT_SYMBOL(ldlm_cli_cancel_req);
2700 EXPORT_SYMBOL(ldlm_replay_locks);
2701 EXPORT_SYMBOL(ldlm_resource_foreach);
2702 EXPORT_SYMBOL(ldlm_namespace_foreach);
2703 EXPORT_SYMBOL(ldlm_resource_iterate);
2704 EXPORT_SYMBOL(ldlm_cancel_resource_local);
2705 EXPORT_SYMBOL(ldlm_cli_cancel_list_local);
2706 EXPORT_SYMBOL(ldlm_cli_cancel_list);
2707
2708 /* ldlm_lockd.c */
2709 EXPORT_SYMBOL(ldlm_server_blocking_ast);
2710 EXPORT_SYMBOL(ldlm_server_completion_ast);
2711 EXPORT_SYMBOL(ldlm_server_glimpse_ast);
2712 EXPORT_SYMBOL(ldlm_handle_enqueue);
2713 EXPORT_SYMBOL(ldlm_handle_enqueue0);
2714 EXPORT_SYMBOL(ldlm_handle_cancel);
2715 EXPORT_SYMBOL(ldlm_request_cancel);
2716 EXPORT_SYMBOL(ldlm_handle_convert);
2717 EXPORT_SYMBOL(ldlm_handle_convert0);
2718 EXPORT_SYMBOL(ldlm_del_waiting_lock);
2719 EXPORT_SYMBOL(ldlm_get_ref);
2720 EXPORT_SYMBOL(ldlm_put_ref);
2721 EXPORT_SYMBOL(ldlm_refresh_waiting_lock);
2722 EXPORT_SYMBOL(ldlm_revoke_export_locks);
2723
2724 /* ldlm_resource.c */
2725 EXPORT_SYMBOL(ldlm_namespace_new);
2726 EXPORT_SYMBOL(ldlm_namespace_cleanup);
2727 EXPORT_SYMBOL(ldlm_namespace_free);
2728 EXPORT_SYMBOL(ldlm_namespace_dump);
2729 EXPORT_SYMBOL(ldlm_dump_all_namespaces);
2730 EXPORT_SYMBOL(ldlm_resource_get);
2731 EXPORT_SYMBOL(ldlm_resource_putref);
2732 EXPORT_SYMBOL(ldlm_resource_unlink_lock);
2733
2734 /* ldlm_lib.c */
2735 EXPORT_SYMBOL(client_import_add_conn);
2736 EXPORT_SYMBOL(client_import_del_conn);
2737 EXPORT_SYMBOL(client_obd_setup);
2738 EXPORT_SYMBOL(client_obd_cleanup);
2739 EXPORT_SYMBOL(client_connect_import);
2740 EXPORT_SYMBOL(client_disconnect_export);
2741 EXPORT_SYMBOL(server_disconnect_export);
2742 EXPORT_SYMBOL(target_stop_recovery_thread);
2743 EXPORT_SYMBOL(target_handle_connect);
2744 EXPORT_SYMBOL(target_cleanup_recovery);
2745 EXPORT_SYMBOL(target_destroy_export);
2746 EXPORT_SYMBOL(target_cancel_recovery_timer);
2747 EXPORT_SYMBOL(target_send_reply);
2748 EXPORT_SYMBOL(target_queue_recovery_request);
2749 EXPORT_SYMBOL(target_handle_ping);
2750 EXPORT_SYMBOL(target_pack_pool_reply);
2751 EXPORT_SYMBOL(target_handle_disconnect);
2752
2753 /* l_lock.c */
2754 EXPORT_SYMBOL(lock_res_and_lock);
2755 EXPORT_SYMBOL(unlock_res_and_lock);