Whamcloud - gitweb
Branch HEAD
[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  * Copyright (C) 2002-2004 Cluster File Systems, Inc.
5  *   Author: Peter Braam <braam@clusterfs.com>
6  *   Author: Phil Schwan <phil@clusterfs.com>
7  *
8  *   This file is part of the Lustre file system, http://www.lustre.org
9  *   Lustre is a trademark of Cluster File Systems, Inc.
10  *
11  *   You may have signed or agreed to another license before downloading
12  *   this software.  If so, you are bound by the terms and conditions
13  *   of that agreement, and the following does not apply to you.  See the
14  *   LICENSE file included with this distribution for more information.
15  *
16  *   If you did not agree to a different license, then this copy of Lustre
17  *   is open source software; you can redistribute it and/or modify it
18  *   under the terms of version 2 of the GNU General Public License as
19  *   published by the Free Software Foundation.
20  *
21  *   In either case, Lustre is distributed in the hope that it will be
22  *   useful, but WITHOUT ANY WARRANTY; without even the implied warranty
23  *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  *   license text for more details.
25  */
26
27 #ifndef EXPORT_SYMTAB
28 # define EXPORT_SYMTAB
29 #endif
30 #define DEBUG_SUBSYSTEM S_LDLM
31
32 #ifdef __KERNEL__
33 # include <libcfs/libcfs.h>
34 #else
35 # include <liblustre.h>
36 #endif
37
38 #include <lustre_dlm.h>
39 #include <obd_class.h>
40 #include <libcfs/list.h>
41 #include "ldlm_internal.h"
42
43 extern cfs_mem_cache_t *ldlm_resource_slab;
44 extern cfs_mem_cache_t *ldlm_lock_slab;
45 static struct semaphore ldlm_ref_sem;
46 static int ldlm_refcount;
47
48 /* LDLM state */
49
50 static struct ldlm_state *ldlm_state;
51
52 inline cfs_time_t round_timeout(cfs_time_t timeout)
53 {
54         return cfs_time_seconds((int)cfs_duration_sec(cfs_time_sub(timeout, 0)) + 1);
55 }
56
57 /* timeout for initial callback (AST) reply */
58 static inline unsigned int ldlm_get_rq_timeout(unsigned int ldlm_timeout,
59                                                unsigned int obd_timeout)
60 {
61         unsigned int timeout = min(ldlm_timeout, obd_timeout / 3);
62
63         return timeout < 1 ? 1 : timeout;
64 }
65
66 #ifdef __KERNEL__
67 /* w_l_spinlock protects both waiting_locks_list and expired_lock_thread */
68 static spinlock_t waiting_locks_spinlock;   /* BH lock (timer) */
69 static struct list_head waiting_locks_list;
70 static cfs_timer_t waiting_locks_timer;
71
72 static struct expired_lock_thread {
73         cfs_waitq_t               elt_waitq;
74         int                       elt_state;
75         int                       elt_dump;
76         struct list_head          elt_expired_locks;
77 } expired_lock_thread;
78 #endif
79
80 #define ELT_STOPPED   0
81 #define ELT_READY     1
82 #define ELT_TERMINATE 2
83
84 struct ldlm_bl_pool {
85         spinlock_t              blp_lock;
86         struct list_head        blp_list;
87         cfs_waitq_t             blp_waitq;
88         atomic_t                blp_num_threads;
89         struct completion       blp_comp;
90 };
91
92 struct ldlm_bl_work_item {
93         struct list_head        blwi_entry;
94         struct ldlm_namespace   *blwi_ns;
95         struct ldlm_lock_desc   blwi_ld;
96         struct ldlm_lock        *blwi_lock;
97         struct list_head        blwi_head;
98         int                     blwi_count;
99 };
100
101 #ifdef __KERNEL__
102
103 static inline int have_expired_locks(void)
104 {
105         int need_to_run;
106
107         ENTRY;
108         spin_lock_bh(&waiting_locks_spinlock);
109         need_to_run = !list_empty(&expired_lock_thread.elt_expired_locks);
110         spin_unlock_bh(&waiting_locks_spinlock);
111
112         RETURN(need_to_run);
113 }
114
115 static int expired_lock_main(void *arg)
116 {
117         struct list_head *expired = &expired_lock_thread.elt_expired_locks;
118         struct l_wait_info lwi = { 0 };
119         int do_dump;
120
121         ENTRY;
122         cfs_daemonize("ldlm_elt");
123
124         expired_lock_thread.elt_state = ELT_READY;
125         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
126
127         while (1) {
128                 l_wait_event(expired_lock_thread.elt_waitq,
129                              have_expired_locks() ||
130                              expired_lock_thread.elt_state == ELT_TERMINATE,
131                              &lwi);
132
133                 spin_lock_bh(&waiting_locks_spinlock);
134                 if (expired_lock_thread.elt_dump) {
135                         spin_unlock_bh(&waiting_locks_spinlock);
136
137                         /* from waiting_locks_callback, but not in timer */
138                         libcfs_debug_dumplog();
139                         libcfs_run_lbug_upcall(__FILE__,
140                                                 "waiting_locks_callback",
141                                                 expired_lock_thread.elt_dump);
142
143                         spin_lock_bh(&waiting_locks_spinlock);
144                         expired_lock_thread.elt_dump = 0;
145                 }
146
147                 do_dump = 0;
148
149                 while (!list_empty(expired)) {
150                         struct obd_export *export;
151                         struct ldlm_lock *lock;
152
153                         lock = list_entry(expired->next, struct ldlm_lock,
154                                           l_pending_chain);
155                         if ((void *)lock < LP_POISON + CFS_PAGE_SIZE &&
156                             (void *)lock >= LP_POISON) {
157                                 spin_unlock_bh(&waiting_locks_spinlock);
158                                 CERROR("free lock on elt list %p\n", lock);
159                                 LBUG();
160                         }
161                         list_del_init(&lock->l_pending_chain);
162                         if ((void *)lock->l_export < LP_POISON + CFS_PAGE_SIZE &&
163                             (void *)lock->l_export >= LP_POISON) {
164                                 CERROR("lock with free export on elt list %p\n",
165                                        lock->l_export);
166                                 lock->l_export = NULL;
167                                 LDLM_ERROR(lock, "free export");
168                                 continue;
169                         }
170                         export = class_export_get(lock->l_export);
171                         spin_unlock_bh(&waiting_locks_spinlock);
172
173                         do_dump++;
174                         class_fail_export(export);
175                         class_export_put(export);
176                         spin_lock_bh(&waiting_locks_spinlock);
177                 }
178                 spin_unlock_bh(&waiting_locks_spinlock);
179
180                 if (do_dump && obd_dump_on_eviction) {
181                         CERROR("dump the log upon eviction\n");
182                         libcfs_debug_dumplog();
183                 }
184
185                 if (expired_lock_thread.elt_state == ELT_TERMINATE)
186                         break;
187         }
188
189         expired_lock_thread.elt_state = ELT_STOPPED;
190         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
191         RETURN(0);
192 }
193
194 static int ldlm_add_waiting_lock(struct ldlm_lock *lock);
195
196 /* This is called from within a timer interrupt and cannot schedule */
197 static void waiting_locks_callback(unsigned long unused)
198 {
199         struct ldlm_lock *lock, *last = NULL;
200
201 repeat:
202         spin_lock_bh(&waiting_locks_spinlock);
203         while (!list_empty(&waiting_locks_list)) {
204                 lock = list_entry(waiting_locks_list.next, struct ldlm_lock,
205                                   l_pending_chain);
206
207                 if (cfs_time_after(lock->l_callback_timeout, cfs_time_current()) ||
208                     (lock->l_req_mode == LCK_GROUP))
209                         break;
210
211                 if (ptlrpc_check_suspend()) {
212                         /* there is a case when we talk to one mds, holding
213                          * lock from another mds. this way we easily can get
214                          * here, if second mds is being recovered. so, we
215                          * suspend timeouts. bug 6019 */
216
217                         LDLM_ERROR(lock, "recharge timeout: %s@%s nid %s ",
218                                    lock->l_export->exp_client_uuid.uuid,
219                                    lock->l_export->exp_connection->c_remote_uuid.uuid,
220                                    libcfs_nid2str(lock->l_export->exp_connection->c_peer.nid));
221
222                         list_del_init(&lock->l_pending_chain);
223                         spin_unlock_bh(&waiting_locks_spinlock);
224                         ldlm_add_waiting_lock(lock);
225                         goto repeat;
226                 }
227
228                 /* if timeout overlaps the activation time of suspended timeouts
229                  * then extend it to give a chance for client to reconnect */
230                 if (cfs_time_before(cfs_time_sub(lock->l_callback_timeout,
231                                                  cfs_time_seconds(obd_timeout)/2),
232                                     ptlrpc_suspend_wakeup_time())) {
233                         LDLM_ERROR(lock, "extend timeout due to recovery: %s@%s nid %s ",
234                                    lock->l_export->exp_client_uuid.uuid,
235                                    lock->l_export->exp_connection->c_remote_uuid.uuid,
236                                    libcfs_nid2str(lock->l_export->exp_connection->c_peer.nid));
237
238                         list_del_init(&lock->l_pending_chain);
239                         spin_unlock_bh(&waiting_locks_spinlock);
240                         ldlm_add_waiting_lock(lock);
241                         goto repeat;
242                 }
243
244                 LDLM_ERROR(lock, "lock callback timer expired: evicting client "
245                            "%s@%s nid %s\n",
246                            lock->l_export->exp_client_uuid.uuid,
247                            lock->l_export->exp_connection->c_remote_uuid.uuid,
248                            libcfs_nid2str(lock->l_export->exp_connection->c_peer.nid));
249
250                 last = lock;
251
252                 list_del(&lock->l_pending_chain);
253                 list_add(&lock->l_pending_chain,
254                          &expired_lock_thread.elt_expired_locks);
255         }
256
257         if (!list_empty(&expired_lock_thread.elt_expired_locks)) {
258                 if (obd_dump_on_timeout)
259                         expired_lock_thread.elt_dump = __LINE__;
260
261                 cfs_waitq_signal(&expired_lock_thread.elt_waitq);
262         }
263
264         /*
265          * Make sure the timer will fire again if we have any locks
266          * left.
267          */
268         if (!list_empty(&waiting_locks_list)) {
269                 cfs_time_t timeout_rounded;
270                 lock = list_entry(waiting_locks_list.next, struct ldlm_lock,
271                                   l_pending_chain);
272                 timeout_rounded = (cfs_time_t)round_timeout(lock->l_callback_timeout);
273                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
274         }
275         spin_unlock_bh(&waiting_locks_spinlock);
276 }
277
278 /*
279  * Indicate that we're waiting for a client to call us back cancelling a given
280  * lock.  We add it to the pending-callback chain, and schedule the lock-timeout
281  * timer to fire appropriately.  (We round up to the next second, to avoid
282  * floods of timer firings during periods of high lock contention and traffic).
283  *
284  * Called with the namespace lock held.
285  */
286 static int __ldlm_add_waiting_lock(struct ldlm_lock *lock)
287 {
288         cfs_time_t timeout_rounded;
289
290         if (!list_empty(&lock->l_pending_chain))
291                 return 0;
292
293         lock->l_callback_timeout =cfs_time_add(cfs_time_current(),
294                                                cfs_time_seconds(obd_timeout)/2);
295
296         timeout_rounded = round_timeout(lock->l_callback_timeout);
297
298         if (cfs_time_before(timeout_rounded, cfs_timer_deadline(&waiting_locks_timer)) ||
299             !cfs_timer_is_armed(&waiting_locks_timer)) {
300                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
301
302         }
303         list_add_tail(&lock->l_pending_chain, &waiting_locks_list); /* FIFO */
304         return 1;
305 }
306
307 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
308 {
309         int ret;
310
311         LASSERT(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK));
312
313         spin_lock_bh(&waiting_locks_spinlock);
314         if (lock->l_destroyed) {
315                 static cfs_time_t next;
316                 spin_unlock_bh(&waiting_locks_spinlock);
317                 LDLM_ERROR(lock, "not waiting on destroyed lock (bug 5653)");
318                 if (cfs_time_after(cfs_time_current(), next)) {
319                         next = cfs_time_shift(14400);
320                         libcfs_debug_dumpstack(NULL);
321                 }
322                 return 0;
323         }
324
325         ret = __ldlm_add_waiting_lock(lock);
326         spin_unlock_bh(&waiting_locks_spinlock);
327
328         LDLM_DEBUG(lock, "%sadding to wait list",
329                    ret == 0 ? "not re-" : "");
330         return ret;
331 }
332
333 /*
334  * Remove a lock from the pending list, likely because it had its cancellation
335  * callback arrive without incident.  This adjusts the lock-timeout timer if
336  * needed.  Returns 0 if the lock wasn't pending after all, 1 if it was.
337  *
338  * Called with namespace lock held.
339  */
340 int __ldlm_del_waiting_lock(struct ldlm_lock *lock)
341 {
342         struct list_head *list_next;
343
344         if (list_empty(&lock->l_pending_chain))
345                 return 0;
346
347         list_next = lock->l_pending_chain.next;
348         if (lock->l_pending_chain.prev == &waiting_locks_list) {
349                 /* Removing the head of the list, adjust timer. */
350                 if (list_next == &waiting_locks_list) {
351                         /* No more, just cancel. */
352                         cfs_timer_disarm(&waiting_locks_timer);
353                 } else {
354                         struct ldlm_lock *next;
355                         next = list_entry(list_next, struct ldlm_lock,
356                                           l_pending_chain);
357                         cfs_timer_arm(&waiting_locks_timer,
358                                       round_timeout(next->l_callback_timeout));
359                 }
360         }
361         list_del_init(&lock->l_pending_chain);
362
363         return 1;
364 }
365
366 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
367 {
368         int ret;
369
370         if (lock->l_export == NULL) {
371                 /* We don't have a "waiting locks list" on clients. */
372                 LDLM_DEBUG(lock, "client lock: no-op");
373                 return 0;
374         }
375
376         spin_lock_bh(&waiting_locks_spinlock);
377         ret = __ldlm_del_waiting_lock(lock);
378         spin_unlock_bh(&waiting_locks_spinlock);
379
380         LDLM_DEBUG(lock, "%s", ret == 0 ? "wasn't waiting" : "removed");
381         return ret;
382 }
383
384 /*
385  * Prolong the lock
386  *
387  * Called with namespace lock held.
388  */
389 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock)
390 {
391         if (lock->l_export == NULL) {
392                 /* We don't have a "waiting locks list" on clients. */
393                 LDLM_DEBUG(lock, "client lock: no-op");
394                 return 0;
395         }
396
397         spin_lock_bh(&waiting_locks_spinlock);
398
399         if (list_empty(&lock->l_pending_chain)) {
400                 spin_unlock_bh(&waiting_locks_spinlock);
401                 LDLM_DEBUG(lock, "wasn't waiting");
402                 return 0;
403         }
404
405         __ldlm_del_waiting_lock(lock);
406         __ldlm_add_waiting_lock(lock);
407         spin_unlock_bh(&waiting_locks_spinlock);
408
409         LDLM_DEBUG(lock, "refreshed");
410         return 1;
411 }
412
413 #else /* !__KERNEL__ */
414
415 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
416 {
417         LASSERT(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK));
418         RETURN(1);
419 }
420
421 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
422 {
423         RETURN(0);
424 }
425
426 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock)
427 {
428         RETURN(0);
429 }
430 #endif /* __KERNEL__ */
431
432 static void ldlm_failed_ast(struct ldlm_lock *lock, int rc,
433                             const char *ast_type)
434 {
435         struct ptlrpc_connection *conn = lock->l_export->exp_connection;
436         char                     *str = libcfs_nid2str(conn->c_peer.nid);
437
438         LCONSOLE_ERROR_MSG(0x138, "A client on nid %s was evicted from "
439                            "service %s.\n", str,
440                            lock->l_export->exp_obd->obd_name);
441
442         LCONSOLE_ERROR_MSG(0x012, "Lock %s callback to %s timed out for "
443                            "resource %d\n", ast_type,
444                            obd_export_nid2str(lock->l_export), rc);
445
446         if (obd_dump_on_timeout)
447                 libcfs_debug_dumplog();
448         class_fail_export(lock->l_export);
449 }
450
451 static int ldlm_handle_ast_error(struct ldlm_lock *lock,
452                                  struct ptlrpc_request *req, int rc,
453                                  const char *ast_type)
454 {
455         lnet_process_id_t peer = req->rq_import->imp_connection->c_peer;
456
457         if (rc == -ETIMEDOUT || rc == -EINTR || rc == -ENOTCONN) {
458                 LASSERT(lock->l_export);
459                 if (lock->l_export->exp_libclient) {
460                         LDLM_DEBUG(lock, "%s AST to liblustre client (nid %s)"
461                                    " timeout, just cancelling lock", ast_type,
462                                    libcfs_nid2str(peer.nid));
463                         ldlm_lock_cancel(lock);
464                         rc = -ERESTART;
465                 } else if (lock->l_flags & LDLM_FL_CANCEL) {
466                         LDLM_DEBUG(lock, "%s AST timeout from nid %s, but "
467                                    "cancel was received (AST reply lost?)",
468                                    ast_type, libcfs_nid2str(peer.nid));
469                         ldlm_lock_cancel(lock);
470                         rc = -ERESTART;
471                 } else {
472                         ldlm_del_waiting_lock(lock);
473                         ldlm_failed_ast(lock, rc, ast_type);
474                 }
475         } else if (rc) {
476                 if (rc == -EINVAL)
477                         LDLM_DEBUG(lock, "client (nid %s) returned %d"
478                                " from %s AST - normal race",
479                                libcfs_nid2str(peer.nid),
480                                req->rq_repmsg ?
481                                lustre_msg_get_status(req->rq_repmsg) : -1,
482                                ast_type);
483                 else
484                         LDLM_ERROR(lock, "client (nid %s) returned %d "
485                                    "from %s AST", libcfs_nid2str(peer.nid),
486                                    (req->rq_repmsg != NULL) ?
487                                    lustre_msg_get_status(req->rq_repmsg) : 0,
488                                    ast_type);
489                 ldlm_lock_cancel(lock);
490                 /* Server-side AST functions are called from ldlm_reprocess_all,
491                  * which needs to be told to please restart its reprocessing. */
492                 rc = -ERESTART;
493         }
494
495         return rc;
496 }
497
498 /*
499  * ->l_blocking_ast() method for server-side locks. This is invoked when newly
500  * enqueued server lock conflicts with given one.
501  *
502  * Sends blocking ast rpc to the client owning that lock; arms timeout timer
503  * to wait for client response.
504  */
505 int ldlm_server_blocking_ast(struct ldlm_lock *lock,
506                              struct ldlm_lock_desc *desc,
507                              void *data, int flag)
508 {
509         struct ldlm_request *body;
510         struct ptlrpc_request *req;
511         int size[] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
512                        [DLM_LOCKREQ_OFF]     = sizeof(*body) };
513         int instant_cancel = 0, rc = 0;
514         ENTRY;
515
516         if (flag == LDLM_CB_CANCELING) {
517                 /* Don't need to do anything here. */
518                 RETURN(0);
519         }
520
521         LASSERT(lock);
522         if (lock->l_export->exp_obd->obd_recovering != 0) {
523                 LDLM_ERROR(lock, "BUG 6063: lock collide during recovery");
524                 ldlm_lock_dump(D_ERROR, lock, 0);
525         }
526
527         req = ptlrpc_prep_req(lock->l_export->exp_imp_reverse,
528                               LUSTRE_DLM_VERSION, LDLM_BL_CALLBACK, 2, size,
529                               NULL);
530         if (req == NULL)
531                 RETURN(-ENOMEM);
532
533         lock_res(lock->l_resource);
534         if (lock->l_granted_mode != lock->l_req_mode) {
535                 /* this blocking AST will be communicated as part of the
536                  * completion AST instead */
537                 unlock_res(lock->l_resource);
538                 ptlrpc_req_finished(req);
539                 LDLM_DEBUG(lock, "lock not granted, not sending blocking AST");
540                 RETURN(0);
541         }
542
543         if (lock->l_destroyed) {
544                 /* What's the point? */
545                 unlock_res(lock->l_resource);
546                 ptlrpc_req_finished(req);
547                 RETURN(0);
548         }
549
550         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
551                 instant_cancel = 1;
552
553         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
554         body->lock_handle[0] = lock->l_remote_handle;
555         body->lock_desc = *desc;
556         body->lock_flags |= (lock->l_flags & LDLM_AST_FLAGS);
557
558         LDLM_DEBUG(lock, "server preparing blocking AST");
559
560         ptlrpc_req_set_repsize(req, 1, NULL);
561         if (instant_cancel) {
562                 unlock_res(lock->l_resource);
563                 ldlm_lock_cancel(lock);
564         } else {
565                 LASSERT(lock->l_granted_mode == lock->l_req_mode);
566                 ldlm_add_waiting_lock(lock);
567                 unlock_res(lock->l_resource);
568         }
569
570         req->rq_send_state = LUSTRE_IMP_FULL;
571         req->rq_timeout = ldlm_get_rq_timeout(ldlm_timeout, obd_timeout);
572
573         if (lock->l_export && lock->l_export->exp_ldlm_stats)
574                 lprocfs_counter_incr(lock->l_export->exp_ldlm_stats,
575                                      LDLM_BL_CALLBACK - LDLM_FIRST_OPC);
576
577         if (unlikely(instant_cancel)) {
578                 rc = ptl_send_rpc(req, 1);
579         } else {
580                 rc = ptlrpc_queue_wait(req);
581                 OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_GLIMPSE, 2);
582         }
583         if (rc != 0) {
584                 /* If client canceled the lock but the cancel has not been
585                  * recieved yet, we need to update lvbo to have the proper
586                  * attributes cached. */
587                 if (rc == -EINVAL)
588                         ldlm_res_lvbo_update(lock->l_resource, NULL, 0, 1);
589                 rc = ldlm_handle_ast_error(lock, req, rc, "blocking");
590         }
591
592         ptlrpc_req_finished(req);
593
594         /* If we cancelled the lock, we need to restart ldlm_reprocess_queue */
595         if (!rc && instant_cancel)
596                 rc = -ERESTART;
597
598         RETURN(rc);
599 }
600
601 int ldlm_server_completion_ast(struct ldlm_lock *lock, int flags, void *data)
602 {
603         struct ldlm_request *body;
604         struct ptlrpc_request *req;
605         struct timeval granted_time;
606         long total_enqueue_wait;
607         int size[3] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
608                         [DLM_LOCKREQ_OFF]     = sizeof(*body) };
609         int rc = 0, buffers = 2, instant_cancel = 0;
610         ENTRY;
611
612         LASSERT(lock != NULL);
613
614         do_gettimeofday(&granted_time);
615         total_enqueue_wait = cfs_timeval_sub(&granted_time,
616                                              &lock->l_enqueued_time, NULL);
617
618         if (total_enqueue_wait / 1000000 > obd_timeout)
619                 LDLM_ERROR(lock, "enqueue wait took %luus from %lu",
620                            total_enqueue_wait, lock->l_enqueued_time.tv_sec);
621
622         lock_res_and_lock(lock);
623         if (lock->l_resource->lr_lvb_len) {
624                 size[DLM_REQ_REC_OFF] = lock->l_resource->lr_lvb_len;
625                 buffers = 3;
626         }
627         unlock_res_and_lock(lock);
628
629         req = ptlrpc_prep_req(lock->l_export->exp_imp_reverse,
630                               LUSTRE_DLM_VERSION, LDLM_CP_CALLBACK, buffers,
631                               size, NULL);
632         if (req == NULL)
633                 RETURN(-ENOMEM);
634
635         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
636         body->lock_handle[0] = lock->l_remote_handle;
637         body->lock_flags = flags;
638         ldlm_lock2desc(lock, &body->lock_desc);
639
640         if (buffers == 3) {
641                 void *lvb;
642
643                 lvb = lustre_msg_buf(req->rq_reqmsg, DLM_REQ_REC_OFF,
644                                      lock->l_resource->lr_lvb_len);
645                 lock_res_and_lock(lock);
646                 memcpy(lvb, lock->l_resource->lr_lvb_data,
647                        lock->l_resource->lr_lvb_len);
648                 unlock_res_and_lock(lock);
649         }
650
651         LDLM_DEBUG(lock, "server preparing completion AST (after %ldus wait)",
652                    total_enqueue_wait);
653
654         ptlrpc_req_set_repsize(req, 1, NULL);
655
656         req->rq_send_state = LUSTRE_IMP_FULL;
657         req->rq_timeout = ldlm_get_rq_timeout(ldlm_timeout, obd_timeout);
658
659         /* We only send real blocking ASTs after the lock is granted */
660         lock_res_and_lock(lock);
661         if (lock->l_flags & LDLM_FL_AST_SENT) {
662                 body->lock_flags |= LDLM_FL_AST_SENT;
663
664                 /* We might get here prior to ldlm_handle_enqueue setting
665                  * LDLM_FL_CANCEL_ON_BLOCK flag. Then we will put this lock
666                  * into waiting list, but this is safe and similar code in
667                  * ldlm_handle_enqueue will call ldlm_lock_cancel() still,
668                  * that would not only cancel the lock, but will also remove
669                  * it from waiting list */
670                 if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
671                         unlock_res_and_lock(lock);
672                         ldlm_lock_cancel(lock);
673                         instant_cancel = 1;
674                         lock_res_and_lock(lock);
675                 } else {
676                         /* start the lock-timeout clock */
677                         ldlm_add_waiting_lock(lock);
678                 }
679         }
680         unlock_res_and_lock(lock);
681
682         if (lock->l_export && lock->l_export->exp_ldlm_stats)
683                 lprocfs_counter_incr(lock->l_export->exp_ldlm_stats,
684                                      LDLM_CP_CALLBACK - LDLM_FIRST_OPC);
685
686         rc = ptlrpc_queue_wait(req);
687         if (rc != 0)
688                 rc = ldlm_handle_ast_error(lock, req, rc, "completion");
689
690         ptlrpc_req_finished(req);
691
692         /* If we cancelled the lock, we need to restart ldlm_reprocess_queue */
693         if (!rc && instant_cancel)
694                 rc = -ERESTART;
695
696         RETURN(rc);
697 }
698
699 int ldlm_server_glimpse_ast(struct ldlm_lock *lock, void *data)
700 {
701         struct ldlm_resource *res = lock->l_resource;
702         struct ldlm_request *body;
703         struct ptlrpc_request *req;
704         int size[] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
705                        [DLM_LOCKREQ_OFF]     = sizeof(*body) };
706         int rc = 0;
707         ENTRY;
708
709         LASSERT(lock != NULL);
710
711         req = ptlrpc_prep_req(lock->l_export->exp_imp_reverse,
712                               LUSTRE_DLM_VERSION, LDLM_GL_CALLBACK, 2, size,
713                               NULL);
714         if (req == NULL)
715                 RETURN(-ENOMEM);
716
717         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
718         body->lock_handle[0] = lock->l_remote_handle;
719         ldlm_lock2desc(lock, &body->lock_desc);
720
721         lock_res_and_lock(lock);
722         size[REPLY_REC_OFF] = lock->l_resource->lr_lvb_len;
723         unlock_res_and_lock(lock);
724         res = lock->l_resource;
725         ptlrpc_req_set_repsize(req, 2, size);
726
727         req->rq_send_state = LUSTRE_IMP_FULL;
728         req->rq_timeout = ldlm_get_rq_timeout(ldlm_timeout, obd_timeout);
729
730         if (lock->l_export && lock->l_export->exp_ldlm_stats)
731                 lprocfs_counter_incr(lock->l_export->exp_ldlm_stats,
732                                      LDLM_GL_CALLBACK - LDLM_FIRST_OPC);
733
734         rc = ptlrpc_queue_wait(req);
735         if (rc == -ELDLM_NO_LOCK_DATA)
736                 LDLM_DEBUG(lock, "lost race - client has a lock but no inode");
737         else if (rc != 0)
738                 rc = ldlm_handle_ast_error(lock, req, rc, "glimpse");
739         else
740                 rc = ldlm_res_lvbo_update(res, req->rq_repmsg,
741                                           REPLY_REC_OFF, 1);
742         ptlrpc_req_finished(req);
743         RETURN(rc);
744 }
745
746 static struct ldlm_lock *
747 find_existing_lock(struct obd_export *exp,
748                    const struct lustre_handle *remote_hdl)
749 {
750         struct list_head *iter;
751
752         spin_lock(&exp->exp_ldlm_data.led_lock);
753         list_for_each(iter, &exp->exp_ldlm_data.led_held_locks) {
754                 struct ldlm_lock *lock;
755                 lock = list_entry(iter, struct ldlm_lock, l_export_chain);
756                 if (lock->l_remote_handle.cookie == remote_hdl->cookie) {
757                         LDLM_LOCK_GET(lock);
758                         spin_unlock(&exp->exp_ldlm_data.led_lock);
759                         return lock;
760                 }
761         }
762         spin_unlock(&exp->exp_ldlm_data.led_lock);
763         return NULL;
764 }
765
766 #ifdef __KERNEL__
767 extern unsigned long long lu_time_stamp_get(void);
768 #else
769 #define lu_time_stamp_get() time(NULL)
770 #endif
771
772 /*
773  * Main server-side entry point into LDLM. This is called by ptlrpc service
774  * threads to carry out client lock enqueueing requests.
775  */
776 int ldlm_handle_enqueue0(struct ldlm_namespace *ns,
777                          struct ptlrpc_request *req,
778                          const struct ldlm_request *dlm_req,
779                          const struct ldlm_callback_suite *cbs)
780 {
781         struct ldlm_reply *dlm_rep;
782         int size[3] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
783                         [DLM_LOCKREPLY_OFF]   = sizeof(*dlm_rep) };
784         int rc = 0;
785         __u32 flags;
786         ldlm_error_t err = ELDLM_OK;
787         struct ldlm_lock *lock = NULL;
788         void *cookie = NULL;
789         ENTRY;
790
791         LDLM_DEBUG_NOLOCK("server-side enqueue handler START");
792
793         ldlm_request_cancel(req, dlm_req, LDLM_ENQUEUE_CANCEL_OFF);
794         flags = dlm_req->lock_flags;
795
796         LASSERT(req->rq_export);
797
798         if (req->rq_export->exp_ldlm_stats)
799                 lprocfs_counter_incr(req->rq_export->exp_ldlm_stats,
800                                      LDLM_ENQUEUE - LDLM_FIRST_OPC);
801
802         if (unlikely(dlm_req->lock_desc.l_resource.lr_type < LDLM_MIN_TYPE ||
803                      dlm_req->lock_desc.l_resource.lr_type >= LDLM_MAX_TYPE)) {
804                 DEBUG_REQ(D_ERROR, req, "invalid lock request type %d",
805                           dlm_req->lock_desc.l_resource.lr_type);
806                 GOTO(out, rc = -EFAULT);
807         }
808
809         if (unlikely(dlm_req->lock_desc.l_req_mode <= LCK_MINMODE ||
810                      dlm_req->lock_desc.l_req_mode >= LCK_MAXMODE ||
811                      dlm_req->lock_desc.l_req_mode &
812                      (dlm_req->lock_desc.l_req_mode-1))) {
813                 DEBUG_REQ(D_ERROR, req, "invalid lock request mode %d",
814                           dlm_req->lock_desc.l_req_mode);
815                 GOTO(out, rc = -EFAULT);
816         }
817
818         if (req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) {
819                 if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
820                              LDLM_PLAIN)) {
821                         DEBUG_REQ(D_ERROR, req,
822                                   "PLAIN lock request from IBITS client?");
823                         GOTO(out, rc = -EPROTO);
824                 }
825         } else if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
826                             LDLM_IBITS)) {
827                 DEBUG_REQ(D_ERROR, req,
828                           "IBITS lock request from unaware client?");
829                 GOTO(out, rc = -EPROTO);
830         }
831
832 #if 0
833         /* FIXME this makes it impossible to use LDLM_PLAIN locks -- check
834            against server's _CONNECT_SUPPORTED flags? (I don't want to use
835            ibits for mgc/mgs) */
836
837         /* INODEBITS_INTEROP: Perform conversion from plain lock to
838          * inodebits lock if client does not support them. */
839         if (!(req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) &&
840             (dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN)) {
841                 dlm_req->lock_desc.l_resource.lr_type = LDLM_IBITS;
842                 dlm_req->lock_desc.l_policy_data.l_inodebits.bits =
843                         MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
844                 if (dlm_req->lock_desc.l_req_mode == LCK_PR)
845                         dlm_req->lock_desc.l_req_mode = LCK_CR;
846         }
847 #endif
848
849         if (unlikely(flags & LDLM_FL_REPLAY)) {
850                 lock = find_existing_lock(req->rq_export,
851                                           &dlm_req->lock_handle[0]);
852                 if (lock != NULL) {
853                         DEBUG_REQ(D_DLMTRACE, req, "found existing lock cookie "
854                                   LPX64, lock->l_handle.h_cookie);
855                         GOTO(existing_lock, rc = 0);
856                 }
857         }
858
859         /* The lock's callback data might be set in the policy function */
860         lock = ldlm_lock_create(ns, &dlm_req->lock_desc.l_resource.lr_name,
861                                 dlm_req->lock_desc.l_resource.lr_type,
862                                 dlm_req->lock_desc.l_req_mode,
863                                 cbs->lcs_blocking, cbs->lcs_completion,
864                                 cbs->lcs_glimpse, NULL, 0);
865
866         if (!lock)
867                 GOTO(out, rc = -ENOMEM);
868
869         do_gettimeofday(&lock->l_enqueued_time);
870         lock->l_remote_handle = dlm_req->lock_handle[0];
871         LDLM_DEBUG(lock, "server-side enqueue handler, new lock created");
872
873         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_ENQUEUE_BLOCKED, obd_timeout * 2);
874         /* Don't enqueue a lock onto the export if it has already
875          * been evicted.  Cancel it now instead. (bug 3822) */
876         if (req->rq_export->exp_failed) {
877                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
878                 GOTO(out, rc = -ENOTCONN);
879         }
880         lock->l_export = class_export_get(req->rq_export);
881         spin_lock(&lock->l_export->exp_ldlm_data.led_lock);
882         list_add(&lock->l_export_chain,
883                  &lock->l_export->exp_ldlm_data.led_held_locks);
884         spin_unlock(&lock->l_export->exp_ldlm_data.led_lock);
885
886 existing_lock:
887
888         if (flags & LDLM_FL_HAS_INTENT) {
889                 /* In this case, the reply buffer is allocated deep in
890                  * local_lock_enqueue by the policy function. */
891                 cookie = req;
892         } else {
893                 int buffers = 2;
894
895                 lock_res_and_lock(lock);
896                 if (lock->l_resource->lr_lvb_len) {
897                         size[DLM_REPLY_REC_OFF] = lock->l_resource->lr_lvb_len;
898                         buffers = 3;
899                 }
900                 unlock_res_and_lock(lock);
901
902                 if (OBD_FAIL_CHECK_ONCE(OBD_FAIL_LDLM_ENQUEUE_EXTENT_ERR))
903                         GOTO(out, rc = -ENOMEM);
904
905                 rc = lustre_pack_reply(req, buffers, size, NULL);
906                 if (rc)
907                         GOTO(out, rc);
908         }
909
910         if (dlm_req->lock_desc.l_resource.lr_type != LDLM_PLAIN)
911                 lock->l_policy_data = dlm_req->lock_desc.l_policy_data;
912         if (dlm_req->lock_desc.l_resource.lr_type == LDLM_EXTENT)
913                 lock->l_req_extent = lock->l_policy_data.l_extent;
914
915         err = ldlm_lock_enqueue(ns, &lock, cookie, &flags);
916         if (err)
917                 GOTO(out, err);
918
919         dlm_rep = lustre_msg_buf(req->rq_repmsg, DLM_LOCKREPLY_OFF,
920                                  sizeof(*dlm_rep));
921         dlm_rep->lock_flags = flags;
922
923         ldlm_lock2desc(lock, &dlm_rep->lock_desc);
924         ldlm_lock2handle(lock, &dlm_rep->lock_handle);
925
926         /* We never send a blocking AST until the lock is granted, but
927          * we can tell it right now */
928         lock_res_and_lock(lock);
929
930         /* Now take into account flags to be inherited from original lock
931            request both in reply to client and in our own lock flags. */
932         dlm_rep->lock_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
933         lock->l_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
934
935         /* Don't move a pending lock onto the export if it has already
936          * been evicted.  Cancel it now instead. (bug 5683) */
937         if (unlikely(req->rq_export->exp_failed ||
938                      OBD_FAIL_CHECK_ONCE(OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT))) {
939                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
940                 rc = -ENOTCONN;
941         } else if (lock->l_flags & LDLM_FL_AST_SENT) {
942                 dlm_rep->lock_flags |= LDLM_FL_AST_SENT;
943                 if (lock->l_granted_mode == lock->l_req_mode) {
944                         /*
945                          * Only cancel lock if it was granted, because it would
946                          * be destroyed immediatelly and would never be granted
947                          * in the future, causing timeouts on client.  Not
948                          * granted lock will be cancelled immediatelly after
949                          * sending completion AST.
950                          */
951                         if (dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK) {
952                                 unlock_res_and_lock(lock);
953                                 ldlm_lock_cancel(lock);
954                                 lock_res_and_lock(lock);
955                         } else
956                                 ldlm_add_waiting_lock(lock);
957                 }
958         }
959         /* Make sure we never ever grant usual metadata locks to liblustre
960            clients */
961         if ((dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN ||
962             dlm_req->lock_desc.l_resource.lr_type == LDLM_IBITS) &&
963              req->rq_export->exp_libclient) {
964                 if (unlikely(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) ||
965                              !(dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK))){
966                         CERROR("Granting sync lock to libclient. "
967                                "req fl %d, rep fl %d, lock fl %d\n",
968                                dlm_req->lock_flags, dlm_rep->lock_flags,
969                                lock->l_flags);
970                         LDLM_ERROR(lock, "sync lock");
971                         if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT) {
972                                 struct ldlm_intent *it;
973                                 it = lustre_msg_buf(req->rq_reqmsg,
974                                                     DLM_INTENT_IT_OFF,
975                                                     sizeof(*it));
976                                 if (it != NULL) {
977                                         CERROR("This is intent %s ("LPU64")\n",
978                                                ldlm_it2str(it->opc), it->opc);
979                                 }
980                         }
981                 }
982         }
983
984         unlock_res_and_lock(lock);
985
986         EXIT;
987  out:
988         req->rq_status = err;
989         if (req->rq_reply_state == NULL) {
990                 err = lustre_pack_reply(req, 1, NULL, NULL);
991                 if (rc == 0)
992                         rc = err;
993                 req->rq_status = rc;
994         }
995
996         /* The LOCK_CHANGED code in ldlm_lock_enqueue depends on this
997          * ldlm_reprocess_all.  If this moves, revisit that code. -phil */
998         if (lock) {
999                 LDLM_DEBUG(lock, "server-side enqueue handler, sending reply"
1000                            "(err=%d, rc=%d)", err, rc);
1001
1002                 lock_res_and_lock(lock);
1003                 if (rc == 0) {
1004                         size[DLM_REPLY_REC_OFF] = lock->l_resource->lr_lvb_len;
1005                         if (size[DLM_REPLY_REC_OFF] > 0) {
1006                                 void *lvb = lustre_msg_buf(req->rq_repmsg,
1007                                                        DLM_REPLY_REC_OFF,
1008                                                        size[DLM_REPLY_REC_OFF]);
1009                                 LASSERTF(lvb != NULL, "req %p, lock %p\n",
1010                                          req, lock);
1011
1012                                 memcpy(lvb, lock->l_resource->lr_lvb_data,
1013                                        size[DLM_REPLY_REC_OFF]);
1014                         }
1015                 } else {
1016                         ldlm_resource_unlink_lock(lock);
1017                         ldlm_lock_destroy_nolock(lock);
1018                 }
1019                 unlock_res_and_lock(lock);
1020
1021                 if (!err && dlm_req->lock_desc.l_resource.lr_type != LDLM_FLOCK)
1022                         ldlm_reprocess_all(lock->l_resource);
1023
1024                 LDLM_LOCK_PUT(lock);
1025         }
1026
1027         LDLM_DEBUG_NOLOCK("server-side enqueue handler END (lock %p, rc %d)",
1028                           lock, rc);
1029
1030         return rc;
1031 }
1032
1033 int ldlm_handle_enqueue(struct ptlrpc_request *req,
1034                         ldlm_completion_callback completion_callback,
1035                         ldlm_blocking_callback blocking_callback,
1036                         ldlm_glimpse_callback glimpse_callback)
1037 {
1038         int rc;
1039         struct ldlm_request *dlm_req;
1040         struct ldlm_callback_suite cbs = {
1041                 .lcs_completion = completion_callback,
1042                 .lcs_blocking   = blocking_callback,
1043                 .lcs_glimpse    = glimpse_callback
1044         };
1045
1046
1047         dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF,
1048                                      sizeof *dlm_req, lustre_swab_ldlm_request);
1049         if (dlm_req != NULL) {
1050                 rc = ldlm_handle_enqueue0(req->rq_export->exp_obd->obd_namespace,
1051                                           req, dlm_req, &cbs);
1052         } else {
1053                 CERROR ("Can't unpack dlm_req\n");
1054                 rc = -EFAULT;
1055         }
1056         return rc;
1057 }
1058
1059 int ldlm_handle_convert0(struct ptlrpc_request *req,
1060                          const struct ldlm_request *dlm_req)
1061 {
1062         struct ldlm_reply *dlm_rep;
1063         struct ldlm_lock *lock;
1064         int rc;
1065         int size[2] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
1066                         [DLM_LOCKREPLY_OFF]   = sizeof(*dlm_rep) };
1067         ENTRY;
1068
1069         if (req->rq_export && req->rq_export->exp_ldlm_stats)
1070                 lprocfs_counter_incr(req->rq_export->exp_ldlm_stats,
1071                                      LDLM_CONVERT - LDLM_FIRST_OPC);
1072
1073         rc = lustre_pack_reply(req, 2, size, NULL);
1074         if (rc) {
1075                 CERROR("out of memory\n");
1076                 RETURN(-ENOMEM);
1077         }
1078         dlm_rep = lustre_msg_buf(req->rq_repmsg, DLM_LOCKREPLY_OFF,
1079                                  sizeof(*dlm_rep));
1080         dlm_rep->lock_flags = dlm_req->lock_flags;
1081
1082         lock = ldlm_handle2lock(&dlm_req->lock_handle[0]);
1083         if (!lock) {
1084                 req->rq_status = EINVAL;
1085         } else {
1086                 void *res = NULL;
1087
1088                 LDLM_DEBUG(lock, "server-side convert handler START");
1089
1090                 do_gettimeofday(&lock->l_enqueued_time);
1091                 res = ldlm_lock_convert(lock, dlm_req->lock_desc.l_req_mode,
1092                                         &dlm_rep->lock_flags);
1093                 if (res) {
1094                         if (ldlm_del_waiting_lock(lock))
1095                                 LDLM_DEBUG(lock, "converted waiting lock");
1096                         req->rq_status = 0;
1097                 } else {
1098                         req->rq_status = EDEADLOCK;
1099                 }
1100         }
1101
1102         if (lock) {
1103                 if (!req->rq_status)
1104                         ldlm_reprocess_all(lock->l_resource);
1105                 LDLM_DEBUG(lock, "server-side convert handler END");
1106                 LDLM_LOCK_PUT(lock);
1107         } else
1108                 LDLM_DEBUG_NOLOCK("server-side convert handler END");
1109
1110         RETURN(0);
1111 }
1112
1113 int ldlm_handle_convert(struct ptlrpc_request *req)
1114 {
1115         int rc;
1116         struct ldlm_request *dlm_req;
1117
1118         dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF, sizeof *dlm_req,
1119                                      lustre_swab_ldlm_request);
1120         if (dlm_req != NULL) {
1121                 rc = ldlm_handle_convert0(req, dlm_req);
1122         } else {
1123                 CERROR ("Can't unpack dlm_req\n");
1124                 rc = -EFAULT;
1125         }
1126         return rc;
1127 }
1128
1129 /* Cancel all the locks, which handles are packed into ldlm_request */
1130 int ldlm_request_cancel(struct ptlrpc_request *req,
1131                         const struct ldlm_request *dlm_req, int first)
1132 {
1133         struct ldlm_resource *res, *pres = NULL;
1134         struct ldlm_lock *lock;
1135         int i, count, done = 0;
1136         ENTRY;
1137
1138         count = dlm_req->lock_count ? dlm_req->lock_count : 1;
1139         if (first >= count)
1140                 RETURN(0);
1141
1142         /* There is no lock on the server at the replay time,
1143          * skip lock cancelling to make replay tests to pass. */
1144         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1145                 RETURN(0);
1146
1147         LDLM_DEBUG_NOLOCK("server-side cancel handler START: %d locks, "
1148                           "starting at %d", count, first);
1149
1150         for (i = first; i < count; i++) {
1151                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
1152                 if (!lock) {
1153                         LDLM_DEBUG_NOLOCK("server-side cancel handler stale "
1154                                           "lock (cookie "LPU64")",
1155                                           dlm_req->lock_handle[i].cookie);
1156                         continue;
1157                 }
1158
1159                 res = lock->l_resource;
1160                 done++;
1161
1162                 if (res != pres) {
1163                         if (pres != NULL) {
1164                                 ldlm_reprocess_all(pres);
1165                                 ldlm_resource_putref(pres);
1166                         }
1167                         if (res != NULL) {
1168                                 ldlm_resource_getref(res);
1169                                 ldlm_res_lvbo_update(res, NULL, 0, 1);
1170                         }
1171                         pres = res;
1172                 }
1173                 ldlm_lock_cancel(lock);
1174                 LDLM_LOCK_PUT(lock);
1175         }
1176         if (pres != NULL) {
1177                 ldlm_reprocess_all(pres);
1178                 ldlm_resource_putref(pres);
1179         }
1180         LDLM_DEBUG_NOLOCK("server-side cancel handler END");
1181         RETURN(done);
1182 }
1183
1184 int ldlm_handle_cancel(struct ptlrpc_request *req)
1185 {
1186         struct ldlm_request *dlm_req;
1187         int rc;
1188         ENTRY;
1189
1190         dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF, sizeof(*dlm_req),
1191                                      lustre_swab_ldlm_request);
1192         if (dlm_req == NULL) {
1193                 CERROR("bad request buffer for cancel\n");
1194                 RETURN(-EFAULT);
1195         }
1196
1197         if (req->rq_export && req->rq_export->exp_ldlm_stats)
1198                 lprocfs_counter_incr(req->rq_export->exp_ldlm_stats,
1199                                      LDLM_CANCEL - LDLM_FIRST_OPC);
1200
1201         rc = lustre_pack_reply(req, 1, NULL, NULL);
1202         if (rc) {
1203                 CERROR("out of memory\n");
1204                 RETURN(-ENOMEM);
1205         }
1206
1207         if (!ldlm_request_cancel(req, dlm_req, 0))
1208                 req->rq_status = ESTALE;
1209
1210         if (ptlrpc_reply(req) != 0)
1211                 LBUG();
1212
1213         RETURN(0);
1214 }
1215
1216 void ldlm_handle_bl_callback(struct ldlm_namespace *ns,
1217                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock)
1218 {
1219         int do_ast;
1220         ENTRY;
1221
1222         LDLM_DEBUG(lock, "client blocking AST callback handler START");
1223
1224         lock_res_and_lock(lock);
1225         lock->l_flags |= LDLM_FL_CBPENDING;
1226
1227         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
1228                 lock->l_flags |= LDLM_FL_CANCEL;
1229
1230         do_ast = (!lock->l_readers && !lock->l_writers);
1231         unlock_res_and_lock(lock);
1232
1233         if (do_ast) {
1234                 LDLM_DEBUG(lock, "already unused, calling "
1235                            "callback (%p)", lock->l_blocking_ast);
1236                 if (lock->l_blocking_ast != NULL)
1237                         lock->l_blocking_ast(lock, ld, lock->l_ast_data,
1238                                              LDLM_CB_BLOCKING);
1239         } else {
1240                 LDLM_DEBUG(lock, "Lock still has references, will be"
1241                            " cancelled later");
1242         }
1243
1244         LDLM_DEBUG(lock, "client blocking callback handler END");
1245         LDLM_LOCK_PUT(lock);
1246         EXIT;
1247 }
1248
1249 static void ldlm_handle_cp_callback(struct ptlrpc_request *req,
1250                                     struct ldlm_namespace *ns,
1251                                     struct ldlm_request *dlm_req,
1252                                     struct ldlm_lock *lock)
1253 {
1254         CFS_LIST_HEAD(ast_list);
1255         ENTRY;
1256
1257         LDLM_DEBUG(lock, "client completion callback handler START");
1258
1259         lock_res_and_lock(lock);
1260
1261         /* If we receive the completion AST before the actual enqueue returned,
1262          * then we might need to switch lock modes, resources, or extents. */
1263         if (dlm_req->lock_desc.l_granted_mode != lock->l_req_mode) {
1264                 lock->l_req_mode = dlm_req->lock_desc.l_granted_mode;
1265                 LDLM_DEBUG(lock, "completion AST, new lock mode");
1266         }
1267
1268         if (lock->l_resource->lr_type != LDLM_PLAIN) {
1269                 lock->l_policy_data = dlm_req->lock_desc.l_policy_data;
1270                 LDLM_DEBUG(lock, "completion AST, new policy data");
1271         }
1272
1273         ldlm_resource_unlink_lock(lock);
1274         if (memcmp(&dlm_req->lock_desc.l_resource.lr_name,
1275                    &lock->l_resource->lr_name,
1276                    sizeof(lock->l_resource->lr_name)) != 0) {
1277                 unlock_res_and_lock(lock);
1278                 ldlm_lock_change_resource(ns, lock,
1279                                         &dlm_req->lock_desc.l_resource.lr_name);
1280                 LDLM_DEBUG(lock, "completion AST, new resource");
1281                 CERROR("change resource!\n");
1282                 lock_res_and_lock(lock);
1283         }
1284
1285         if (dlm_req->lock_flags & LDLM_FL_AST_SENT) {
1286                 lock->l_flags |= LDLM_FL_CBPENDING;
1287                 LDLM_DEBUG(lock, "completion AST includes blocking AST");
1288         }
1289
1290         if (lock->l_lvb_len) {
1291                 void *lvb;
1292                 lvb = lustre_swab_reqbuf(req, DLM_REQ_REC_OFF, lock->l_lvb_len,
1293                                          lock->l_lvb_swabber);
1294                 if (lvb == NULL) {
1295                         LDLM_ERROR(lock, "completion AST did not contain "
1296                                    "expected LVB!");
1297                 } else {
1298                         memcpy(lock->l_lvb_data, lvb, lock->l_lvb_len);
1299                 }
1300         }
1301
1302         ldlm_grant_lock(lock, &ast_list);
1303         unlock_res_and_lock(lock);
1304
1305         LDLM_DEBUG(lock, "callback handler finished, about to run_ast_work");
1306
1307         ldlm_run_cp_ast_work(&ast_list);
1308
1309         LDLM_DEBUG_NOLOCK("client completion callback handler END (lock %p)",
1310                           lock);
1311         LDLM_LOCK_PUT(lock);
1312         EXIT;
1313 }
1314
1315 static void ldlm_handle_gl_callback(struct ptlrpc_request *req,
1316                                     struct ldlm_namespace *ns,
1317                                     struct ldlm_request *dlm_req,
1318                                     struct ldlm_lock *lock)
1319 {
1320         int rc = -ENOSYS;
1321         ENTRY;
1322
1323         LDLM_DEBUG(lock, "client glimpse AST callback handler");
1324
1325         if (lock->l_glimpse_ast != NULL)
1326                 rc = lock->l_glimpse_ast(lock, req);
1327
1328         if (req->rq_repmsg != NULL) {
1329                 ptlrpc_reply(req);
1330         } else {
1331                 req->rq_status = rc;
1332                 ptlrpc_error(req);
1333         }
1334
1335         lock_res_and_lock(lock);
1336         if (lock->l_granted_mode == LCK_PW &&
1337             !lock->l_readers && !lock->l_writers &&
1338             cfs_time_after(cfs_time_current(),
1339                            cfs_time_add(lock->l_last_used,
1340                                         cfs_time_seconds(10)))) {
1341                 unlock_res_and_lock(lock);
1342                 if (ldlm_bl_to_thread_lock(ns, NULL, lock))
1343                         ldlm_handle_bl_callback(ns, NULL, lock);
1344
1345                 EXIT;
1346                 return;
1347         }
1348         unlock_res_and_lock(lock);
1349         LDLM_LOCK_PUT(lock);
1350         EXIT;
1351 }
1352
1353 static int ldlm_callback_reply(struct ptlrpc_request *req, int rc)
1354 {
1355         req->rq_status = rc;
1356         if (req->rq_reply_state == NULL) {
1357                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1358                 if (rc)
1359                         return rc;
1360         }
1361         return ptlrpc_reply(req);
1362 }
1363
1364 #ifdef __KERNEL__
1365 static int ldlm_bl_to_thread(struct ldlm_namespace *ns,
1366                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock,
1367                              struct list_head *cancels, int count)
1368 {
1369         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1370         struct ldlm_bl_work_item *blwi;
1371         ENTRY;
1372
1373         if (cancels && count == 0)
1374                 RETURN(0);
1375
1376         OBD_ALLOC(blwi, sizeof(*blwi));
1377         if (blwi == NULL)
1378                 RETURN(-ENOMEM);
1379
1380         blwi->blwi_ns = ns;
1381         if (ld != NULL)
1382                 blwi->blwi_ld = *ld;
1383         if (count) {
1384                 list_add(&blwi->blwi_head, cancels);
1385                 list_del_init(cancels);
1386                 blwi->blwi_count = count;
1387         } else {
1388                 blwi->blwi_lock = lock;
1389         }
1390         spin_lock(&blp->blp_lock);
1391         list_add_tail(&blwi->blwi_entry, &blp->blp_list);
1392         cfs_waitq_signal(&blp->blp_waitq);
1393         spin_unlock(&blp->blp_lock);
1394
1395         RETURN(0);
1396 }
1397 #endif
1398
1399 int ldlm_bl_to_thread_lock(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1400                            struct ldlm_lock *lock)
1401 {
1402 #ifdef __KERNEL__
1403         RETURN(ldlm_bl_to_thread(ns, ld, lock, NULL, 0));
1404 #else
1405         RETURN(-ENOSYS);
1406 #endif
1407 }
1408
1409 int ldlm_bl_to_thread_list(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1410                            struct list_head *cancels, int count)
1411 {
1412 #ifdef __KERNEL__
1413         RETURN(ldlm_bl_to_thread(ns, ld, NULL, cancels, count));
1414 #else
1415         RETURN(-ENOSYS);
1416 #endif
1417 }
1418
1419 static int ldlm_callback_handler(struct ptlrpc_request *req)
1420 {
1421         struct ldlm_namespace *ns;
1422         struct ldlm_request *dlm_req;
1423         struct ldlm_lock *lock;
1424         int rc;
1425         ENTRY;
1426
1427         /* Requests arrive in sender's byte order.  The ptlrpc service
1428          * handler has already checked and, if necessary, byte-swapped the
1429          * incoming request message body, but I am responsible for the
1430          * message buffers. */
1431
1432         if (req->rq_export == NULL) {
1433                 struct ldlm_request *dlm_req;
1434
1435                 CDEBUG(D_RPCTRACE, "operation %d from %s with bad "
1436                        "export cookie "LPX64"; this is "
1437                        "normal if this node rebooted with a lock held\n",
1438                        lustre_msg_get_opc(req->rq_reqmsg),
1439                        libcfs_id2str(req->rq_peer),
1440                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
1441
1442                 dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF,
1443                                              sizeof(*dlm_req),
1444                                              lustre_swab_ldlm_request);
1445                 if (dlm_req != NULL)
1446                         CDEBUG(D_RPCTRACE, "--> lock cookie: "LPX64"\n",
1447                                dlm_req->lock_handle[0].cookie);
1448
1449                 ldlm_callback_reply(req, -ENOTCONN);
1450                 RETURN(0);
1451         }
1452
1453         LASSERT(req->rq_export != NULL);
1454         LASSERT(req->rq_export->exp_obd != NULL);
1455
1456         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1457         case LDLM_BL_CALLBACK:
1458                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_BL_CALLBACK, 0);
1459                 break;
1460         case LDLM_CP_CALLBACK:
1461                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_CP_CALLBACK, 0);
1462                 break;
1463         case LDLM_GL_CALLBACK:
1464                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_GL_CALLBACK, 0);
1465                 break;
1466         case OBD_LOG_CANCEL: /* remove this eventually - for 1.4.0 compat */
1467                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOG_CANCEL_NET, 0);
1468                 rc = llog_origin_handle_cancel(req);
1469                 ldlm_callback_reply(req, rc);
1470                 RETURN(0);
1471         case OBD_QC_CALLBACK:
1472                 OBD_FAIL_RETURN(OBD_FAIL_OBD_QC_CALLBACK_NET, 0);
1473                 rc = target_handle_qc_callback(req);
1474                 ldlm_callback_reply(req, rc);
1475                 RETURN(0);
1476         case QUOTA_DQACQ:
1477         case QUOTA_DQREL:
1478                 /* reply in handler */
1479                 rc = target_handle_dqacq_callback(req);
1480                 RETURN(0);
1481         case LLOG_ORIGIN_HANDLE_CREATE:
1482                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
1483                 rc = llog_origin_handle_create(req);
1484                 ldlm_callback_reply(req, rc);
1485                 RETURN(0);
1486         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
1487                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
1488                 rc = llog_origin_handle_next_block(req);
1489                 ldlm_callback_reply(req, rc);
1490                 RETURN(0);
1491         case LLOG_ORIGIN_HANDLE_READ_HEADER:
1492                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
1493                 rc = llog_origin_handle_read_header(req);
1494                 ldlm_callback_reply(req, rc);
1495                 RETURN(0);
1496         case LLOG_ORIGIN_HANDLE_CLOSE:
1497                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
1498                 rc = llog_origin_handle_close(req);
1499                 ldlm_callback_reply(req, rc);
1500                 RETURN(0);
1501         case SEC_CTX_FINI:
1502                 /* do nothing */
1503                 RETURN(0);
1504         default:
1505                 CERROR("unknown opcode %u\n",
1506                        lustre_msg_get_opc(req->rq_reqmsg));
1507                 ldlm_callback_reply(req, -EPROTO);
1508                 RETURN(0);
1509         }
1510
1511         ns = req->rq_export->exp_obd->obd_namespace;
1512         LASSERT(ns != NULL);
1513
1514         dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF, sizeof(*dlm_req),
1515                                      lustre_swab_ldlm_request);
1516         if (dlm_req == NULL) {
1517                 CERROR ("can't unpack dlm_req\n");
1518                 ldlm_callback_reply(req, -EPROTO);
1519                 RETURN (0);
1520         }
1521
1522         lock = ldlm_handle2lock_ns(ns, &dlm_req->lock_handle[0]);
1523         if (!lock) {
1524                 CDEBUG(D_DLMTRACE, "callback on lock "LPX64" - lock "
1525                        "disappeared\n", dlm_req->lock_handle[0].cookie);
1526                 ldlm_callback_reply(req, -EINVAL);
1527                 RETURN(0);
1528         }
1529
1530         /* Copy hints/flags (e.g. LDLM_FL_DISCARD_DATA) from AST. */
1531         lock_res_and_lock(lock);
1532         lock->l_flags |= (dlm_req->lock_flags & LDLM_AST_FLAGS);
1533         if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1534                 /* If somebody cancels locks and cache is already droped,
1535                  * we can tell the server we have no lock. Otherwise, we
1536                  * should send cancel after dropping the cache. */
1537                 if ((lock->l_flags & LDLM_FL_CANCELING) &&
1538                     (lock->l_flags & LDLM_FL_BL_DONE)) {
1539                         LDLM_DEBUG(lock, "callback on lock "
1540                                    LPX64" - lock disappeared\n",
1541                                    dlm_req->lock_handle[0].cookie);
1542                         unlock_res_and_lock(lock);
1543                         LDLM_LOCK_PUT(lock);
1544                         ldlm_callback_reply(req, -EINVAL);
1545                         RETURN(0);
1546                 }
1547                 lock->l_flags |= LDLM_FL_BL_AST;
1548         }
1549         unlock_res_and_lock(lock);
1550
1551         /* We want the ost thread to get this reply so that it can respond
1552          * to ost requests (write cache writeback) that might be triggered
1553          * in the callback.
1554          *
1555          * But we'd also like to be able to indicate in the reply that we're
1556          * cancelling right now, because it's unused, or have an intent result
1557          * in the reply, so we might have to push the responsibility for sending
1558          * the reply down into the AST handlers, alas. */
1559
1560         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1561         case LDLM_BL_CALLBACK:
1562                 CDEBUG(D_INODE, "blocking ast\n");
1563                 if (!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK))
1564                         ldlm_callback_reply(req, 0);
1565                 if (ldlm_bl_to_thread_lock(ns, &dlm_req->lock_desc, lock))
1566                         ldlm_handle_bl_callback(ns, &dlm_req->lock_desc, lock);
1567                 break;
1568         case LDLM_CP_CALLBACK:
1569                 CDEBUG(D_INODE, "completion ast\n");
1570                 ldlm_callback_reply(req, 0);
1571                 ldlm_handle_cp_callback(req, ns, dlm_req, lock);
1572                 break;
1573         case LDLM_GL_CALLBACK:
1574                 CDEBUG(D_INODE, "glimpse ast\n");
1575                 ldlm_handle_gl_callback(req, ns, dlm_req, lock);
1576                 break;
1577         default:
1578                 LBUG();                         /* checked above */
1579         }
1580
1581         RETURN(0);
1582 }
1583
1584 static int ldlm_cancel_handler(struct ptlrpc_request *req)
1585 {
1586         int rc;
1587         ENTRY;
1588
1589         /* Requests arrive in sender's byte order.  The ptlrpc service
1590          * handler has already checked and, if necessary, byte-swapped the
1591          * incoming request message body, but I am responsible for the
1592          * message buffers. */
1593
1594         if (req->rq_export == NULL) {
1595                 struct ldlm_request *dlm_req;
1596
1597                 CERROR("operation %d from %s with bad export cookie "LPU64"\n",
1598                        lustre_msg_get_opc(req->rq_reqmsg),
1599                        libcfs_id2str(req->rq_peer),
1600                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
1601
1602                 dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF,
1603                                              sizeof(*dlm_req),
1604                                              lustre_swab_ldlm_request);
1605                 if (dlm_req != NULL)
1606                         ldlm_lock_dump_handle(D_ERROR,
1607                                               &dlm_req->lock_handle[0]);
1608                 ldlm_callback_reply(req, -ENOTCONN);
1609                 RETURN(0);
1610         }
1611
1612         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1613
1614         /* XXX FIXME move this back to mds/handler.c, bug 249 */
1615         case LDLM_CANCEL:
1616                 CDEBUG(D_INODE, "cancel\n");
1617                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_CANCEL, 0);
1618                 rc = ldlm_handle_cancel(req);
1619                 if (rc)
1620                         break;
1621                 RETURN(0);
1622         case OBD_LOG_CANCEL:
1623                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOG_CANCEL_NET, 0);
1624                 rc = llog_origin_handle_cancel(req);
1625                 ldlm_callback_reply(req, rc);
1626                 RETURN(0);
1627         default:
1628                 CERROR("invalid opcode %d\n",
1629                        lustre_msg_get_opc(req->rq_reqmsg));
1630                 ldlm_callback_reply(req, -EINVAL);
1631         }
1632
1633         RETURN(0);
1634 }
1635
1636 void ldlm_revoke_export_locks(struct obd_export *exp)
1637 {
1638         struct list_head *locklist = &exp->exp_ldlm_data.led_held_locks;
1639         struct list_head  rpc_list;
1640         struct ldlm_lock *lock, *next;
1641         struct ldlm_lock_desc desc;
1642
1643         ENTRY;
1644         INIT_LIST_HEAD(&rpc_list);
1645
1646         spin_lock(&exp->exp_ldlm_data.led_lock);
1647         list_for_each_entry_safe(lock, next, locklist, l_export_chain) {
1648                 lock_res_and_lock(lock);
1649
1650                 if (lock->l_req_mode != lock->l_granted_mode) {
1651                         unlock_res_and_lock(lock);
1652                         continue;
1653                 }
1654
1655                 LASSERT(lock->l_resource);
1656                 if (lock->l_resource->lr_type != LDLM_IBITS &&
1657                     lock->l_resource->lr_type != LDLM_PLAIN) {
1658                         unlock_res_and_lock(lock);
1659                         continue;
1660                 }
1661
1662                 if (lock->l_flags & LDLM_FL_AST_SENT) {
1663                         unlock_res_and_lock(lock);
1664                         continue;
1665                 }
1666
1667                 LASSERT(lock->l_blocking_ast);
1668                 LASSERT(!lock->l_blocking_lock);
1669
1670                 lock->l_flags |= LDLM_FL_AST_SENT;
1671                 list_move(&lock->l_export_chain, &rpc_list);
1672
1673                 unlock_res_and_lock(lock);
1674         }
1675         spin_unlock(&exp->exp_ldlm_data.led_lock);
1676
1677         while (!list_empty(&rpc_list)) {
1678                 lock = list_entry(rpc_list.next, struct ldlm_lock,
1679                                   l_export_chain);
1680                 list_del_init(&lock->l_export_chain);
1681
1682                 /* the desc just pretend to exclusive */
1683                 ldlm_lock2desc(lock, &desc);
1684                 desc.l_req_mode = LCK_EX;
1685                 desc.l_granted_mode = 0;
1686
1687                 LDLM_LOCK_GET(lock);
1688                 lock->l_blocking_ast(lock, &desc, lock->l_ast_data,
1689                                      LDLM_CB_BLOCKING);
1690                 LDLM_LOCK_PUT(lock);
1691         }
1692         EXIT;
1693 }
1694
1695 #ifdef __KERNEL__
1696 static struct ldlm_bl_work_item *ldlm_bl_get_work(struct ldlm_bl_pool *blp)
1697 {
1698         struct ldlm_bl_work_item *blwi = NULL;
1699
1700         spin_lock(&blp->blp_lock);
1701         if (!list_empty(&blp->blp_list)) {
1702                 blwi = list_entry(blp->blp_list.next, struct ldlm_bl_work_item,
1703                                   blwi_entry);
1704                 list_del(&blwi->blwi_entry);
1705         }
1706         spin_unlock(&blp->blp_lock);
1707
1708         return blwi;
1709 }
1710
1711 struct ldlm_bl_thread_data {
1712         int                     bltd_num;
1713         struct ldlm_bl_pool     *bltd_blp;
1714 };
1715
1716 static int ldlm_bl_thread_main(void *arg)
1717 {
1718         struct ldlm_bl_thread_data *bltd = arg;
1719         struct ldlm_bl_pool *blp = bltd->bltd_blp;
1720         ENTRY;
1721
1722         {
1723                 char name[CFS_CURPROC_COMM_MAX];
1724                 snprintf(name, sizeof(name) - 1, "ldlm_bl_%02d",
1725                          bltd->bltd_num);
1726                 cfs_daemonize(name);
1727         }
1728
1729         atomic_inc(&blp->blp_num_threads);
1730         complete(&blp->blp_comp);
1731
1732         while(1) {
1733                 struct l_wait_info lwi = { 0 };
1734                 struct ldlm_bl_work_item *blwi = NULL;
1735
1736                 l_wait_event_exclusive(blp->blp_waitq,
1737                                        (blwi = ldlm_bl_get_work(blp)) != NULL,
1738                                        &lwi);
1739
1740                 if (blwi->blwi_ns == NULL)
1741                         break;
1742
1743                 if (blwi->blwi_count) {
1744                         /* The special case when we cancel locks in lru
1745                          * asynchronously, we pass the list of locks here.
1746                          * Thus lock is marked LDLM_FL_CANCELING, and already
1747                          * canceled locally. */
1748                         ldlm_cli_cancel_list(&blwi->blwi_head,
1749                                              blwi->blwi_count, NULL, 0, 0);
1750                 } else {
1751                         ldlm_handle_bl_callback(blwi->blwi_ns, &blwi->blwi_ld,
1752                                                 blwi->blwi_lock);
1753                 }
1754                 OBD_FREE(blwi, sizeof(*blwi));
1755         }
1756
1757         atomic_dec(&blp->blp_num_threads);
1758         complete(&blp->blp_comp);
1759         RETURN(0);
1760 }
1761
1762 #endif
1763
1764 static int ldlm_setup(ldlm_side_t client);
1765 static int ldlm_cleanup(ldlm_side_t client, int force);
1766
1767 int ldlm_get_ref(ldlm_side_t client)
1768 {
1769         int rc = 0;
1770         ENTRY;
1771         mutex_down(&ldlm_ref_sem);
1772         if (++ldlm_refcount == 1) {
1773                 rc = ldlm_setup(client);
1774                 if (rc)
1775                         ldlm_refcount--;
1776         }
1777         mutex_up(&ldlm_ref_sem);
1778
1779         RETURN(rc);
1780 }
1781
1782 void ldlm_put_ref(ldlm_side_t client, int force)
1783 {
1784         ENTRY;
1785         mutex_down(&ldlm_ref_sem);
1786         if (ldlm_refcount == 1) {
1787                 int rc = ldlm_cleanup(client, force);
1788                 if (rc)
1789                         CERROR("ldlm_cleanup failed: %d\n", rc);
1790                 else
1791                         ldlm_refcount--;
1792         } else {
1793                 ldlm_refcount--;
1794         }
1795         mutex_up(&ldlm_ref_sem);
1796
1797         EXIT;
1798 }
1799
1800 static int ldlm_setup(ldlm_side_t client)
1801 {
1802         struct ldlm_bl_pool *blp;
1803         int rc = 0;
1804 #ifdef __KERNEL__
1805         int i;
1806 #endif
1807         ENTRY;
1808
1809         if (ldlm_state != NULL)
1810                 RETURN(-EALREADY);
1811
1812         OBD_ALLOC(ldlm_state, sizeof(*ldlm_state));
1813         if (ldlm_state == NULL)
1814                 RETURN(-ENOMEM);
1815
1816 #ifdef LPROCFS
1817         rc = ldlm_proc_setup();
1818         if (rc != 0)
1819                 GOTO(out_free, rc);
1820 #endif
1821
1822         ldlm_state->ldlm_cb_service =
1823                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
1824                                 LDLM_MAXREPSIZE, LDLM_CB_REQUEST_PORTAL,
1825                                 LDLM_CB_REPLY_PORTAL, ldlm_timeout * 900,
1826                                 ldlm_callback_handler, "ldlm_cbd",
1827                                 ldlm_svc_proc_dir, NULL,
1828                                 LDLM_THREADS_AUTO_MIN, LDLM_THREADS_AUTO_MAX,
1829                                 "ldlm_cb",
1830                                 LCT_MD_THREAD|LCT_DT_THREAD);
1831
1832         if (!ldlm_state->ldlm_cb_service) {
1833                 CERROR("failed to start service\n");
1834                 GOTO(out_proc, rc = -ENOMEM);
1835         }
1836
1837         ldlm_state->ldlm_cancel_service =
1838                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
1839                                 LDLM_MAXREPSIZE, LDLM_CANCEL_REQUEST_PORTAL,
1840                                 LDLM_CANCEL_REPLY_PORTAL, ldlm_timeout * 6000,
1841                                 ldlm_cancel_handler, "ldlm_canceld",
1842                                 ldlm_svc_proc_dir, NULL,
1843                                 LDLM_THREADS_AUTO_MIN, LDLM_THREADS_AUTO_MAX,
1844                                 "ldlm_cn",
1845                                 LCT_MD_THREAD|LCT_DT_THREAD|LCT_CL_THREAD);
1846
1847         if (!ldlm_state->ldlm_cancel_service) {
1848                 CERROR("failed to start service\n");
1849                 GOTO(out_proc, rc = -ENOMEM);
1850         }
1851
1852         OBD_ALLOC(blp, sizeof(*blp));
1853         if (blp == NULL)
1854                 GOTO(out_proc, rc = -ENOMEM);
1855         ldlm_state->ldlm_bl_pool = blp;
1856
1857         atomic_set(&blp->blp_num_threads, 0);
1858         cfs_waitq_init(&blp->blp_waitq);
1859         spin_lock_init(&blp->blp_lock);
1860
1861         CFS_INIT_LIST_HEAD(&blp->blp_list);
1862
1863 #ifdef __KERNEL__
1864         for (i = 0; i < LDLM_BL_THREADS; i++) {
1865                 struct ldlm_bl_thread_data bltd = {
1866                         .bltd_num = i,
1867                         .bltd_blp = blp,
1868                 };
1869                 init_completion(&blp->blp_comp);
1870                 rc = cfs_kernel_thread(ldlm_bl_thread_main, &bltd, 0);
1871                 if (rc < 0) {
1872                         CERROR("cannot start LDLM thread #%d: rc %d\n", i, rc);
1873                         GOTO(out_thread, rc);
1874                 }
1875                 wait_for_completion(&blp->blp_comp);
1876         }
1877
1878         rc = ptlrpc_start_threads(NULL, ldlm_state->ldlm_cancel_service);
1879         if (rc)
1880                 GOTO(out_thread, rc);
1881
1882         rc = ptlrpc_start_threads(NULL, ldlm_state->ldlm_cb_service);
1883         if (rc)
1884                 GOTO(out_thread, rc);
1885
1886         CFS_INIT_LIST_HEAD(&expired_lock_thread.elt_expired_locks);
1887         expired_lock_thread.elt_state = ELT_STOPPED;
1888         cfs_waitq_init(&expired_lock_thread.elt_waitq);
1889
1890         CFS_INIT_LIST_HEAD(&waiting_locks_list);
1891         spin_lock_init(&waiting_locks_spinlock);
1892         cfs_timer_init(&waiting_locks_timer, waiting_locks_callback, 0);
1893
1894         rc = cfs_kernel_thread(expired_lock_main, NULL, CLONE_VM | CLONE_FILES);
1895         if (rc < 0) {
1896                 CERROR("Cannot start ldlm expired-lock thread: %d\n", rc);
1897                 GOTO(out_thread, rc);
1898         }
1899
1900         wait_event(expired_lock_thread.elt_waitq,
1901                    expired_lock_thread.elt_state == ELT_READY);
1902 #endif
1903
1904 #ifdef __KERNEL__
1905         rc = ldlm_pools_init(client);
1906         if (rc)
1907                 GOTO(out_thread, rc);
1908 #endif
1909         RETURN(0);
1910
1911 #ifdef __KERNEL__
1912  out_thread:
1913         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
1914         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
1915 #endif
1916
1917  out_proc:
1918 #ifdef LPROCFS
1919         ldlm_proc_cleanup();
1920  out_free:
1921 #endif
1922         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
1923         ldlm_state = NULL;
1924         return rc;
1925 }
1926
1927 static int ldlm_cleanup(ldlm_side_t client, int force)
1928 {
1929 #ifdef __KERNEL__
1930         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1931 #endif
1932         ENTRY;
1933
1934         if (!list_empty(ldlm_namespace_list(LDLM_NAMESPACE_SERVER)) || 
1935             !list_empty(ldlm_namespace_list(LDLM_NAMESPACE_CLIENT))) {
1936                 CERROR("ldlm still has namespaces; clean these up first.\n");
1937                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
1938                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
1939                 RETURN(-EBUSY);
1940         }
1941
1942 #ifdef __KERNEL__
1943         ldlm_pools_fini();
1944 #endif
1945
1946 #ifdef __KERNEL__
1947         while (atomic_read(&blp->blp_num_threads) > 0) {
1948                 struct ldlm_bl_work_item blwi = { .blwi_ns = NULL };
1949
1950                 init_completion(&blp->blp_comp);
1951
1952                 spin_lock(&blp->blp_lock);
1953                 list_add_tail(&blwi.blwi_entry, &blp->blp_list);
1954                 cfs_waitq_signal(&blp->blp_waitq);
1955                 spin_unlock(&blp->blp_lock);
1956
1957                 wait_for_completion(&blp->blp_comp);
1958         }
1959         OBD_FREE(blp, sizeof(*blp));
1960
1961         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
1962         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
1963         ldlm_proc_cleanup();
1964
1965         expired_lock_thread.elt_state = ELT_TERMINATE;
1966         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
1967         wait_event(expired_lock_thread.elt_waitq,
1968                    expired_lock_thread.elt_state == ELT_STOPPED);
1969 #else
1970         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
1971         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
1972 #endif
1973
1974         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
1975         ldlm_state = NULL;
1976
1977         RETURN(0);
1978 }
1979
1980 int __init ldlm_init(void)
1981 {
1982         init_mutex(&ldlm_ref_sem);
1983         init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_SERVER));
1984         init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
1985         ldlm_resource_slab = cfs_mem_cache_create("ldlm_resources",
1986                                                sizeof(struct ldlm_resource), 0,
1987                                                SLAB_HWCACHE_ALIGN);
1988         if (ldlm_resource_slab == NULL)
1989                 return -ENOMEM;
1990
1991         ldlm_lock_slab = cfs_mem_cache_create("ldlm_locks",
1992                                            sizeof(struct ldlm_lock), 0,
1993                                            SLAB_HWCACHE_ALIGN);
1994         if (ldlm_lock_slab == NULL) {
1995                 cfs_mem_cache_destroy(ldlm_resource_slab);
1996                 return -ENOMEM;
1997         }
1998
1999         return 0;
2000 }
2001
2002 void __exit ldlm_exit(void)
2003 {
2004         int rc;
2005         if (ldlm_refcount)
2006                 CERROR("ldlm_refcount is %d in ldlm_exit!\n", ldlm_refcount);
2007         rc = cfs_mem_cache_destroy(ldlm_resource_slab);
2008         LASSERTF(rc == 0, "couldn't free ldlm resource slab\n");
2009         rc = cfs_mem_cache_destroy(ldlm_lock_slab);
2010         LASSERTF(rc == 0, "couldn't free ldlm lock slab\n");
2011 }
2012
2013 /* ldlm_extent.c */
2014 EXPORT_SYMBOL(ldlm_extent_shift_kms);
2015
2016 /* ldlm_lock.c */
2017 EXPORT_SYMBOL(ldlm_get_processing_policy);
2018 EXPORT_SYMBOL(ldlm_lock2desc);
2019 EXPORT_SYMBOL(ldlm_register_intent);
2020 EXPORT_SYMBOL(ldlm_lockname);
2021 EXPORT_SYMBOL(ldlm_typename);
2022 EXPORT_SYMBOL(ldlm_lock2handle);
2023 EXPORT_SYMBOL(__ldlm_handle2lock);
2024 EXPORT_SYMBOL(ldlm_lock_get);
2025 EXPORT_SYMBOL(ldlm_lock_put);
2026 EXPORT_SYMBOL(ldlm_lock_match);
2027 EXPORT_SYMBOL(ldlm_lock_cancel);
2028 EXPORT_SYMBOL(ldlm_lock_addref);
2029 EXPORT_SYMBOL(ldlm_lock_decref);
2030 EXPORT_SYMBOL(ldlm_lock_decref_and_cancel);
2031 EXPORT_SYMBOL(ldlm_lock_change_resource);
2032 EXPORT_SYMBOL(ldlm_lock_set_data);
2033 EXPORT_SYMBOL(ldlm_it2str);
2034 EXPORT_SYMBOL(ldlm_lock_dump);
2035 EXPORT_SYMBOL(ldlm_lock_dump_handle);
2036 EXPORT_SYMBOL(ldlm_cancel_locks_for_export);
2037 EXPORT_SYMBOL(ldlm_reprocess_all_ns);
2038 EXPORT_SYMBOL(ldlm_lock_allow_match);
2039
2040 /* ldlm_request.c */
2041 EXPORT_SYMBOL(ldlm_completion_ast);
2042 EXPORT_SYMBOL(ldlm_blocking_ast);
2043 EXPORT_SYMBOL(ldlm_glimpse_ast);
2044 EXPORT_SYMBOL(ldlm_expired_completion_wait);
2045 EXPORT_SYMBOL(ldlm_prep_enqueue_req);
2046 EXPORT_SYMBOL(ldlm_cli_convert);
2047 EXPORT_SYMBOL(ldlm_cli_enqueue);
2048 EXPORT_SYMBOL(ldlm_cli_enqueue_fini);
2049 EXPORT_SYMBOL(ldlm_cli_enqueue_local);
2050 EXPORT_SYMBOL(ldlm_cli_cancel);
2051 EXPORT_SYMBOL(ldlm_cli_cancel_unused);
2052 EXPORT_SYMBOL(ldlm_cli_cancel_unused_resource);
2053 EXPORT_SYMBOL(ldlm_cli_cancel_req);
2054 EXPORT_SYMBOL(ldlm_cli_join_lru);
2055 EXPORT_SYMBOL(ldlm_replay_locks);
2056 EXPORT_SYMBOL(ldlm_resource_foreach);
2057 EXPORT_SYMBOL(ldlm_namespace_foreach);
2058 EXPORT_SYMBOL(ldlm_namespace_foreach_res);
2059 EXPORT_SYMBOL(ldlm_resource_iterate);
2060 EXPORT_SYMBOL(ldlm_cancel_resource_local);
2061 EXPORT_SYMBOL(ldlm_cli_cancel_list);
2062
2063 /* ldlm_lockd.c */
2064 EXPORT_SYMBOL(ldlm_server_blocking_ast);
2065 EXPORT_SYMBOL(ldlm_server_completion_ast);
2066 EXPORT_SYMBOL(ldlm_server_glimpse_ast);
2067 EXPORT_SYMBOL(ldlm_handle_enqueue);
2068 EXPORT_SYMBOL(ldlm_handle_enqueue0);
2069 EXPORT_SYMBOL(ldlm_handle_cancel);
2070 EXPORT_SYMBOL(ldlm_request_cancel);
2071 EXPORT_SYMBOL(ldlm_handle_convert);
2072 EXPORT_SYMBOL(ldlm_handle_convert0);
2073 EXPORT_SYMBOL(ldlm_del_waiting_lock);
2074 EXPORT_SYMBOL(ldlm_get_ref);
2075 EXPORT_SYMBOL(ldlm_put_ref);
2076 EXPORT_SYMBOL(ldlm_refresh_waiting_lock);
2077 EXPORT_SYMBOL(ldlm_revoke_export_locks);
2078
2079 /* ldlm_resource.c */
2080 EXPORT_SYMBOL(ldlm_namespace_new);
2081 EXPORT_SYMBOL(ldlm_namespace_cleanup);
2082 EXPORT_SYMBOL(ldlm_namespace_free);
2083 EXPORT_SYMBOL(ldlm_namespace_dump);
2084 EXPORT_SYMBOL(ldlm_dump_all_namespaces);
2085 EXPORT_SYMBOL(ldlm_resource_get);
2086 EXPORT_SYMBOL(ldlm_resource_putref);
2087 EXPORT_SYMBOL(ldlm_resource_unlink_lock);
2088
2089 /* ldlm_lib.c */
2090 EXPORT_SYMBOL(client_import_add_conn);
2091 EXPORT_SYMBOL(client_import_del_conn);
2092 EXPORT_SYMBOL(client_obd_setup);
2093 EXPORT_SYMBOL(client_obd_cleanup);
2094 EXPORT_SYMBOL(client_connect_import);
2095 EXPORT_SYMBOL(client_disconnect_export);
2096 EXPORT_SYMBOL(target_start_recovery_thread);
2097 EXPORT_SYMBOL(target_stop_recovery_thread);
2098 EXPORT_SYMBOL(target_handle_connect);
2099 EXPORT_SYMBOL(target_cleanup_recovery);
2100 EXPORT_SYMBOL(target_destroy_export);
2101 EXPORT_SYMBOL(target_cancel_recovery_timer);
2102 EXPORT_SYMBOL(target_send_reply);
2103 EXPORT_SYMBOL(target_queue_recovery_request);
2104 EXPORT_SYMBOL(target_handle_ping);
2105 EXPORT_SYMBOL(target_pack_pool_reply);
2106 EXPORT_SYMBOL(target_handle_disconnect);
2107
2108 /* l_lock.c */
2109 EXPORT_SYMBOL(lock_res_and_lock);
2110 EXPORT_SYMBOL(unlock_res_and_lock);
2111