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