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