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