Whamcloud - gitweb
7eb6127f5aff1eea4fe332dbe45538f97cdabcdf
[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 static int ldlm_cb_interpret(struct ptlrpc_request *req, void *data, int rc)
499 {
500         struct ldlm_cb_set_arg *arg;
501         struct ldlm_lock *lock;
502         ENTRY;
503
504         LASSERT(data != NULL);
505
506         arg = req->rq_async_args.pointer_arg[0];
507         lock = req->rq_async_args.pointer_arg[1];
508         LASSERT(lock != NULL);
509         if (rc != 0) {
510                 /* If client canceled the lock but the cancel has not 
511                  * been recieved yet, we need to update lvbo to have the
512                  * proper attributes cached. */
513                 if (rc == -EINVAL && arg->type == LDLM_BL_CALLBACK)
514                         ldlm_res_lvbo_update(lock->l_resource, NULL, 
515                                              0, 1);
516                 rc = ldlm_handle_ast_error(lock, req, rc, 
517                                            arg->type == LDLM_BL_CALLBACK
518                                            ? "blocking" : "completion");
519         }                
520
521         LDLM_LOCK_PUT(lock);
522
523         if (rc == -ERESTART)
524                 atomic_set(&arg->restart, 1);
525
526         RETURN(0);
527 }
528
529 static inline int ldlm_bl_and_cp_ast_fini(struct ptlrpc_request *req,
530                                           struct ldlm_cb_set_arg *arg,
531                                           struct ldlm_lock *lock,
532                                           int instant_cancel)
533 {
534         int rc = 0;
535         ENTRY;
536
537         if (unlikely(instant_cancel)) {
538                 rc = ptl_send_rpc(req, 1);
539                 ptlrpc_req_finished(req);
540                 if (rc == 0)
541                         /* If we cancelled the lock, we need to restart
542                          * ldlm_reprocess_queue */
543                         atomic_set(&arg->restart, 1);
544         } else {
545                 LDLM_LOCK_GET(lock);
546                 ptlrpc_set_add_req(arg->set, req);
547         }       
548
549         RETURN(rc);
550 }
551
552 /*
553  * ->l_blocking_ast() method for server-side locks. This is invoked when newly
554  * enqueued server lock conflicts with given one.
555  *
556  * Sends blocking ast rpc to the client owning that lock; arms timeout timer
557  * to wait for client response.
558  */
559 int ldlm_server_blocking_ast(struct ldlm_lock *lock,
560                              struct ldlm_lock_desc *desc,
561                              void *data, int flag)
562 {
563         struct ldlm_cb_set_arg *arg = data;
564         struct ldlm_request *body;
565         struct ptlrpc_request *req;
566         int size[] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
567                        [DLM_LOCKREQ_OFF]     = sizeof(*body) };
568         int instant_cancel = 0, rc;
569         ENTRY;
570
571         if (flag == LDLM_CB_CANCELING) {
572                 /* Don't need to do anything here. */
573                 RETURN(0);
574         }
575
576         LASSERT(lock);
577         LASSERT(data != NULL);
578         if (lock->l_export->exp_obd->obd_recovering != 0) {
579                 LDLM_ERROR(lock, "BUG 6063: lock collide during recovery");
580                 ldlm_lock_dump(D_ERROR, lock, 0);
581         }
582
583         req = ptlrpc_prep_req(lock->l_export->exp_imp_reverse,
584                               LUSTRE_DLM_VERSION, LDLM_BL_CALLBACK, 2, size,
585                               NULL);
586         if (req == NULL)
587                 RETURN(-ENOMEM);
588
589         req->rq_async_args.pointer_arg[0] = arg;
590         req->rq_async_args.pointer_arg[1] = lock;
591         req->rq_interpret_reply = ldlm_cb_interpret;
592         req->rq_no_resend = 1;
593
594         lock_res(lock->l_resource);
595         if (lock->l_granted_mode != lock->l_req_mode) {
596                 /* this blocking AST will be communicated as part of the
597                  * completion AST instead */
598                 unlock_res(lock->l_resource);
599                 ptlrpc_req_finished(req);
600                 LDLM_DEBUG(lock, "lock not granted, not sending blocking AST");
601                 RETURN(0);
602         }
603
604         if (lock->l_destroyed) {
605                 /* What's the point? */
606                 unlock_res(lock->l_resource);
607                 ptlrpc_req_finished(req);
608                 RETURN(0);
609         }
610
611         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
612                 instant_cancel = 1;
613
614         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
615         body->lock_handle[0] = lock->l_remote_handle;
616         body->lock_desc = *desc;
617         body->lock_flags |= (lock->l_flags & LDLM_AST_FLAGS);
618
619         LDLM_DEBUG(lock, "server preparing blocking AST");
620
621         ptlrpc_req_set_repsize(req, 1, NULL);
622         if (instant_cancel) {
623                 unlock_res(lock->l_resource);
624                 ldlm_lock_cancel(lock);
625         } else {
626                 LASSERT(lock->l_granted_mode == lock->l_req_mode);
627                 ldlm_add_waiting_lock(lock);
628                 unlock_res(lock->l_resource);
629         }
630
631         req->rq_send_state = LUSTRE_IMP_FULL;
632         req->rq_timeout = ldlm_get_rq_timeout(ldlm_timeout, obd_timeout);
633
634         if (lock->l_export && lock->l_export->exp_ldlm_stats)
635                 lprocfs_counter_incr(lock->l_export->exp_ldlm_stats,
636                                      LDLM_BL_CALLBACK - LDLM_FIRST_OPC);
637
638         rc = ldlm_bl_and_cp_ast_fini(req, arg, lock, instant_cancel);
639
640         RETURN(rc);
641 }
642
643 int ldlm_server_completion_ast(struct ldlm_lock *lock, int flags, void *data)
644 {
645         struct ldlm_cb_set_arg *arg = data;
646         struct ldlm_request *body;
647         struct ptlrpc_request *req;
648         struct timeval granted_time;
649         long total_enqueue_wait;
650         int size[3] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
651                         [DLM_LOCKREQ_OFF]     = sizeof(*body) };
652         int rc, buffers = 2, instant_cancel = 0;
653         ENTRY;
654
655         LASSERT(lock != NULL);
656         LASSERT(data != NULL);
657
658         do_gettimeofday(&granted_time);
659         total_enqueue_wait = cfs_timeval_sub(&granted_time,
660                                              &lock->l_enqueued_time, NULL);
661
662         if (total_enqueue_wait / 1000000 > obd_timeout)
663                 LDLM_ERROR(lock, "enqueue wait took %luus from %lu",
664                            total_enqueue_wait, lock->l_enqueued_time.tv_sec);
665
666         lock_res_and_lock(lock);
667         if (lock->l_resource->lr_lvb_len) {
668                 size[DLM_REQ_REC_OFF] = lock->l_resource->lr_lvb_len;
669                 buffers = 3;
670         }
671         unlock_res_and_lock(lock);
672
673         req = ptlrpc_prep_req(lock->l_export->exp_imp_reverse,
674                               LUSTRE_DLM_VERSION, LDLM_CP_CALLBACK, buffers,
675                               size, NULL);
676         if (req == NULL)
677                 RETURN(-ENOMEM);
678
679         req->rq_async_args.pointer_arg[0] = arg;
680         req->rq_async_args.pointer_arg[1] = lock;
681         req->rq_interpret_reply = ldlm_cb_interpret;
682         req->rq_no_resend = 1;
683
684         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
685         body->lock_handle[0] = lock->l_remote_handle;
686         body->lock_flags = flags;
687         ldlm_lock2desc(lock, &body->lock_desc);
688
689         if (buffers == 3) {
690                 void *lvb;
691
692                 lvb = lustre_msg_buf(req->rq_reqmsg, DLM_REQ_REC_OFF,
693                                      lock->l_resource->lr_lvb_len);
694                 lock_res_and_lock(lock);
695                 memcpy(lvb, lock->l_resource->lr_lvb_data,
696                        lock->l_resource->lr_lvb_len);
697                 unlock_res_and_lock(lock);
698         }
699
700         LDLM_DEBUG(lock, "server preparing completion AST (after %ldus wait)",
701                    total_enqueue_wait);
702
703         ptlrpc_req_set_repsize(req, 1, NULL);
704
705         req->rq_send_state = LUSTRE_IMP_FULL;
706         req->rq_timeout = ldlm_get_rq_timeout(ldlm_timeout, obd_timeout);
707
708         /* We only send real blocking ASTs after the lock is granted */
709         lock_res_and_lock(lock);
710         if (lock->l_flags & LDLM_FL_AST_SENT) {
711                 body->lock_flags |= LDLM_FL_AST_SENT;
712
713                 /* We might get here prior to ldlm_handle_enqueue setting
714                  * LDLM_FL_CANCEL_ON_BLOCK flag. Then we will put this lock
715                  * into waiting list, but this is safe and similar code in
716                  * ldlm_handle_enqueue will call ldlm_lock_cancel() still,
717                  * that would not only cancel the lock, but will also remove
718                  * it from waiting list */
719                 if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
720                         unlock_res_and_lock(lock);
721                         ldlm_lock_cancel(lock);
722                         instant_cancel = 1;
723                         lock_res_and_lock(lock);
724                 } else {
725                         /* start the lock-timeout clock */
726                         ldlm_add_waiting_lock(lock);
727                 }
728         }
729         unlock_res_and_lock(lock);
730
731         if (lock->l_export && lock->l_export->exp_ldlm_stats)
732                 lprocfs_counter_incr(lock->l_export->exp_ldlm_stats,
733                                      LDLM_CP_CALLBACK - LDLM_FIRST_OPC);
734
735         rc = ldlm_bl_and_cp_ast_fini(req, arg, lock, instant_cancel);
736
737         RETURN(rc);
738 }
739
740 int ldlm_server_glimpse_ast(struct ldlm_lock *lock, void *data)
741 {
742         struct ldlm_resource *res = lock->l_resource;
743         struct ldlm_request *body;
744         struct ptlrpc_request *req;
745         int size[] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
746                        [DLM_LOCKREQ_OFF]     = sizeof(*body) };
747         int rc = 0;
748         ENTRY;
749
750         LASSERT(lock != NULL);
751
752         req = ptlrpc_prep_req(lock->l_export->exp_imp_reverse,
753                               LUSTRE_DLM_VERSION, LDLM_GL_CALLBACK, 2, size,
754                               NULL);
755         if (req == NULL)
756                 RETURN(-ENOMEM);
757
758         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
759         body->lock_handle[0] = lock->l_remote_handle;
760         ldlm_lock2desc(lock, &body->lock_desc);
761
762         lock_res_and_lock(lock);
763         size[REPLY_REC_OFF] = lock->l_resource->lr_lvb_len;
764         unlock_res_and_lock(lock);
765         res = lock->l_resource;
766         ptlrpc_req_set_repsize(req, 2, size);
767
768         req->rq_send_state = LUSTRE_IMP_FULL;
769         req->rq_timeout = ldlm_get_rq_timeout(ldlm_timeout, obd_timeout);
770
771         if (lock->l_export && lock->l_export->exp_ldlm_stats)
772                 lprocfs_counter_incr(lock->l_export->exp_ldlm_stats,
773                                      LDLM_GL_CALLBACK - LDLM_FIRST_OPC);
774
775         rc = ptlrpc_queue_wait(req);
776         if (rc == -ELDLM_NO_LOCK_DATA)
777                 LDLM_DEBUG(lock, "lost race - client has a lock but no inode");
778         else if (rc != 0)
779                 rc = ldlm_handle_ast_error(lock, req, rc, "glimpse");
780         else
781                 rc = ldlm_res_lvbo_update(res, req->rq_repmsg,
782                                           REPLY_REC_OFF, 1);
783         ptlrpc_req_finished(req);
784         RETURN(rc);
785 }
786
787 static struct ldlm_lock *
788 find_existing_lock(struct obd_export *exp,
789                    const struct lustre_handle *remote_hdl)
790 {
791         struct list_head *iter;
792
793         spin_lock(&exp->exp_ldlm_data.led_lock);
794         list_for_each(iter, &exp->exp_ldlm_data.led_held_locks) {
795                 struct ldlm_lock *lock;
796                 lock = list_entry(iter, struct ldlm_lock, l_export_chain);
797                 if (lock->l_remote_handle.cookie == remote_hdl->cookie) {
798                         LDLM_LOCK_GET(lock);
799                         spin_unlock(&exp->exp_ldlm_data.led_lock);
800                         return lock;
801                 }
802         }
803         spin_unlock(&exp->exp_ldlm_data.led_lock);
804         return NULL;
805 }
806
807 #ifdef __KERNEL__
808 extern unsigned long long lu_time_stamp_get(void);
809 #else
810 #define lu_time_stamp_get() time(NULL)
811 #endif
812
813 /*
814  * Main server-side entry point into LDLM. This is called by ptlrpc service
815  * threads to carry out client lock enqueueing requests.
816  */
817 int ldlm_handle_enqueue0(struct ldlm_namespace *ns,
818                          struct ptlrpc_request *req,
819                          const struct ldlm_request *dlm_req,
820                          const struct ldlm_callback_suite *cbs)
821 {
822         struct ldlm_reply *dlm_rep;
823         int size[3] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
824                         [DLM_LOCKREPLY_OFF]   = sizeof(*dlm_rep) };
825         int rc = 0;
826         __u32 flags;
827         ldlm_error_t err = ELDLM_OK;
828         struct ldlm_lock *lock = NULL;
829         void *cookie = NULL;
830         ENTRY;
831
832         LDLM_DEBUG_NOLOCK("server-side enqueue handler START");
833
834         ldlm_request_cancel(req, dlm_req, LDLM_ENQUEUE_CANCEL_OFF);
835         flags = dlm_req->lock_flags;
836
837         LASSERT(req->rq_export);
838
839         if (req->rq_export->exp_ldlm_stats)
840                 lprocfs_counter_incr(req->rq_export->exp_ldlm_stats,
841                                      LDLM_ENQUEUE - LDLM_FIRST_OPC);
842
843         if (unlikely(dlm_req->lock_desc.l_resource.lr_type < LDLM_MIN_TYPE ||
844                      dlm_req->lock_desc.l_resource.lr_type >= LDLM_MAX_TYPE)) {
845                 DEBUG_REQ(D_ERROR, req, "invalid lock request type %d",
846                           dlm_req->lock_desc.l_resource.lr_type);
847                 GOTO(out, rc = -EFAULT);
848         }
849
850         if (unlikely(dlm_req->lock_desc.l_req_mode <= LCK_MINMODE ||
851                      dlm_req->lock_desc.l_req_mode >= LCK_MAXMODE ||
852                      dlm_req->lock_desc.l_req_mode &
853                      (dlm_req->lock_desc.l_req_mode-1))) {
854                 DEBUG_REQ(D_ERROR, req, "invalid lock request mode %d",
855                           dlm_req->lock_desc.l_req_mode);
856                 GOTO(out, rc = -EFAULT);
857         }
858
859         if (req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) {
860                 if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
861                              LDLM_PLAIN)) {
862                         DEBUG_REQ(D_ERROR, req,
863                                   "PLAIN lock request from IBITS client?");
864                         GOTO(out, rc = -EPROTO);
865                 }
866         } else if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
867                             LDLM_IBITS)) {
868                 DEBUG_REQ(D_ERROR, req,
869                           "IBITS lock request from unaware client?");
870                 GOTO(out, rc = -EPROTO);
871         }
872
873 #if 0
874         /* FIXME this makes it impossible to use LDLM_PLAIN locks -- check
875            against server's _CONNECT_SUPPORTED flags? (I don't want to use
876            ibits for mgc/mgs) */
877
878         /* INODEBITS_INTEROP: Perform conversion from plain lock to
879          * inodebits lock if client does not support them. */
880         if (!(req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) &&
881             (dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN)) {
882                 dlm_req->lock_desc.l_resource.lr_type = LDLM_IBITS;
883                 dlm_req->lock_desc.l_policy_data.l_inodebits.bits =
884                         MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
885                 if (dlm_req->lock_desc.l_req_mode == LCK_PR)
886                         dlm_req->lock_desc.l_req_mode = LCK_CR;
887         }
888 #endif
889
890         if (unlikely(flags & LDLM_FL_REPLAY)) {
891                 lock = find_existing_lock(req->rq_export,
892                                           &dlm_req->lock_handle[0]);
893                 if (lock != NULL) {
894                         DEBUG_REQ(D_DLMTRACE, req, "found existing lock cookie "
895                                   LPX64, lock->l_handle.h_cookie);
896                         GOTO(existing_lock, rc = 0);
897                 }
898         }
899
900         /* The lock's callback data might be set in the policy function */
901         lock = ldlm_lock_create(ns, &dlm_req->lock_desc.l_resource.lr_name,
902                                 dlm_req->lock_desc.l_resource.lr_type,
903                                 dlm_req->lock_desc.l_req_mode,
904                                 cbs->lcs_blocking, cbs->lcs_completion,
905                                 cbs->lcs_glimpse, NULL, 0);
906
907         if (!lock)
908                 GOTO(out, rc = -ENOMEM);
909
910         do_gettimeofday(&lock->l_enqueued_time);
911         lock->l_remote_handle = dlm_req->lock_handle[0];
912         LDLM_DEBUG(lock, "server-side enqueue handler, new lock created");
913
914         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_ENQUEUE_BLOCKED, obd_timeout * 2);
915         /* Don't enqueue a lock onto the export if it has already
916          * been evicted.  Cancel it now instead. (bug 3822) */
917         if (req->rq_export->exp_failed) {
918                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
919                 GOTO(out, rc = -ENOTCONN);
920         }
921         lock->l_export = class_export_get(req->rq_export);
922         spin_lock(&lock->l_export->exp_ldlm_data.led_lock);
923         list_add(&lock->l_export_chain,
924                  &lock->l_export->exp_ldlm_data.led_held_locks);
925         spin_unlock(&lock->l_export->exp_ldlm_data.led_lock);
926
927 existing_lock:
928
929         if (flags & LDLM_FL_HAS_INTENT) {
930                 /* In this case, the reply buffer is allocated deep in
931                  * local_lock_enqueue by the policy function. */
932                 cookie = req;
933         } else {
934                 int buffers = 2;
935
936                 lock_res_and_lock(lock);
937                 if (lock->l_resource->lr_lvb_len) {
938                         size[DLM_REPLY_REC_OFF] = lock->l_resource->lr_lvb_len;
939                         buffers = 3;
940                 }
941                 unlock_res_and_lock(lock);
942
943                 if (OBD_FAIL_CHECK_ONCE(OBD_FAIL_LDLM_ENQUEUE_EXTENT_ERR))
944                         GOTO(out, rc = -ENOMEM);
945
946                 rc = lustre_pack_reply(req, buffers, size, NULL);
947                 if (rc)
948                         GOTO(out, rc);
949         }
950
951         if (dlm_req->lock_desc.l_resource.lr_type != LDLM_PLAIN)
952                 lock->l_policy_data = dlm_req->lock_desc.l_policy_data;
953         if (dlm_req->lock_desc.l_resource.lr_type == LDLM_EXTENT)
954                 lock->l_req_extent = lock->l_policy_data.l_extent;
955
956         err = ldlm_lock_enqueue(ns, &lock, cookie, &flags);
957         if (err)
958                 GOTO(out, err);
959
960         dlm_rep = lustre_msg_buf(req->rq_repmsg, DLM_LOCKREPLY_OFF,
961                                  sizeof(*dlm_rep));
962         dlm_rep->lock_flags = flags;
963
964         ldlm_lock2desc(lock, &dlm_rep->lock_desc);
965         ldlm_lock2handle(lock, &dlm_rep->lock_handle);
966
967         /* We never send a blocking AST until the lock is granted, but
968          * we can tell it right now */
969         lock_res_and_lock(lock);
970
971         /* Now take into account flags to be inherited from original lock
972            request both in reply to client and in our own lock flags. */
973         dlm_rep->lock_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
974         lock->l_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
975
976         /* Don't move a pending lock onto the export if it has already
977          * been evicted.  Cancel it now instead. (bug 5683) */
978         if (unlikely(req->rq_export->exp_failed ||
979                      OBD_FAIL_CHECK_ONCE(OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT))) {
980                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
981                 rc = -ENOTCONN;
982         } else if (lock->l_flags & LDLM_FL_AST_SENT) {
983                 dlm_rep->lock_flags |= LDLM_FL_AST_SENT;
984                 if (lock->l_granted_mode == lock->l_req_mode) {
985                         /*
986                          * Only cancel lock if it was granted, because it would
987                          * be destroyed immediatelly and would never be granted
988                          * in the future, causing timeouts on client.  Not
989                          * granted lock will be cancelled immediatelly after
990                          * sending completion AST.
991                          */
992                         if (dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK) {
993                                 unlock_res_and_lock(lock);
994                                 ldlm_lock_cancel(lock);
995                                 lock_res_and_lock(lock);
996                         } else
997                                 ldlm_add_waiting_lock(lock);
998                 }
999         }
1000         /* Make sure we never ever grant usual metadata locks to liblustre
1001            clients */
1002         if ((dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN ||
1003             dlm_req->lock_desc.l_resource.lr_type == LDLM_IBITS) &&
1004              req->rq_export->exp_libclient) {
1005                 if (unlikely(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) ||
1006                              !(dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK))){
1007                         CERROR("Granting sync lock to libclient. "
1008                                "req fl %d, rep fl %d, lock fl %d\n",
1009                                dlm_req->lock_flags, dlm_rep->lock_flags,
1010                                lock->l_flags);
1011                         LDLM_ERROR(lock, "sync lock");
1012                         if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT) {
1013                                 struct ldlm_intent *it;
1014                                 it = lustre_msg_buf(req->rq_reqmsg,
1015                                                     DLM_INTENT_IT_OFF,
1016                                                     sizeof(*it));
1017                                 if (it != NULL) {
1018                                         CERROR("This is intent %s ("LPU64")\n",
1019                                                ldlm_it2str(it->opc), it->opc);
1020                                 }
1021                         }
1022                 }
1023         }
1024
1025         unlock_res_and_lock(lock);
1026
1027         EXIT;
1028  out:
1029         req->rq_status = err;
1030         if (req->rq_reply_state == NULL) {
1031                 err = lustre_pack_reply(req, 1, NULL, NULL);
1032                 if (rc == 0)
1033                         rc = err;
1034                 req->rq_status = rc;
1035         }
1036
1037         /* The LOCK_CHANGED code in ldlm_lock_enqueue depends on this
1038          * ldlm_reprocess_all.  If this moves, revisit that code. -phil */
1039         if (lock) {
1040                 LDLM_DEBUG(lock, "server-side enqueue handler, sending reply"
1041                            "(err=%d, rc=%d)", err, rc);
1042
1043                 lock_res_and_lock(lock);
1044                 if (rc == 0) {
1045                         size[DLM_REPLY_REC_OFF] = lock->l_resource->lr_lvb_len;
1046                         if (size[DLM_REPLY_REC_OFF] > 0) {
1047                                 void *lvb = lustre_msg_buf(req->rq_repmsg,
1048                                                        DLM_REPLY_REC_OFF,
1049                                                        size[DLM_REPLY_REC_OFF]);
1050                                 LASSERTF(lvb != NULL, "req %p, lock %p\n",
1051                                          req, lock);
1052
1053                                 memcpy(lvb, lock->l_resource->lr_lvb_data,
1054                                        size[DLM_REPLY_REC_OFF]);
1055                         }
1056                 } else {
1057                         ldlm_resource_unlink_lock(lock);
1058                         ldlm_lock_destroy_nolock(lock);
1059                 }
1060                 unlock_res_and_lock(lock);
1061
1062                 if (!err && dlm_req->lock_desc.l_resource.lr_type != LDLM_FLOCK)
1063                         ldlm_reprocess_all(lock->l_resource);
1064
1065                 LDLM_LOCK_PUT(lock);
1066         }
1067
1068         LDLM_DEBUG_NOLOCK("server-side enqueue handler END (lock %p, rc %d)",
1069                           lock, rc);
1070
1071         return rc;
1072 }
1073
1074 int ldlm_handle_enqueue(struct ptlrpc_request *req,
1075                         ldlm_completion_callback completion_callback,
1076                         ldlm_blocking_callback blocking_callback,
1077                         ldlm_glimpse_callback glimpse_callback)
1078 {
1079         int rc;
1080         struct ldlm_request *dlm_req;
1081         struct ldlm_callback_suite cbs = {
1082                 .lcs_completion = completion_callback,
1083                 .lcs_blocking   = blocking_callback,
1084                 .lcs_glimpse    = glimpse_callback
1085         };
1086
1087
1088         dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF,
1089                                      sizeof *dlm_req, lustre_swab_ldlm_request);
1090         if (dlm_req != NULL) {
1091                 rc = ldlm_handle_enqueue0(req->rq_export->exp_obd->obd_namespace,
1092                                           req, dlm_req, &cbs);
1093         } else {
1094                 CERROR ("Can't unpack dlm_req\n");
1095                 rc = -EFAULT;
1096         }
1097         return rc;
1098 }
1099
1100 int ldlm_handle_convert0(struct ptlrpc_request *req,
1101                          const struct ldlm_request *dlm_req)
1102 {
1103         struct ldlm_reply *dlm_rep;
1104         struct ldlm_lock *lock;
1105         int rc;
1106         int size[2] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
1107                         [DLM_LOCKREPLY_OFF]   = sizeof(*dlm_rep) };
1108         ENTRY;
1109
1110         if (req->rq_export && req->rq_export->exp_ldlm_stats)
1111                 lprocfs_counter_incr(req->rq_export->exp_ldlm_stats,
1112                                      LDLM_CONVERT - LDLM_FIRST_OPC);
1113
1114         rc = lustre_pack_reply(req, 2, size, NULL);
1115         if (rc)
1116                 RETURN(rc);
1117
1118         dlm_rep = lustre_msg_buf(req->rq_repmsg, DLM_LOCKREPLY_OFF,
1119                                  sizeof(*dlm_rep));
1120         dlm_rep->lock_flags = dlm_req->lock_flags;
1121
1122         lock = ldlm_handle2lock(&dlm_req->lock_handle[0]);
1123         if (!lock) {
1124                 req->rq_status = EINVAL;
1125         } else {
1126                 void *res = NULL;
1127
1128                 LDLM_DEBUG(lock, "server-side convert handler START");
1129
1130                 do_gettimeofday(&lock->l_enqueued_time);
1131                 res = ldlm_lock_convert(lock, dlm_req->lock_desc.l_req_mode,
1132                                         &dlm_rep->lock_flags);
1133                 if (res) {
1134                         if (ldlm_del_waiting_lock(lock))
1135                                 LDLM_DEBUG(lock, "converted waiting lock");
1136                         req->rq_status = 0;
1137                 } else {
1138                         req->rq_status = EDEADLOCK;
1139                 }
1140         }
1141
1142         if (lock) {
1143                 if (!req->rq_status)
1144                         ldlm_reprocess_all(lock->l_resource);
1145                 LDLM_DEBUG(lock, "server-side convert handler END");
1146                 LDLM_LOCK_PUT(lock);
1147         } else
1148                 LDLM_DEBUG_NOLOCK("server-side convert handler END");
1149
1150         RETURN(0);
1151 }
1152
1153 int ldlm_handle_convert(struct ptlrpc_request *req)
1154 {
1155         int rc;
1156         struct ldlm_request *dlm_req;
1157
1158         dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF, sizeof *dlm_req,
1159                                      lustre_swab_ldlm_request);
1160         if (dlm_req != NULL) {
1161                 rc = ldlm_handle_convert0(req, dlm_req);
1162         } else {
1163                 CERROR ("Can't unpack dlm_req\n");
1164                 rc = -EFAULT;
1165         }
1166         return rc;
1167 }
1168
1169 /* Cancel all the locks, which handles are packed into ldlm_request */
1170 int ldlm_request_cancel(struct ptlrpc_request *req,
1171                         const struct ldlm_request *dlm_req, int first)
1172 {
1173         struct ldlm_resource *res, *pres = NULL;
1174         struct ldlm_lock *lock;
1175         int i, count, done = 0;
1176         ENTRY;
1177
1178         count = dlm_req->lock_count ? dlm_req->lock_count : 1;
1179         if (first >= count)
1180                 RETURN(0);
1181
1182         /* There is no lock on the server at the replay time,
1183          * skip lock cancelling to make replay tests to pass. */
1184         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1185                 RETURN(0);
1186
1187         LDLM_DEBUG_NOLOCK("server-side cancel handler START: %d locks, "
1188                           "starting at %d", count, first);
1189
1190         for (i = first; i < count; i++) {
1191                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
1192                 if (!lock) {
1193                         LDLM_DEBUG_NOLOCK("server-side cancel handler stale "
1194                                           "lock (cookie "LPU64")",
1195                                           dlm_req->lock_handle[i].cookie);
1196                         continue;
1197                 }
1198
1199                 res = lock->l_resource;
1200                 done++;
1201
1202                 if (res != pres) {
1203                         if (pres != NULL) {
1204                                 ldlm_reprocess_all(pres);
1205                                 ldlm_resource_putref(pres);
1206                         }
1207                         if (res != NULL) {
1208                                 ldlm_resource_getref(res);
1209                                 ldlm_res_lvbo_update(res, NULL, 0, 1);
1210                         }
1211                         pres = res;
1212                 }
1213                 ldlm_lock_cancel(lock);
1214                 LDLM_LOCK_PUT(lock);
1215         }
1216         if (pres != NULL) {
1217                 ldlm_reprocess_all(pres);
1218                 ldlm_resource_putref(pres);
1219         }
1220         LDLM_DEBUG_NOLOCK("server-side cancel handler END");
1221         RETURN(done);
1222 }
1223
1224 int ldlm_handle_cancel(struct ptlrpc_request *req)
1225 {
1226         struct ldlm_request *dlm_req;
1227         int rc;
1228         ENTRY;
1229
1230         dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF, sizeof(*dlm_req),
1231                                      lustre_swab_ldlm_request);
1232         if (dlm_req == NULL) {
1233                 CERROR("bad request buffer for cancel\n");
1234                 RETURN(-EFAULT);
1235         }
1236
1237         if (req->rq_export && req->rq_export->exp_ldlm_stats)
1238                 lprocfs_counter_incr(req->rq_export->exp_ldlm_stats,
1239                                      LDLM_CANCEL - LDLM_FIRST_OPC);
1240
1241         rc = lustre_pack_reply(req, 1, NULL, NULL);
1242         if (rc)
1243                 RETURN(rc);
1244
1245         if (!ldlm_request_cancel(req, dlm_req, 0))
1246                 req->rq_status = ESTALE;
1247
1248         if (ptlrpc_reply(req) != 0)
1249                 LBUG();
1250
1251         RETURN(0);
1252 }
1253
1254 void ldlm_handle_bl_callback(struct ldlm_namespace *ns,
1255                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock)
1256 {
1257         int do_ast;
1258         ENTRY;
1259
1260         LDLM_DEBUG(lock, "client blocking AST callback handler START");
1261
1262         lock_res_and_lock(lock);
1263         lock->l_flags |= LDLM_FL_CBPENDING;
1264
1265         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
1266                 lock->l_flags |= LDLM_FL_CANCEL;
1267
1268         do_ast = (!lock->l_readers && !lock->l_writers);
1269         unlock_res_and_lock(lock);
1270
1271         if (do_ast) {
1272                 LDLM_DEBUG(lock, "already unused, calling "
1273                            "callback (%p)", lock->l_blocking_ast);
1274                 if (lock->l_blocking_ast != NULL)
1275                         lock->l_blocking_ast(lock, ld, lock->l_ast_data,
1276                                              LDLM_CB_BLOCKING);
1277         } else {
1278                 LDLM_DEBUG(lock, "Lock still has references, will be"
1279                            " cancelled later");
1280         }
1281
1282         LDLM_DEBUG(lock, "client blocking callback handler END");
1283         LDLM_LOCK_PUT(lock);
1284         EXIT;
1285 }
1286
1287 static void ldlm_handle_cp_callback(struct ptlrpc_request *req,
1288                                     struct ldlm_namespace *ns,
1289                                     struct ldlm_request *dlm_req,
1290                                     struct ldlm_lock *lock)
1291 {
1292         CFS_LIST_HEAD(ast_list);
1293         ENTRY;
1294
1295         LDLM_DEBUG(lock, "client completion callback handler START");
1296
1297         lock_res_and_lock(lock);
1298
1299         /* If we receive the completion AST before the actual enqueue returned,
1300          * then we might need to switch lock modes, resources, or extents. */
1301         if (dlm_req->lock_desc.l_granted_mode != lock->l_req_mode) {
1302                 lock->l_req_mode = dlm_req->lock_desc.l_granted_mode;
1303                 LDLM_DEBUG(lock, "completion AST, new lock mode");
1304         }
1305
1306         if (lock->l_resource->lr_type != LDLM_PLAIN) {
1307                 lock->l_policy_data = dlm_req->lock_desc.l_policy_data;
1308                 LDLM_DEBUG(lock, "completion AST, new policy data");
1309         }
1310
1311         ldlm_resource_unlink_lock(lock);
1312         if (memcmp(&dlm_req->lock_desc.l_resource.lr_name,
1313                    &lock->l_resource->lr_name,
1314                    sizeof(lock->l_resource->lr_name)) != 0) {
1315                 unlock_res_and_lock(lock);
1316                 ldlm_lock_change_resource(ns, lock,
1317                                         &dlm_req->lock_desc.l_resource.lr_name);
1318                 LDLM_DEBUG(lock, "completion AST, new resource");
1319                 CERROR("change resource!\n");
1320                 lock_res_and_lock(lock);
1321         }
1322
1323         if (dlm_req->lock_flags & LDLM_FL_AST_SENT) {
1324                 lock->l_flags |= LDLM_FL_CBPENDING;
1325                 LDLM_DEBUG(lock, "completion AST includes blocking AST");
1326         }
1327
1328         if (lock->l_lvb_len) {
1329                 void *lvb;
1330                 lvb = lustre_swab_reqbuf(req, DLM_REQ_REC_OFF, lock->l_lvb_len,
1331                                          lock->l_lvb_swabber);
1332                 if (lvb == NULL) {
1333                         LDLM_ERROR(lock, "completion AST did not contain "
1334                                    "expected LVB!");
1335                 } else {
1336                         memcpy(lock->l_lvb_data, lvb, lock->l_lvb_len);
1337                 }
1338         }
1339
1340         ldlm_grant_lock(lock, &ast_list);
1341         unlock_res_and_lock(lock);
1342
1343         LDLM_DEBUG(lock, "callback handler finished, about to run_ast_work");
1344
1345         ldlm_run_cp_ast_work(&ast_list);
1346
1347         LDLM_DEBUG_NOLOCK("client completion callback handler END (lock %p)",
1348                           lock);
1349         LDLM_LOCK_PUT(lock);
1350         EXIT;
1351 }
1352
1353 static void ldlm_handle_gl_callback(struct ptlrpc_request *req,
1354                                     struct ldlm_namespace *ns,
1355                                     struct ldlm_request *dlm_req,
1356                                     struct ldlm_lock *lock)
1357 {
1358         int rc = -ENOSYS;
1359         ENTRY;
1360
1361         LDLM_DEBUG(lock, "client glimpse AST callback handler");
1362
1363         if (lock->l_glimpse_ast != NULL)
1364                 rc = lock->l_glimpse_ast(lock, req);
1365
1366         if (req->rq_repmsg != NULL) {
1367                 ptlrpc_reply(req);
1368         } else {
1369                 req->rq_status = rc;
1370                 ptlrpc_error(req);
1371         }
1372
1373         lock_res_and_lock(lock);
1374         if (lock->l_granted_mode == LCK_PW &&
1375             !lock->l_readers && !lock->l_writers &&
1376             cfs_time_after(cfs_time_current(),
1377                            cfs_time_add(lock->l_last_used,
1378                                         cfs_time_seconds(10)))) {
1379                 unlock_res_and_lock(lock);
1380                 if (ldlm_bl_to_thread_lock(ns, NULL, lock))
1381                         ldlm_handle_bl_callback(ns, NULL, lock);
1382
1383                 EXIT;
1384                 return;
1385         }
1386         unlock_res_and_lock(lock);
1387         LDLM_LOCK_PUT(lock);
1388         EXIT;
1389 }
1390
1391 static int ldlm_callback_reply(struct ptlrpc_request *req, int rc)
1392 {
1393         req->rq_status = rc;
1394         if (req->rq_reply_state == NULL) {
1395                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1396                 if (rc)
1397                         return rc;
1398         }
1399         return ptlrpc_reply(req);
1400 }
1401
1402 #ifdef __KERNEL__
1403 static int ldlm_bl_to_thread(struct ldlm_namespace *ns,
1404                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock,
1405                              struct list_head *cancels, int count)
1406 {
1407         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1408         struct ldlm_bl_work_item *blwi;
1409         ENTRY;
1410
1411         if (cancels && count == 0)
1412                 RETURN(0);
1413
1414         OBD_ALLOC(blwi, sizeof(*blwi));
1415         if (blwi == NULL)
1416                 RETURN(-ENOMEM);
1417
1418         blwi->blwi_ns = ns;
1419         if (ld != NULL)
1420                 blwi->blwi_ld = *ld;
1421         if (count) {
1422                 list_add(&blwi->blwi_head, cancels);
1423                 list_del_init(cancels);
1424                 blwi->blwi_count = count;
1425         } else {
1426                 blwi->blwi_lock = lock;
1427         }
1428         spin_lock(&blp->blp_lock);
1429         list_add_tail(&blwi->blwi_entry, &blp->blp_list);
1430         cfs_waitq_signal(&blp->blp_waitq);
1431         spin_unlock(&blp->blp_lock);
1432
1433         RETURN(0);
1434 }
1435 #endif
1436
1437 int ldlm_bl_to_thread_lock(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1438                            struct ldlm_lock *lock)
1439 {
1440 #ifdef __KERNEL__
1441         RETURN(ldlm_bl_to_thread(ns, ld, lock, NULL, 0));
1442 #else
1443         RETURN(-ENOSYS);
1444 #endif
1445 }
1446
1447 int ldlm_bl_to_thread_list(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1448                            struct list_head *cancels, int count)
1449 {
1450 #ifdef __KERNEL__
1451         RETURN(ldlm_bl_to_thread(ns, ld, NULL, cancels, count));
1452 #else
1453         RETURN(-ENOSYS);
1454 #endif
1455 }
1456
1457 static int ldlm_callback_handler(struct ptlrpc_request *req)
1458 {
1459         struct ldlm_namespace *ns;
1460         struct ldlm_request *dlm_req;
1461         struct ldlm_lock *lock;
1462         int rc;
1463         ENTRY;
1464
1465         /* Requests arrive in sender's byte order.  The ptlrpc service
1466          * handler has already checked and, if necessary, byte-swapped the
1467          * incoming request message body, but I am responsible for the
1468          * message buffers. */
1469
1470         if (req->rq_export == NULL) {
1471                 struct ldlm_request *dlm_req;
1472
1473                 CDEBUG(D_RPCTRACE, "operation %d from %s with bad "
1474                        "export cookie "LPX64"; this is "
1475                        "normal if this node rebooted with a lock held\n",
1476                        lustre_msg_get_opc(req->rq_reqmsg),
1477                        libcfs_id2str(req->rq_peer),
1478                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
1479
1480                 dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF,
1481                                              sizeof(*dlm_req),
1482                                              lustre_swab_ldlm_request);
1483                 if (dlm_req != NULL)
1484                         CDEBUG(D_RPCTRACE, "--> lock cookie: "LPX64"\n",
1485                                dlm_req->lock_handle[0].cookie);
1486
1487                 ldlm_callback_reply(req, -ENOTCONN);
1488                 RETURN(0);
1489         }
1490
1491         LASSERT(req->rq_export != NULL);
1492         LASSERT(req->rq_export->exp_obd != NULL);
1493
1494         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1495         case LDLM_BL_CALLBACK:
1496                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_BL_CALLBACK, 0);
1497                 break;
1498         case LDLM_CP_CALLBACK:
1499                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_CP_CALLBACK, 0);
1500                 break;
1501         case LDLM_GL_CALLBACK:
1502                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_GL_CALLBACK, 0);
1503                 break;
1504         case OBD_LOG_CANCEL: /* remove this eventually - for 1.4.0 compat */
1505                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOG_CANCEL_NET, 0);
1506                 rc = llog_origin_handle_cancel(req);
1507                 ldlm_callback_reply(req, rc);
1508                 RETURN(0);
1509         case OBD_QC_CALLBACK:
1510                 OBD_FAIL_RETURN(OBD_FAIL_OBD_QC_CALLBACK_NET, 0);
1511                 rc = target_handle_qc_callback(req);
1512                 ldlm_callback_reply(req, rc);
1513                 RETURN(0);
1514         case QUOTA_DQACQ:
1515         case QUOTA_DQREL:
1516                 /* reply in handler */
1517                 rc = target_handle_dqacq_callback(req);
1518                 RETURN(0);
1519         case LLOG_ORIGIN_HANDLE_CREATE:
1520                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
1521                 rc = llog_origin_handle_create(req);
1522                 ldlm_callback_reply(req, rc);
1523                 RETURN(0);
1524         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
1525                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
1526                 rc = llog_origin_handle_next_block(req);
1527                 ldlm_callback_reply(req, rc);
1528                 RETURN(0);
1529         case LLOG_ORIGIN_HANDLE_READ_HEADER:
1530                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
1531                 rc = llog_origin_handle_read_header(req);
1532                 ldlm_callback_reply(req, rc);
1533                 RETURN(0);
1534         case LLOG_ORIGIN_HANDLE_CLOSE:
1535                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
1536                 rc = llog_origin_handle_close(req);
1537                 ldlm_callback_reply(req, rc);
1538                 RETURN(0);
1539         case SEC_CTX_FINI:
1540                 /* do nothing */
1541                 RETURN(0);
1542         default:
1543                 CERROR("unknown opcode %u\n",
1544                        lustre_msg_get_opc(req->rq_reqmsg));
1545                 ldlm_callback_reply(req, -EPROTO);
1546                 RETURN(0);
1547         }
1548
1549         ns = req->rq_export->exp_obd->obd_namespace;
1550         LASSERT(ns != NULL);
1551
1552         dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF, sizeof(*dlm_req),
1553                                      lustre_swab_ldlm_request);
1554         if (dlm_req == NULL) {
1555                 CERROR ("can't unpack dlm_req\n");
1556                 ldlm_callback_reply(req, -EPROTO);
1557                 RETURN (0);
1558         }
1559
1560         lock = ldlm_handle2lock_ns(ns, &dlm_req->lock_handle[0]);
1561         if (!lock) {
1562                 CDEBUG(D_DLMTRACE, "callback on lock "LPX64" - lock "
1563                        "disappeared\n", dlm_req->lock_handle[0].cookie);
1564                 ldlm_callback_reply(req, -EINVAL);
1565                 RETURN(0);
1566         }
1567
1568         /* Copy hints/flags (e.g. LDLM_FL_DISCARD_DATA) from AST. */
1569         lock_res_and_lock(lock);
1570         lock->l_flags |= (dlm_req->lock_flags & LDLM_AST_FLAGS);
1571         if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1572                 /* If somebody cancels locks and cache is already droped,
1573                  * we can tell the server we have no lock. Otherwise, we
1574                  * should send cancel after dropping the cache. */
1575                 if ((lock->l_flags & LDLM_FL_CANCELING) &&
1576                     (lock->l_flags & LDLM_FL_BL_DONE)) {
1577                         LDLM_DEBUG(lock, "callback on lock "
1578                                    LPX64" - lock disappeared\n",
1579                                    dlm_req->lock_handle[0].cookie);
1580                         unlock_res_and_lock(lock);
1581                         LDLM_LOCK_PUT(lock);
1582                         ldlm_callback_reply(req, -EINVAL);
1583                         RETURN(0);
1584                 }
1585                 lock->l_flags |= LDLM_FL_BL_AST;
1586         }
1587         unlock_res_and_lock(lock);
1588
1589         /* We want the ost thread to get this reply so that it can respond
1590          * to ost requests (write cache writeback) that might be triggered
1591          * in the callback.
1592          *
1593          * But we'd also like to be able to indicate in the reply that we're
1594          * cancelling right now, because it's unused, or have an intent result
1595          * in the reply, so we might have to push the responsibility for sending
1596          * the reply down into the AST handlers, alas. */
1597
1598         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1599         case LDLM_BL_CALLBACK:
1600                 CDEBUG(D_INODE, "blocking ast\n");
1601                 if (!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK))
1602                         ldlm_callback_reply(req, 0);
1603                 if (ldlm_bl_to_thread_lock(ns, &dlm_req->lock_desc, lock))
1604                         ldlm_handle_bl_callback(ns, &dlm_req->lock_desc, lock);
1605                 break;
1606         case LDLM_CP_CALLBACK:
1607                 CDEBUG(D_INODE, "completion ast\n");
1608                 ldlm_callback_reply(req, 0);
1609                 ldlm_handle_cp_callback(req, ns, dlm_req, lock);
1610                 break;
1611         case LDLM_GL_CALLBACK:
1612                 CDEBUG(D_INODE, "glimpse ast\n");
1613                 ldlm_handle_gl_callback(req, ns, dlm_req, lock);
1614                 break;
1615         default:
1616                 LBUG();                         /* checked above */
1617         }
1618
1619         RETURN(0);
1620 }
1621
1622 static int ldlm_cancel_handler(struct ptlrpc_request *req)
1623 {
1624         int rc;
1625         ENTRY;
1626
1627         /* Requests arrive in sender's byte order.  The ptlrpc service
1628          * handler has already checked and, if necessary, byte-swapped the
1629          * incoming request message body, but I am responsible for the
1630          * message buffers. */
1631
1632         if (req->rq_export == NULL) {
1633                 struct ldlm_request *dlm_req;
1634
1635                 CERROR("operation %d from %s with bad export cookie "LPU64"\n",
1636                        lustre_msg_get_opc(req->rq_reqmsg),
1637                        libcfs_id2str(req->rq_peer),
1638                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
1639
1640                 dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF,
1641                                              sizeof(*dlm_req),
1642                                              lustre_swab_ldlm_request);
1643                 if (dlm_req != NULL)
1644                         ldlm_lock_dump_handle(D_ERROR,
1645                                               &dlm_req->lock_handle[0]);
1646                 ldlm_callback_reply(req, -ENOTCONN);
1647                 RETURN(0);
1648         }
1649
1650         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1651
1652         /* XXX FIXME move this back to mds/handler.c, bug 249 */
1653         case LDLM_CANCEL:
1654                 CDEBUG(D_INODE, "cancel\n");
1655                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_CANCEL, 0);
1656                 rc = ldlm_handle_cancel(req);
1657                 if (rc)
1658                         break;
1659                 RETURN(0);
1660         case OBD_LOG_CANCEL:
1661                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOG_CANCEL_NET, 0);
1662                 rc = llog_origin_handle_cancel(req);
1663                 ldlm_callback_reply(req, rc);
1664                 RETURN(0);
1665         default:
1666                 CERROR("invalid opcode %d\n",
1667                        lustre_msg_get_opc(req->rq_reqmsg));
1668                 ldlm_callback_reply(req, -EINVAL);
1669         }
1670
1671         RETURN(0);
1672 }
1673
1674 void ldlm_revoke_export_locks(struct obd_export *exp)
1675 {
1676         struct list_head *locklist = &exp->exp_ldlm_data.led_held_locks;
1677         struct list_head  rpc_list;
1678         struct ldlm_lock *lock, *next;
1679         struct ldlm_lock_desc desc;
1680
1681         ENTRY;
1682         INIT_LIST_HEAD(&rpc_list);
1683
1684         spin_lock(&exp->exp_ldlm_data.led_lock);
1685         list_for_each_entry_safe(lock, next, locklist, l_export_chain) {
1686                 lock_res_and_lock(lock);
1687
1688                 if (lock->l_req_mode != lock->l_granted_mode) {
1689                         unlock_res_and_lock(lock);
1690                         continue;
1691                 }
1692
1693                 LASSERT(lock->l_resource);
1694                 if (lock->l_resource->lr_type != LDLM_IBITS &&
1695                     lock->l_resource->lr_type != LDLM_PLAIN) {
1696                         unlock_res_and_lock(lock);
1697                         continue;
1698                 }
1699
1700                 if (lock->l_flags & LDLM_FL_AST_SENT) {
1701                         unlock_res_and_lock(lock);
1702                         continue;
1703                 }
1704
1705                 LASSERT(lock->l_blocking_ast);
1706                 LASSERT(!lock->l_blocking_lock);
1707
1708                 lock->l_flags |= LDLM_FL_AST_SENT;
1709                 list_move(&lock->l_export_chain, &rpc_list);
1710
1711                 unlock_res_and_lock(lock);
1712         }
1713         spin_unlock(&exp->exp_ldlm_data.led_lock);
1714
1715         while (!list_empty(&rpc_list)) {
1716                 lock = list_entry(rpc_list.next, struct ldlm_lock,
1717                                   l_export_chain);
1718                 list_del_init(&lock->l_export_chain);
1719
1720                 /* the desc just pretend to exclusive */
1721                 ldlm_lock2desc(lock, &desc);
1722                 desc.l_req_mode = LCK_EX;
1723                 desc.l_granted_mode = 0;
1724
1725                 LDLM_LOCK_GET(lock);
1726                 lock->l_blocking_ast(lock, &desc, lock->l_ast_data,
1727                                      LDLM_CB_BLOCKING);
1728                 LDLM_LOCK_PUT(lock);
1729         }
1730         EXIT;
1731 }
1732
1733 #ifdef __KERNEL__
1734 static struct ldlm_bl_work_item *ldlm_bl_get_work(struct ldlm_bl_pool *blp)
1735 {
1736         struct ldlm_bl_work_item *blwi = NULL;
1737
1738         spin_lock(&blp->blp_lock);
1739         if (!list_empty(&blp->blp_list)) {
1740                 blwi = list_entry(blp->blp_list.next, struct ldlm_bl_work_item,
1741                                   blwi_entry);
1742                 list_del(&blwi->blwi_entry);
1743         }
1744         spin_unlock(&blp->blp_lock);
1745
1746         return blwi;
1747 }
1748
1749 struct ldlm_bl_thread_data {
1750         int                     bltd_num;
1751         struct ldlm_bl_pool     *bltd_blp;
1752 };
1753
1754 static int ldlm_bl_thread_main(void *arg)
1755 {
1756         struct ldlm_bl_thread_data *bltd = arg;
1757         struct ldlm_bl_pool *blp = bltd->bltd_blp;
1758         ENTRY;
1759
1760         {
1761                 char name[CFS_CURPROC_COMM_MAX];
1762                 snprintf(name, sizeof(name) - 1, "ldlm_bl_%02d",
1763                          bltd->bltd_num);
1764                 cfs_daemonize(name);
1765         }
1766
1767         atomic_inc(&blp->blp_num_threads);
1768         complete(&blp->blp_comp);
1769
1770         while(1) {
1771                 struct l_wait_info lwi = { 0 };
1772                 struct ldlm_bl_work_item *blwi = NULL;
1773
1774                 l_wait_event_exclusive(blp->blp_waitq,
1775                                        (blwi = ldlm_bl_get_work(blp)) != NULL,
1776                                        &lwi);
1777
1778                 if (blwi->blwi_ns == NULL)
1779                         break;
1780
1781                 if (blwi->blwi_count) {
1782                         /* The special case when we cancel locks in lru
1783                          * asynchronously, we pass the list of locks here.
1784                          * Thus lock is marked LDLM_FL_CANCELING, and already
1785                          * canceled locally. */
1786                         ldlm_cli_cancel_list(&blwi->blwi_head,
1787                                              blwi->blwi_count, NULL, 0, 0);
1788                 } else {
1789                         ldlm_handle_bl_callback(blwi->blwi_ns, &blwi->blwi_ld,
1790                                                 blwi->blwi_lock);
1791                 }
1792                 OBD_FREE(blwi, sizeof(*blwi));
1793         }
1794
1795         atomic_dec(&blp->blp_num_threads);
1796         complete(&blp->blp_comp);
1797         RETURN(0);
1798 }
1799
1800 #endif
1801
1802 static int ldlm_setup(void);
1803 static int ldlm_cleanup(int force);
1804
1805 int ldlm_get_ref(void)
1806 {
1807         int rc = 0;
1808         ENTRY;
1809         mutex_down(&ldlm_ref_sem);
1810         if (++ldlm_refcount == 1) {
1811                 rc = ldlm_setup();
1812                 if (rc)
1813                         ldlm_refcount--;
1814         }
1815         mutex_up(&ldlm_ref_sem);
1816
1817         RETURN(rc);
1818 }
1819
1820 void ldlm_put_ref(int force)
1821 {
1822         ENTRY;
1823         mutex_down(&ldlm_ref_sem);
1824         if (ldlm_refcount == 1) {
1825                 int rc = ldlm_cleanup(force);
1826                 if (rc)
1827                         CERROR("ldlm_cleanup failed: %d\n", rc);
1828                 else
1829                         ldlm_refcount--;
1830         } else {
1831                 ldlm_refcount--;
1832         }
1833         mutex_up(&ldlm_ref_sem);
1834
1835         EXIT;
1836 }
1837
1838 static int ldlm_setup(void)
1839 {
1840         struct ldlm_bl_pool *blp;
1841         int rc = 0;
1842 #ifdef __KERNEL__
1843         int i;
1844 #endif
1845         ENTRY;
1846
1847         if (ldlm_state != NULL)
1848                 RETURN(-EALREADY);
1849
1850         OBD_ALLOC(ldlm_state, sizeof(*ldlm_state));
1851         if (ldlm_state == NULL)
1852                 RETURN(-ENOMEM);
1853
1854 #ifdef LPROCFS
1855         rc = ldlm_proc_setup();
1856         if (rc != 0)
1857                 GOTO(out_free, rc);
1858 #endif
1859
1860         ldlm_state->ldlm_cb_service =
1861                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
1862                                 LDLM_MAXREPSIZE, LDLM_CB_REQUEST_PORTAL,
1863                                 LDLM_CB_REPLY_PORTAL, ldlm_timeout * 900,
1864                                 ldlm_callback_handler, "ldlm_cbd",
1865                                 ldlm_svc_proc_dir, NULL,
1866                                 LDLM_THREADS_AUTO_MIN, LDLM_THREADS_AUTO_MAX,
1867                                 "ldlm_cb",
1868                                 LCT_MD_THREAD|LCT_DT_THREAD);
1869
1870         if (!ldlm_state->ldlm_cb_service) {
1871                 CERROR("failed to start service\n");
1872                 GOTO(out_proc, rc = -ENOMEM);
1873         }
1874
1875         ldlm_state->ldlm_cancel_service =
1876                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
1877                                 LDLM_MAXREPSIZE, LDLM_CANCEL_REQUEST_PORTAL,
1878                                 LDLM_CANCEL_REPLY_PORTAL, ldlm_timeout * 6000,
1879                                 ldlm_cancel_handler, "ldlm_canceld",
1880                                 ldlm_svc_proc_dir, NULL,
1881                                 LDLM_THREADS_AUTO_MIN, LDLM_THREADS_AUTO_MAX,
1882                                 "ldlm_cn",
1883                                 LCT_MD_THREAD|LCT_DT_THREAD|LCT_CL_THREAD);
1884
1885         if (!ldlm_state->ldlm_cancel_service) {
1886                 CERROR("failed to start service\n");
1887                 GOTO(out_proc, rc = -ENOMEM);
1888         }
1889
1890         OBD_ALLOC(blp, sizeof(*blp));
1891         if (blp == NULL)
1892                 GOTO(out_proc, rc = -ENOMEM);
1893         ldlm_state->ldlm_bl_pool = blp;
1894
1895         atomic_set(&blp->blp_num_threads, 0);
1896         cfs_waitq_init(&blp->blp_waitq);
1897         spin_lock_init(&blp->blp_lock);
1898
1899         CFS_INIT_LIST_HEAD(&blp->blp_list);
1900
1901 #ifdef __KERNEL__
1902         for (i = 0; i < LDLM_BL_THREADS; i++) {
1903                 struct ldlm_bl_thread_data bltd = {
1904                         .bltd_num = i,
1905                         .bltd_blp = blp,
1906                 };
1907                 init_completion(&blp->blp_comp);
1908                 rc = cfs_kernel_thread(ldlm_bl_thread_main, &bltd, 0);
1909                 if (rc < 0) {
1910                         CERROR("cannot start LDLM thread #%d: rc %d\n", i, rc);
1911                         GOTO(out_thread, rc);
1912                 }
1913                 wait_for_completion(&blp->blp_comp);
1914         }
1915
1916         rc = ptlrpc_start_threads(NULL, ldlm_state->ldlm_cancel_service);
1917         if (rc)
1918                 GOTO(out_thread, rc);
1919
1920         rc = ptlrpc_start_threads(NULL, ldlm_state->ldlm_cb_service);
1921         if (rc)
1922                 GOTO(out_thread, rc);
1923
1924         CFS_INIT_LIST_HEAD(&expired_lock_thread.elt_expired_locks);
1925         expired_lock_thread.elt_state = ELT_STOPPED;
1926         cfs_waitq_init(&expired_lock_thread.elt_waitq);
1927
1928         CFS_INIT_LIST_HEAD(&waiting_locks_list);
1929         spin_lock_init(&waiting_locks_spinlock);
1930         cfs_timer_init(&waiting_locks_timer, waiting_locks_callback, 0);
1931
1932         rc = cfs_kernel_thread(expired_lock_main, NULL, CLONE_VM | CLONE_FILES);
1933         if (rc < 0) {
1934                 CERROR("Cannot start ldlm expired-lock thread: %d\n", rc);
1935                 GOTO(out_thread, rc);
1936         }
1937
1938         wait_event(expired_lock_thread.elt_waitq,
1939                    expired_lock_thread.elt_state == ELT_READY);
1940 #endif
1941
1942 #ifdef __KERNEL__
1943         rc = ldlm_pools_init();
1944         if (rc)
1945                 GOTO(out_thread, rc);
1946 #endif
1947         RETURN(0);
1948
1949 #ifdef __KERNEL__
1950  out_thread:
1951         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
1952         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
1953 #endif
1954
1955  out_proc:
1956 #ifdef LPROCFS
1957         ldlm_proc_cleanup();
1958  out_free:
1959 #endif
1960         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
1961         ldlm_state = NULL;
1962         return rc;
1963 }
1964
1965 static int ldlm_cleanup(int force)
1966 {
1967 #ifdef __KERNEL__
1968         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1969 #endif
1970         ENTRY;
1971
1972         if (!list_empty(ldlm_namespace_list(LDLM_NAMESPACE_SERVER)) || 
1973             !list_empty(ldlm_namespace_list(LDLM_NAMESPACE_CLIENT))) {
1974                 CERROR("ldlm still has namespaces; clean these up first.\n");
1975                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
1976                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
1977                 RETURN(-EBUSY);
1978         }
1979
1980 #ifdef __KERNEL__
1981         ldlm_pools_fini();
1982 #endif
1983
1984 #ifdef __KERNEL__
1985         while (atomic_read(&blp->blp_num_threads) > 0) {
1986                 struct ldlm_bl_work_item blwi = { .blwi_ns = NULL };
1987
1988                 init_completion(&blp->blp_comp);
1989
1990                 spin_lock(&blp->blp_lock);
1991                 list_add_tail(&blwi.blwi_entry, &blp->blp_list);
1992                 cfs_waitq_signal(&blp->blp_waitq);
1993                 spin_unlock(&blp->blp_lock);
1994
1995                 wait_for_completion(&blp->blp_comp);
1996         }
1997         OBD_FREE(blp, sizeof(*blp));
1998
1999         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2000         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2001         ldlm_proc_cleanup();
2002
2003         expired_lock_thread.elt_state = ELT_TERMINATE;
2004         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
2005         wait_event(expired_lock_thread.elt_waitq,
2006                    expired_lock_thread.elt_state == ELT_STOPPED);
2007 #else
2008         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2009         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2010 #endif
2011
2012         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
2013         ldlm_state = NULL;
2014
2015         RETURN(0);
2016 }
2017
2018 int __init ldlm_init(void)
2019 {
2020         init_mutex(&ldlm_ref_sem);
2021         init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_SERVER));
2022         init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
2023         ldlm_resource_slab = cfs_mem_cache_create("ldlm_resources",
2024                                                sizeof(struct ldlm_resource), 0,
2025                                                SLAB_HWCACHE_ALIGN);
2026         if (ldlm_resource_slab == NULL)
2027                 return -ENOMEM;
2028
2029         ldlm_lock_slab = cfs_mem_cache_create("ldlm_locks",
2030                                            sizeof(struct ldlm_lock), 0,
2031                                            SLAB_HWCACHE_ALIGN);
2032         if (ldlm_lock_slab == NULL) {
2033                 cfs_mem_cache_destroy(ldlm_resource_slab);
2034                 return -ENOMEM;
2035         }
2036
2037         return 0;
2038 }
2039
2040 void __exit ldlm_exit(void)
2041 {
2042         int rc;
2043         if (ldlm_refcount)
2044                 CERROR("ldlm_refcount is %d in ldlm_exit!\n", ldlm_refcount);
2045         rc = cfs_mem_cache_destroy(ldlm_resource_slab);
2046         LASSERTF(rc == 0, "couldn't free ldlm resource slab\n");
2047         rc = cfs_mem_cache_destroy(ldlm_lock_slab);
2048         LASSERTF(rc == 0, "couldn't free ldlm lock slab\n");
2049 }
2050
2051 /* ldlm_extent.c */
2052 EXPORT_SYMBOL(ldlm_extent_shift_kms);
2053
2054 /* ldlm_lock.c */
2055 EXPORT_SYMBOL(ldlm_get_processing_policy);
2056 EXPORT_SYMBOL(ldlm_lock2desc);
2057 EXPORT_SYMBOL(ldlm_register_intent);
2058 EXPORT_SYMBOL(ldlm_lockname);
2059 EXPORT_SYMBOL(ldlm_typename);
2060 EXPORT_SYMBOL(ldlm_lock2handle);
2061 EXPORT_SYMBOL(__ldlm_handle2lock);
2062 EXPORT_SYMBOL(ldlm_lock_get);
2063 EXPORT_SYMBOL(ldlm_lock_put);
2064 EXPORT_SYMBOL(ldlm_lock_match);
2065 EXPORT_SYMBOL(ldlm_lock_cancel);
2066 EXPORT_SYMBOL(ldlm_lock_addref);
2067 EXPORT_SYMBOL(ldlm_lock_decref);
2068 EXPORT_SYMBOL(ldlm_lock_decref_and_cancel);
2069 EXPORT_SYMBOL(ldlm_lock_change_resource);
2070 EXPORT_SYMBOL(ldlm_lock_set_data);
2071 EXPORT_SYMBOL(ldlm_it2str);
2072 EXPORT_SYMBOL(ldlm_lock_dump);
2073 EXPORT_SYMBOL(ldlm_lock_dump_handle);
2074 EXPORT_SYMBOL(ldlm_cancel_locks_for_export);
2075 EXPORT_SYMBOL(ldlm_reprocess_all_ns);
2076 EXPORT_SYMBOL(ldlm_lock_allow_match);
2077
2078 /* ldlm_request.c */
2079 EXPORT_SYMBOL(ldlm_completion_ast);
2080 EXPORT_SYMBOL(ldlm_blocking_ast);
2081 EXPORT_SYMBOL(ldlm_glimpse_ast);
2082 EXPORT_SYMBOL(ldlm_expired_completion_wait);
2083 EXPORT_SYMBOL(ldlm_prep_enqueue_req);
2084 EXPORT_SYMBOL(ldlm_cli_convert);
2085 EXPORT_SYMBOL(ldlm_cli_enqueue);
2086 EXPORT_SYMBOL(ldlm_cli_enqueue_fini);
2087 EXPORT_SYMBOL(ldlm_cli_enqueue_local);
2088 EXPORT_SYMBOL(ldlm_cli_cancel);
2089 EXPORT_SYMBOL(ldlm_cli_cancel_unused);
2090 EXPORT_SYMBOL(ldlm_cli_cancel_unused_resource);
2091 EXPORT_SYMBOL(ldlm_cli_cancel_req);
2092 EXPORT_SYMBOL(ldlm_cli_join_lru);
2093 EXPORT_SYMBOL(ldlm_replay_locks);
2094 EXPORT_SYMBOL(ldlm_resource_foreach);
2095 EXPORT_SYMBOL(ldlm_namespace_foreach);
2096 EXPORT_SYMBOL(ldlm_namespace_foreach_res);
2097 EXPORT_SYMBOL(ldlm_resource_iterate);
2098 EXPORT_SYMBOL(ldlm_cancel_resource_local);
2099 EXPORT_SYMBOL(ldlm_cli_cancel_list);
2100
2101 /* ldlm_lockd.c */
2102 EXPORT_SYMBOL(ldlm_server_blocking_ast);
2103 EXPORT_SYMBOL(ldlm_server_completion_ast);
2104 EXPORT_SYMBOL(ldlm_server_glimpse_ast);
2105 EXPORT_SYMBOL(ldlm_handle_enqueue);
2106 EXPORT_SYMBOL(ldlm_handle_enqueue0);
2107 EXPORT_SYMBOL(ldlm_handle_cancel);
2108 EXPORT_SYMBOL(ldlm_request_cancel);
2109 EXPORT_SYMBOL(ldlm_handle_convert);
2110 EXPORT_SYMBOL(ldlm_handle_convert0);
2111 EXPORT_SYMBOL(ldlm_del_waiting_lock);
2112 EXPORT_SYMBOL(ldlm_get_ref);
2113 EXPORT_SYMBOL(ldlm_put_ref);
2114 EXPORT_SYMBOL(ldlm_refresh_waiting_lock);
2115 EXPORT_SYMBOL(ldlm_revoke_export_locks);
2116
2117 /* ldlm_resource.c */
2118 EXPORT_SYMBOL(ldlm_namespace_new);
2119 EXPORT_SYMBOL(ldlm_namespace_cleanup);
2120 EXPORT_SYMBOL(ldlm_namespace_free);
2121 EXPORT_SYMBOL(ldlm_namespace_dump);
2122 EXPORT_SYMBOL(ldlm_dump_all_namespaces);
2123 EXPORT_SYMBOL(ldlm_resource_get);
2124 EXPORT_SYMBOL(ldlm_resource_putref);
2125 EXPORT_SYMBOL(ldlm_resource_unlink_lock);
2126
2127 /* ldlm_lib.c */
2128 EXPORT_SYMBOL(client_import_add_conn);
2129 EXPORT_SYMBOL(client_import_del_conn);
2130 EXPORT_SYMBOL(client_obd_setup);
2131 EXPORT_SYMBOL(client_obd_cleanup);
2132 EXPORT_SYMBOL(client_connect_import);
2133 EXPORT_SYMBOL(client_disconnect_export);
2134 EXPORT_SYMBOL(target_start_recovery_thread);
2135 EXPORT_SYMBOL(target_stop_recovery_thread);
2136 EXPORT_SYMBOL(target_handle_connect);
2137 EXPORT_SYMBOL(target_cleanup_recovery);
2138 EXPORT_SYMBOL(target_destroy_export);
2139 EXPORT_SYMBOL(target_cancel_recovery_timer);
2140 EXPORT_SYMBOL(target_send_reply);
2141 EXPORT_SYMBOL(target_queue_recovery_request);
2142 EXPORT_SYMBOL(target_handle_ping);
2143 EXPORT_SYMBOL(target_pack_pool_reply);
2144 EXPORT_SYMBOL(target_handle_disconnect);
2145
2146 /* l_lock.c */
2147 EXPORT_SYMBOL(lock_res_and_lock);
2148 EXPORT_SYMBOL(unlock_res_and_lock);
2149