Whamcloud - gitweb
b=22244 handle list of locks in ldlm_bl_thread_main properly
[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 (c) 2002, 2010, Oracle and/or its affiliates. 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_bl_work_item *blwi, int mode)
1638 {
1639         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1640         ENTRY;
1641
1642         cfs_spin_lock(&blp->blp_lock);
1643         if (blwi->blwi_lock && blwi->blwi_lock->l_flags & LDLM_FL_DISCARD_DATA) {
1644                 /* add LDLM_FL_DISCARD_DATA requests to the priority list */
1645                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_prio_list);
1646         } else {
1647                 /* other blocking callbacks are added to the regular list */
1648                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_list);
1649         }
1650         cfs_spin_unlock(&blp->blp_lock);
1651
1652         cfs_waitq_signal(&blp->blp_waitq);
1653         if (mode == LDLM_SYNC)
1654                 /* keep ref count as object is on this stack for SYNC call */
1655                 cfs_wait_for_completion(&blwi->blwi_comp);
1656
1657         RETURN(0);
1658 }
1659
1660 static inline void init_blwi(struct ldlm_bl_work_item *blwi,
1661                              struct ldlm_namespace *ns,
1662                              struct ldlm_lock_desc *ld,
1663                              cfs_list_t *cancels, int count,
1664                              struct ldlm_lock *lock)
1665 {
1666         cfs_init_completion(&blwi->blwi_comp);
1667         /* set ref count to 1 initially, supposed to be released in
1668          * ldlm_bl_thread_main(), if not allocated on the stack */
1669         cfs_atomic_set(&blwi->blwi_ref_count, 1);
1670         CFS_INIT_LIST_HEAD(&blwi->blwi_head);
1671
1672         blwi->blwi_ns = ns;
1673         if (ld != NULL)
1674                 blwi->blwi_ld = *ld;
1675         if (count) {
1676                 cfs_list_add(&blwi->blwi_head, cancels);
1677                 cfs_list_del_init(cancels);
1678                 blwi->blwi_count = count;
1679         } else {
1680                 blwi->blwi_lock = lock;
1681         }
1682 }
1683
1684 static int ldlm_bl_to_thread(struct ldlm_namespace *ns,
1685                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock,
1686                              cfs_list_t *cancels, int count, int mode)
1687 {
1688         ENTRY;
1689
1690         if (cancels && count == 0)
1691                 RETURN(0);
1692
1693         if (mode == LDLM_SYNC) {
1694                 /* if it is synchronous call do minimum mem alloc, as it could
1695                  * be triggered from kernel shrinker
1696                  */
1697                 struct ldlm_bl_work_item blwi;
1698                 memset(&blwi, 0, sizeof(blwi));
1699                 init_blwi(&blwi, ns, ld, cancels, count, lock);
1700                 /* take extra ref as this obj is on stack */
1701                 ldlm_bl_work_item_get(&blwi);
1702                 RETURN(__ldlm_bl_to_thread(&blwi, mode));
1703         } else {
1704                 struct ldlm_bl_work_item *blwi;
1705                 OBD_ALLOC(blwi, sizeof(*blwi));
1706                 if (blwi == NULL)
1707                         RETURN(-ENOMEM);
1708                 init_blwi(blwi, ns, ld, cancels, count, lock);
1709
1710                 RETURN(__ldlm_bl_to_thread(blwi, mode));
1711         }
1712 }
1713
1714 #endif
1715
1716 int ldlm_bl_to_thread_lock(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1717                            struct ldlm_lock *lock)
1718 {
1719 #ifdef __KERNEL__
1720         RETURN(ldlm_bl_to_thread(ns, ld, lock, NULL, 0, LDLM_ASYNC));
1721 #else
1722         RETURN(-ENOSYS);
1723 #endif
1724 }
1725
1726 int ldlm_bl_to_thread_list(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1727                            cfs_list_t *cancels, int count, int mode)
1728 {
1729 #ifdef __KERNEL__
1730         RETURN(ldlm_bl_to_thread(ns, ld, NULL, cancels, count, mode));
1731 #else
1732         RETURN(-ENOSYS);
1733 #endif
1734 }
1735
1736 /* Setinfo coming from Server (eg MDT) to Client (eg MDC)! */
1737 static int ldlm_handle_setinfo(struct ptlrpc_request *req)
1738 {
1739         struct obd_device *obd = req->rq_export->exp_obd;
1740         char *key;
1741         void *val;
1742         int keylen, vallen;
1743         int rc = -ENOSYS;
1744         ENTRY;
1745
1746         DEBUG_REQ(D_HSM, req, "%s: handle setinfo\n", obd->obd_name);
1747
1748         req_capsule_set(&req->rq_pill, &RQF_OBD_SET_INFO);
1749
1750         key = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_KEY);
1751         if (key == NULL) {
1752                 DEBUG_REQ(D_IOCTL, req, "no set_info key");
1753                 RETURN(-EFAULT);
1754         }
1755         keylen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_KEY,
1756                                       RCL_CLIENT);
1757         val = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_VAL);
1758         if (val == NULL) {
1759                 DEBUG_REQ(D_IOCTL, req, "no set_info val");
1760                 RETURN(-EFAULT);
1761         }
1762         vallen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_VAL,
1763                                       RCL_CLIENT);
1764
1765         /* We are responsible for swabbing contents of val */
1766
1767         if (KEY_IS(KEY_HSM_COPYTOOL_SEND))
1768                 /* Pass it on to mdc (the "export" in this case) */
1769                 rc = obd_set_info_async(req->rq_export,
1770                                         sizeof(KEY_HSM_COPYTOOL_SEND),
1771                                         KEY_HSM_COPYTOOL_SEND,
1772                                         vallen, val, NULL);
1773         else
1774                 DEBUG_REQ(D_WARNING, req, "ignoring unknown key %s", key);
1775
1776         return rc;
1777 }
1778
1779 static inline void ldlm_callback_errmsg(struct ptlrpc_request *req,
1780                                         const char *msg, int rc,
1781                                         struct lustre_handle *handle)
1782 {
1783         DEBUG_REQ((req->rq_no_reply || rc) ? D_WARNING : D_DLMTRACE, req,
1784                   "%s: [nid %s] [rc %d] [lock "LPX64"]",
1785                   msg, libcfs_id2str(req->rq_peer), rc,
1786                   handle ? handle->cookie : 0);
1787         if (req->rq_no_reply)
1788                 CWARN("No reply was sent, maybe cause bug 21636.\n");
1789         else if (rc)
1790                 CWARN("Send reply failed, maybe cause bug 21636.\n");
1791 }
1792
1793 /* TODO: handle requests in a similar way as MDT: see mdt_handle_common() */
1794 static int ldlm_callback_handler(struct ptlrpc_request *req)
1795 {
1796         struct ldlm_namespace *ns;
1797         struct ldlm_request *dlm_req;
1798         struct ldlm_lock *lock;
1799         int rc;
1800         ENTRY;
1801
1802         /* Requests arrive in sender's byte order.  The ptlrpc service
1803          * handler has already checked and, if necessary, byte-swapped the
1804          * incoming request message body, but I am responsible for the
1805          * message buffers. */
1806
1807         /* do nothing for sec context finalize */
1808         if (lustre_msg_get_opc(req->rq_reqmsg) == SEC_CTX_FINI)
1809                 RETURN(0);
1810
1811         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
1812
1813         if (req->rq_export == NULL) {
1814                 rc = ldlm_callback_reply(req, -ENOTCONN);
1815                 ldlm_callback_errmsg(req, "Operate on unconnected server",
1816                                      rc, NULL);
1817                 RETURN(0);
1818         }
1819
1820         LASSERT(req->rq_export != NULL);
1821         LASSERT(req->rq_export->exp_obd != NULL);
1822
1823         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1824         case LDLM_BL_CALLBACK:
1825                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_BL_CALLBACK))
1826                         RETURN(0);
1827                 break;
1828         case LDLM_CP_CALLBACK:
1829                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CP_CALLBACK))
1830                         RETURN(0);
1831                 break;
1832         case LDLM_GL_CALLBACK:
1833                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_GL_CALLBACK))
1834                         RETURN(0);
1835                 break;
1836         case LDLM_SET_INFO:
1837                 rc = ldlm_handle_setinfo(req);
1838                 ldlm_callback_reply(req, rc);
1839                 RETURN(0);
1840         case OBD_LOG_CANCEL: /* remove this eventually - for 1.4.0 compat */
1841                 CERROR("shouldn't be handling OBD_LOG_CANCEL on DLM thread\n");
1842                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
1843                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
1844                         RETURN(0);
1845                 rc = llog_origin_handle_cancel(req);
1846                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
1847                         RETURN(0);
1848                 ldlm_callback_reply(req, rc);
1849                 RETURN(0);
1850         case OBD_QC_CALLBACK:
1851                 req_capsule_set(&req->rq_pill, &RQF_QC_CALLBACK);
1852                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_QC_CALLBACK_NET))
1853                         RETURN(0);
1854                 rc = target_handle_qc_callback(req);
1855                 ldlm_callback_reply(req, rc);
1856                 RETURN(0);
1857         case QUOTA_DQACQ:
1858         case QUOTA_DQREL:
1859                 /* reply in handler */
1860                 req_capsule_set(&req->rq_pill, &RQF_MDS_QUOTA_DQACQ);
1861                 rc = target_handle_dqacq_callback(req);
1862                 RETURN(0);
1863         case LLOG_ORIGIN_HANDLE_CREATE:
1864                 req_capsule_set(&req->rq_pill, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
1865                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1866                         RETURN(0);
1867                 rc = llog_origin_handle_create(req);
1868                 ldlm_callback_reply(req, rc);
1869                 RETURN(0);
1870         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
1871                 req_capsule_set(&req->rq_pill,
1872                                 &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
1873                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1874                         RETURN(0);
1875                 rc = llog_origin_handle_next_block(req);
1876                 ldlm_callback_reply(req, rc);
1877                 RETURN(0);
1878         case LLOG_ORIGIN_HANDLE_READ_HEADER:
1879                 req_capsule_set(&req->rq_pill,
1880                                 &RQF_LLOG_ORIGIN_HANDLE_READ_HEADER);
1881                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1882                         RETURN(0);
1883                 rc = llog_origin_handle_read_header(req);
1884                 ldlm_callback_reply(req, rc);
1885                 RETURN(0);
1886         case LLOG_ORIGIN_HANDLE_CLOSE:
1887                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1888                         RETURN(0);
1889                 rc = llog_origin_handle_close(req);
1890                 ldlm_callback_reply(req, rc);
1891                 RETURN(0);
1892         default:
1893                 CERROR("unknown opcode %u\n",
1894                        lustre_msg_get_opc(req->rq_reqmsg));
1895                 ldlm_callback_reply(req, -EPROTO);
1896                 RETURN(0);
1897         }
1898
1899         ns = req->rq_export->exp_obd->obd_namespace;
1900         LASSERT(ns != NULL);
1901
1902         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
1903
1904         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1905         if (dlm_req == NULL) {
1906                 rc = ldlm_callback_reply(req, -EPROTO);
1907                 ldlm_callback_errmsg(req, "Operate without parameter", rc,
1908                                      NULL);
1909                 RETURN(0);
1910         }
1911
1912         /* Force a known safe race, send a cancel to the server for a lock
1913          * which the server has already started a blocking callback on. */
1914         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE) &&
1915             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1916                 rc = ldlm_cli_cancel(&dlm_req->lock_handle[0]);
1917                 if (rc < 0)
1918                         CERROR("ldlm_cli_cancel: %d\n", rc);
1919         }
1920
1921         lock = ldlm_handle2lock_long(&dlm_req->lock_handle[0], 0);
1922         if (!lock) {
1923                 CDEBUG(D_DLMTRACE, "callback on lock "LPX64" - lock "
1924                        "disappeared\n", dlm_req->lock_handle[0].cookie);
1925                 rc = ldlm_callback_reply(req, -EINVAL);
1926                 ldlm_callback_errmsg(req, "Operate with invalid parameter", rc,
1927                                      &dlm_req->lock_handle[0]);
1928                 RETURN(0);
1929         }
1930
1931         if ((lock->l_flags & LDLM_FL_FAIL_LOC) &&
1932             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK)
1933                 OBD_RACE(OBD_FAIL_LDLM_CP_BL_RACE);
1934
1935         /* Copy hints/flags (e.g. LDLM_FL_DISCARD_DATA) from AST. */
1936         lock_res_and_lock(lock);
1937         lock->l_flags |= (dlm_req->lock_flags & LDLM_AST_FLAGS);
1938         if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1939                 /* If somebody cancels lock and cache is already dropped,
1940                  * or lock is failed before cp_ast received on client,
1941                  * we can tell the server we have no lock. Otherwise, we
1942                  * should send cancel after dropping the cache. */
1943                 if (((lock->l_flags & LDLM_FL_CANCELING) &&
1944                     (lock->l_flags & LDLM_FL_BL_DONE)) ||
1945                     (lock->l_flags & LDLM_FL_FAILED)) {
1946                         LDLM_DEBUG(lock, "callback on lock "
1947                                    LPX64" - lock disappeared\n",
1948                                    dlm_req->lock_handle[0].cookie);
1949                         unlock_res_and_lock(lock);
1950                         LDLM_LOCK_RELEASE(lock);
1951                         rc = ldlm_callback_reply(req, -EINVAL);
1952                         ldlm_callback_errmsg(req, "Operate on stale lock", rc,
1953                                              &dlm_req->lock_handle[0]);
1954                         RETURN(0);
1955                 }
1956                 /* BL_AST locks are not needed in lru.
1957                  * let ldlm_cancel_lru() be fast. */
1958                 ldlm_lock_remove_from_lru(lock);
1959                 lock->l_flags |= LDLM_FL_BL_AST;
1960         }
1961         unlock_res_and_lock(lock);
1962
1963         /* We want the ost thread to get this reply so that it can respond
1964          * to ost requests (write cache writeback) that might be triggered
1965          * in the callback.
1966          *
1967          * But we'd also like to be able to indicate in the reply that we're
1968          * cancelling right now, because it's unused, or have an intent result
1969          * in the reply, so we might have to push the responsibility for sending
1970          * the reply down into the AST handlers, alas. */
1971
1972         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1973         case LDLM_BL_CALLBACK:
1974                 CDEBUG(D_INODE, "blocking ast\n");
1975                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_BL_CALLBACK);
1976                 if (!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)) {
1977                         rc = ldlm_callback_reply(req, 0);
1978                         if (req->rq_no_reply || rc)
1979                                 ldlm_callback_errmsg(req, "Normal process", rc,
1980                                                      &dlm_req->lock_handle[0]);
1981                 }
1982                 if (ldlm_bl_to_thread_lock(ns, &dlm_req->lock_desc, lock))
1983                         ldlm_handle_bl_callback(ns, &dlm_req->lock_desc, lock);
1984                 break;
1985         case LDLM_CP_CALLBACK:
1986                 CDEBUG(D_INODE, "completion ast\n");
1987                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_CP_CALLBACK);
1988                 ldlm_callback_reply(req, 0);
1989                 ldlm_handle_cp_callback(req, ns, dlm_req, lock);
1990                 break;
1991         case LDLM_GL_CALLBACK:
1992                 CDEBUG(D_INODE, "glimpse ast\n");
1993                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_GL_CALLBACK);
1994                 ldlm_handle_gl_callback(req, ns, dlm_req, lock);
1995                 break;
1996         default:
1997                 LBUG();                         /* checked above */
1998         }
1999
2000         RETURN(0);
2001 }
2002
2003 static int ldlm_cancel_handler(struct ptlrpc_request *req)
2004 {
2005         int rc;
2006         ENTRY;
2007
2008         /* Requests arrive in sender's byte order.  The ptlrpc service
2009          * handler has already checked and, if necessary, byte-swapped the
2010          * incoming request message body, but I am responsible for the
2011          * message buffers. */
2012
2013         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2014
2015         if (req->rq_export == NULL) {
2016                 struct ldlm_request *dlm_req;
2017
2018                 CERROR("operation %d from %s with bad export cookie "LPU64"\n",
2019                        lustre_msg_get_opc(req->rq_reqmsg),
2020                        libcfs_id2str(req->rq_peer),
2021                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
2022
2023                 if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_CANCEL) {
2024                         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2025                         dlm_req = req_capsule_client_get(&req->rq_pill,
2026                                                          &RMF_DLM_REQ);
2027                         if (dlm_req != NULL)
2028                                 ldlm_lock_dump_handle(D_ERROR,
2029                                                       &dlm_req->lock_handle[0]);
2030                 }
2031                 ldlm_callback_reply(req, -ENOTCONN);
2032                 RETURN(0);
2033         }
2034
2035         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2036
2037         /* XXX FIXME move this back to mds/handler.c, bug 249 */
2038         case LDLM_CANCEL:
2039                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CANCEL);
2040                 CDEBUG(D_INODE, "cancel\n");
2041                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL))
2042                         RETURN(0);
2043                 rc = ldlm_handle_cancel(req);
2044                 if (rc)
2045                         break;
2046                 RETURN(0);
2047         case OBD_LOG_CANCEL:
2048                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
2049                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
2050                         RETURN(0);
2051                 rc = llog_origin_handle_cancel(req);
2052                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
2053                         RETURN(0);
2054                 ldlm_callback_reply(req, rc);
2055                 RETURN(0);
2056         default:
2057                 CERROR("invalid opcode %d\n",
2058                        lustre_msg_get_opc(req->rq_reqmsg));
2059                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2060                 ldlm_callback_reply(req, -EINVAL);
2061         }
2062
2063         RETURN(0);
2064 }
2065
2066 void ldlm_revoke_lock_cb(void *obj, void *data)
2067 {
2068         cfs_list_t         *rpc_list = data;
2069         struct ldlm_lock   *lock = obj;
2070
2071         lock_res_and_lock(lock);
2072
2073         if (lock->l_req_mode != lock->l_granted_mode) {
2074                 unlock_res_and_lock(lock);
2075                 return;
2076         }
2077
2078         LASSERT(lock->l_resource);
2079         if (lock->l_resource->lr_type != LDLM_IBITS &&
2080             lock->l_resource->lr_type != LDLM_PLAIN) {
2081                 unlock_res_and_lock(lock);
2082                 return;
2083         }
2084
2085         if (lock->l_flags & LDLM_FL_AST_SENT) {
2086                 unlock_res_and_lock(lock);
2087                 return;
2088         }
2089
2090         LASSERT(lock->l_blocking_ast);
2091         LASSERT(!lock->l_blocking_lock);
2092
2093         lock->l_flags |= LDLM_FL_AST_SENT;
2094         if (lock->l_export && lock->l_export->exp_lock_hash &&
2095             !cfs_hlist_unhashed(&lock->l_exp_hash))
2096                 cfs_hash_del(lock->l_export->exp_lock_hash,
2097                              &lock->l_remote_handle, &lock->l_exp_hash);
2098         cfs_list_add_tail(&lock->l_rk_ast, rpc_list);
2099         LDLM_LOCK_GET(lock);
2100
2101         unlock_res_and_lock(lock);
2102 }
2103
2104 void ldlm_revoke_export_locks(struct obd_export *exp)
2105 {
2106         cfs_list_t  rpc_list;
2107         ENTRY;
2108
2109         CFS_INIT_LIST_HEAD(&rpc_list);
2110         cfs_hash_for_each_empty(exp->exp_lock_hash,
2111                                 ldlm_revoke_lock_cb, &rpc_list);
2112         ldlm_run_ast_work(&rpc_list, LDLM_WORK_REVOKE_AST);
2113
2114         EXIT;
2115 }
2116
2117 #ifdef __KERNEL__
2118 static struct ldlm_bl_work_item *ldlm_bl_get_work(struct ldlm_bl_pool *blp)
2119 {
2120         struct ldlm_bl_work_item *blwi = NULL;
2121         static unsigned int num_bl = 0;
2122
2123         cfs_spin_lock(&blp->blp_lock);
2124         /* process a request from the blp_list at least every blp_num_threads */
2125         if (!cfs_list_empty(&blp->blp_list) &&
2126             (cfs_list_empty(&blp->blp_prio_list) || num_bl == 0))
2127                 blwi = cfs_list_entry(blp->blp_list.next,
2128                                       struct ldlm_bl_work_item, blwi_entry);
2129         else
2130                 if (!cfs_list_empty(&blp->blp_prio_list))
2131                         blwi = cfs_list_entry(blp->blp_prio_list.next,
2132                                               struct ldlm_bl_work_item,
2133                                               blwi_entry);
2134
2135         if (blwi) {
2136                 if (++num_bl >= cfs_atomic_read(&blp->blp_num_threads))
2137                         num_bl = 0;
2138                 cfs_list_del(&blwi->blwi_entry);
2139         }
2140         cfs_spin_unlock(&blp->blp_lock);
2141
2142         return blwi;
2143 }
2144
2145 /* This only contains temporary data until the thread starts */
2146 struct ldlm_bl_thread_data {
2147         char                    bltd_name[CFS_CURPROC_COMM_MAX];
2148         struct ldlm_bl_pool     *bltd_blp;
2149         cfs_completion_t        bltd_comp;
2150         int                     bltd_num;
2151 };
2152
2153 static int ldlm_bl_thread_main(void *arg);
2154
2155 static int ldlm_bl_thread_start(struct ldlm_bl_pool *blp)
2156 {
2157         struct ldlm_bl_thread_data bltd = { .bltd_blp = blp };
2158         int rc;
2159
2160         cfs_init_completion(&bltd.bltd_comp);
2161         rc = cfs_kernel_thread(ldlm_bl_thread_main, &bltd, 0);
2162         if (rc < 0) {
2163                 CERROR("cannot start LDLM thread ldlm_bl_%02d: rc %d\n",
2164                        cfs_atomic_read(&blp->blp_num_threads), rc);
2165                 return rc;
2166         }
2167         cfs_wait_for_completion(&bltd.bltd_comp);
2168
2169         return 0;
2170 }
2171
2172 static int ldlm_bl_thread_main(void *arg)
2173 {
2174         struct ldlm_bl_pool *blp;
2175         ENTRY;
2176
2177         {
2178                 struct ldlm_bl_thread_data *bltd = arg;
2179
2180                 blp = bltd->bltd_blp;
2181
2182                 bltd->bltd_num =
2183                         cfs_atomic_inc_return(&blp->blp_num_threads) - 1;
2184                 cfs_atomic_inc(&blp->blp_busy_threads);
2185
2186                 snprintf(bltd->bltd_name, sizeof(bltd->bltd_name) - 1,
2187                         "ldlm_bl_%02d", bltd->bltd_num);
2188                 cfs_daemonize(bltd->bltd_name);
2189
2190                 cfs_complete(&bltd->bltd_comp);
2191                 /* cannot use bltd after this, it is only on caller's stack */
2192         }
2193
2194         while (1) {
2195                 struct l_wait_info lwi = { 0 };
2196                 struct ldlm_bl_work_item *blwi = NULL;
2197
2198                 blwi = ldlm_bl_get_work(blp);
2199
2200                 if (blwi == NULL) {
2201                         int busy;
2202
2203                         cfs_atomic_dec(&blp->blp_busy_threads);
2204                         l_wait_event_exclusive(blp->blp_waitq,
2205                                          (blwi = ldlm_bl_get_work(blp)) != NULL,
2206                                          &lwi);
2207                         busy = cfs_atomic_inc_return(&blp->blp_busy_threads);
2208
2209                         if (blwi->blwi_ns == NULL)
2210                                 /* added by ldlm_cleanup() */
2211                                 break;
2212
2213                         /* Not fatal if racy and have a few too many threads */
2214                         if (unlikely(busy < blp->blp_max_threads &&
2215                             busy >= cfs_atomic_read(&blp->blp_num_threads)))
2216                                 /* discard the return value, we tried */
2217                                 ldlm_bl_thread_start(blp);
2218                 } else {
2219                         if (blwi->blwi_ns == NULL)
2220                                 /* added by ldlm_cleanup() */
2221                                 break;
2222                 }
2223
2224                 if (blwi->blwi_count) {
2225                         int count;
2226                         /* The special case when we cancel locks in lru
2227                          * asynchronously, we pass the list of locks here.
2228                          * Thus locks are marked LDLM_FL_CANCELING, but NOT
2229                          * canceled locally yet. */
2230                         count = ldlm_cli_cancel_list_local(&blwi->blwi_head,
2231                                                            blwi->blwi_count,
2232                                                            LCF_BL_AST);
2233                         ldlm_cli_cancel_list(&blwi->blwi_head, count, NULL, 0);
2234                 } else {
2235                         ldlm_handle_bl_callback(blwi->blwi_ns, &blwi->blwi_ld,
2236                                                 blwi->blwi_lock);
2237                 }
2238                 cfs_complete(&blwi->blwi_comp);
2239                 ldlm_bl_work_item_put(blwi);
2240         }
2241
2242         cfs_atomic_dec(&blp->blp_busy_threads);
2243         cfs_atomic_dec(&blp->blp_num_threads);
2244         cfs_complete(&blp->blp_comp);
2245         RETURN(0);
2246 }
2247
2248 #endif
2249
2250 static int ldlm_setup(void);
2251 static int ldlm_cleanup(void);
2252
2253 int ldlm_get_ref(void)
2254 {
2255         int rc = 0;
2256         ENTRY;
2257         cfs_mutex_down(&ldlm_ref_sem);
2258         if (++ldlm_refcount == 1) {
2259                 rc = ldlm_setup();
2260                 if (rc)
2261                         ldlm_refcount--;
2262         }
2263         cfs_mutex_up(&ldlm_ref_sem);
2264
2265         RETURN(rc);
2266 }
2267
2268 void ldlm_put_ref(void)
2269 {
2270         ENTRY;
2271         cfs_mutex_down(&ldlm_ref_sem);
2272         if (ldlm_refcount == 1) {
2273                 int rc = ldlm_cleanup();
2274                 if (rc)
2275                         CERROR("ldlm_cleanup failed: %d\n", rc);
2276                 else
2277                         ldlm_refcount--;
2278         } else {
2279                 ldlm_refcount--;
2280         }
2281         cfs_mutex_up(&ldlm_ref_sem);
2282
2283         EXIT;
2284 }
2285
2286 /*
2287  * Export handle<->lock hash operations.
2288  */
2289 static unsigned
2290 ldlm_export_lock_hash(cfs_hash_t *hs, void *key, unsigned mask)
2291 {
2292         return cfs_hash_u64_hash(((struct lustre_handle *)key)->cookie, mask);
2293 }
2294
2295 static void *
2296 ldlm_export_lock_key(cfs_hlist_node_t *hnode)
2297 {
2298         struct ldlm_lock *lock;
2299         ENTRY;
2300
2301         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2302         RETURN(&lock->l_remote_handle);
2303 }
2304
2305 static int
2306 ldlm_export_lock_compare(void *key, cfs_hlist_node_t *hnode)
2307 {
2308         ENTRY;
2309         RETURN(lustre_handle_equal(ldlm_export_lock_key(hnode), key));
2310 }
2311
2312 static void *
2313 ldlm_export_lock_get(cfs_hlist_node_t *hnode)
2314 {
2315         struct ldlm_lock *lock;
2316         ENTRY;
2317
2318         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2319         LDLM_LOCK_GET(lock);
2320
2321         RETURN(lock);
2322 }
2323
2324 static void *
2325 ldlm_export_lock_put(cfs_hlist_node_t *hnode)
2326 {
2327         struct ldlm_lock *lock;
2328         ENTRY;
2329
2330         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2331         LDLM_LOCK_RELEASE(lock);
2332
2333         RETURN(lock);
2334 }
2335
2336 static cfs_hash_ops_t ldlm_export_lock_ops = {
2337         .hs_hash    = ldlm_export_lock_hash,
2338         .hs_key     = ldlm_export_lock_key,
2339         .hs_compare = ldlm_export_lock_compare,
2340         .hs_get     = ldlm_export_lock_get,
2341         .hs_put     = ldlm_export_lock_put
2342 };
2343
2344 int ldlm_init_export(struct obd_export *exp)
2345 {
2346         ENTRY;
2347
2348         exp->exp_lock_hash =
2349                 cfs_hash_create(obd_uuid2str(&exp->exp_client_uuid),
2350                                 HASH_EXP_LOCK_CUR_BITS, HASH_EXP_LOCK_MAX_BITS,
2351                                 &ldlm_export_lock_ops, CFS_HASH_REHASH);
2352
2353         if (!exp->exp_lock_hash)
2354                 RETURN(-ENOMEM);
2355
2356         RETURN(0);
2357 }
2358 EXPORT_SYMBOL(ldlm_init_export);
2359
2360 void ldlm_destroy_export(struct obd_export *exp)
2361 {
2362         ENTRY;
2363         cfs_hash_putref(exp->exp_lock_hash);
2364         exp->exp_lock_hash = NULL;
2365         EXIT;
2366 }
2367 EXPORT_SYMBOL(ldlm_destroy_export);
2368
2369 static int ldlm_setup(void)
2370 {
2371         struct ldlm_bl_pool *blp;
2372         int rc = 0;
2373         int ldlm_min_threads = LDLM_THREADS_AUTO_MIN;
2374         int ldlm_max_threads = LDLM_THREADS_AUTO_MAX;
2375 #ifdef __KERNEL__
2376         int i;
2377 #endif
2378         ENTRY;
2379
2380         if (ldlm_state != NULL)
2381                 RETURN(-EALREADY);
2382
2383         OBD_ALLOC(ldlm_state, sizeof(*ldlm_state));
2384         if (ldlm_state == NULL)
2385                 RETURN(-ENOMEM);
2386
2387 #ifdef LPROCFS
2388         rc = ldlm_proc_setup();
2389         if (rc != 0)
2390                 GOTO(out_free, rc);
2391 #endif
2392
2393 #ifdef __KERNEL__
2394         if (ldlm_num_threads) {
2395                 /* If ldlm_num_threads is set, it is the min and the max. */
2396                 if (ldlm_num_threads > LDLM_THREADS_AUTO_MAX)
2397                         ldlm_num_threads = LDLM_THREADS_AUTO_MAX;
2398                 if (ldlm_num_threads < LDLM_THREADS_AUTO_MIN)
2399                         ldlm_num_threads = LDLM_THREADS_AUTO_MIN;
2400                 ldlm_min_threads = ldlm_max_threads = ldlm_num_threads;
2401         }
2402 #endif
2403
2404         ldlm_state->ldlm_cb_service =
2405                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
2406                                 LDLM_MAXREPSIZE, LDLM_CB_REQUEST_PORTAL,
2407                                 LDLM_CB_REPLY_PORTAL, 2,
2408                                 ldlm_callback_handler, "ldlm_cbd",
2409                                 ldlm_svc_proc_dir, NULL,
2410                                 ldlm_min_threads, ldlm_max_threads,
2411                                 "ldlm_cb",
2412                                 LCT_MD_THREAD|LCT_DT_THREAD, NULL);
2413
2414         if (!ldlm_state->ldlm_cb_service) {
2415                 CERROR("failed to start service\n");
2416                 GOTO(out_proc, rc = -ENOMEM);
2417         }
2418
2419         ldlm_state->ldlm_cancel_service =
2420                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
2421                                 LDLM_MAXREPSIZE, LDLM_CANCEL_REQUEST_PORTAL,
2422                                 LDLM_CANCEL_REPLY_PORTAL, 6,
2423                                 ldlm_cancel_handler, "ldlm_canceld",
2424                                 ldlm_svc_proc_dir, NULL,
2425                                 ldlm_min_threads, ldlm_max_threads,
2426                                 "ldlm_cn",
2427                                 LCT_MD_THREAD|LCT_DT_THREAD|LCT_CL_THREAD,
2428                                 NULL);
2429
2430         if (!ldlm_state->ldlm_cancel_service) {
2431                 CERROR("failed to start service\n");
2432                 GOTO(out_proc, rc = -ENOMEM);
2433         }
2434
2435         OBD_ALLOC(blp, sizeof(*blp));
2436         if (blp == NULL)
2437                 GOTO(out_proc, rc = -ENOMEM);
2438         ldlm_state->ldlm_bl_pool = blp;
2439
2440         cfs_spin_lock_init(&blp->blp_lock);
2441         CFS_INIT_LIST_HEAD(&blp->blp_list);
2442         CFS_INIT_LIST_HEAD(&blp->blp_prio_list);
2443         cfs_waitq_init(&blp->blp_waitq);
2444         cfs_atomic_set(&blp->blp_num_threads, 0);
2445         cfs_atomic_set(&blp->blp_busy_threads, 0);
2446         blp->blp_min_threads = ldlm_min_threads;
2447         blp->blp_max_threads = ldlm_max_threads;
2448
2449 #ifdef __KERNEL__
2450         for (i = 0; i < blp->blp_min_threads; i++) {
2451                 rc = ldlm_bl_thread_start(blp);
2452                 if (rc < 0)
2453                         GOTO(out_thread, rc);
2454         }
2455
2456         rc = ptlrpc_start_threads(NULL, ldlm_state->ldlm_cancel_service);
2457         if (rc)
2458                 GOTO(out_thread, rc);
2459
2460         rc = ptlrpc_start_threads(NULL, ldlm_state->ldlm_cb_service);
2461         if (rc)
2462                 GOTO(out_thread, rc);
2463
2464         CFS_INIT_LIST_HEAD(&expired_lock_thread.elt_expired_locks);
2465         expired_lock_thread.elt_state = ELT_STOPPED;
2466         cfs_waitq_init(&expired_lock_thread.elt_waitq);
2467
2468         CFS_INIT_LIST_HEAD(&waiting_locks_list);
2469         cfs_spin_lock_init(&waiting_locks_spinlock);
2470         cfs_timer_init(&waiting_locks_timer, waiting_locks_callback, 0);
2471
2472         rc = cfs_kernel_thread(expired_lock_main, NULL, CLONE_VM | CLONE_FILES);
2473         if (rc < 0) {
2474                 CERROR("Cannot start ldlm expired-lock thread: %d\n", rc);
2475                 GOTO(out_thread, rc);
2476         }
2477
2478         cfs_wait_event(expired_lock_thread.elt_waitq,
2479                        expired_lock_thread.elt_state == ELT_READY);
2480 #endif
2481
2482 #ifdef __KERNEL__
2483         rc = ldlm_pools_init();
2484         if (rc)
2485                 GOTO(out_thread, rc);
2486 #endif
2487         RETURN(0);
2488
2489 #ifdef __KERNEL__
2490  out_thread:
2491         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2492         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2493 #endif
2494
2495  out_proc:
2496 #ifdef LPROCFS
2497         ldlm_proc_cleanup();
2498  out_free:
2499 #endif
2500         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
2501         ldlm_state = NULL;
2502         return rc;
2503 }
2504
2505 static int ldlm_cleanup(void)
2506 {
2507 #ifdef __KERNEL__
2508         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
2509 #endif
2510         ENTRY;
2511
2512         if (!cfs_list_empty(ldlm_namespace_list(LDLM_NAMESPACE_SERVER)) ||
2513             !cfs_list_empty(ldlm_namespace_list(LDLM_NAMESPACE_CLIENT))) {
2514                 CERROR("ldlm still has namespaces; clean these up first.\n");
2515                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
2516                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
2517                 RETURN(-EBUSY);
2518         }
2519
2520 #ifdef __KERNEL__
2521         ldlm_pools_fini();
2522 #endif
2523
2524 #ifdef __KERNEL__
2525         while (cfs_atomic_read(&blp->blp_num_threads) > 0) {
2526                 struct ldlm_bl_work_item blwi = { .blwi_ns = NULL };
2527
2528                 cfs_init_completion(&blp->blp_comp);
2529
2530                 cfs_spin_lock(&blp->blp_lock);
2531                 cfs_list_add_tail(&blwi.blwi_entry, &blp->blp_list);
2532                 cfs_waitq_signal(&blp->blp_waitq);
2533                 cfs_spin_unlock(&blp->blp_lock);
2534
2535                 cfs_wait_for_completion(&blp->blp_comp);
2536         }
2537         OBD_FREE(blp, sizeof(*blp));
2538
2539         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2540         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2541         ldlm_proc_cleanup();
2542
2543         expired_lock_thread.elt_state = ELT_TERMINATE;
2544         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
2545         cfs_wait_event(expired_lock_thread.elt_waitq,
2546                        expired_lock_thread.elt_state == ELT_STOPPED);
2547 #else
2548         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2549         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2550 #endif
2551
2552         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
2553         ldlm_state = NULL;
2554
2555         RETURN(0);
2556 }
2557
2558 int __init ldlm_init(void)
2559 {
2560         cfs_init_mutex(&ldlm_ref_sem);
2561         cfs_init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_SERVER));
2562         cfs_init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
2563         ldlm_resource_slab = cfs_mem_cache_create("ldlm_resources",
2564                                                sizeof(struct ldlm_resource), 0,
2565                                                CFS_SLAB_HWCACHE_ALIGN);
2566         if (ldlm_resource_slab == NULL)
2567                 return -ENOMEM;
2568
2569         ldlm_lock_slab = cfs_mem_cache_create("ldlm_locks",
2570                               sizeof(struct ldlm_lock), 0,
2571                               CFS_SLAB_HWCACHE_ALIGN | CFS_SLAB_DESTROY_BY_RCU);
2572         if (ldlm_lock_slab == NULL) {
2573                 cfs_mem_cache_destroy(ldlm_resource_slab);
2574                 return -ENOMEM;
2575         }
2576
2577         ldlm_interval_slab = cfs_mem_cache_create("interval_node",
2578                                         sizeof(struct ldlm_interval),
2579                                         0, CFS_SLAB_HWCACHE_ALIGN);
2580         if (ldlm_interval_slab == NULL) {
2581                 cfs_mem_cache_destroy(ldlm_resource_slab);
2582                 cfs_mem_cache_destroy(ldlm_lock_slab);
2583                 return -ENOMEM;
2584         }
2585 #if LUSTRE_TRACKS_LOCK_EXP_REFS
2586         class_export_dump_hook = ldlm_dump_export_locks;
2587 #endif
2588         return 0;
2589 }
2590
2591 void __exit ldlm_exit(void)
2592 {
2593         int rc;
2594         if (ldlm_refcount)
2595                 CERROR("ldlm_refcount is %d in ldlm_exit!\n", ldlm_refcount);
2596         rc = cfs_mem_cache_destroy(ldlm_resource_slab);
2597         LASSERTF(rc == 0, "couldn't free ldlm resource slab\n");
2598 #ifdef __KERNEL__
2599         /* ldlm_lock_put() use RCU to call ldlm_lock_free, so need call
2600          * synchronize_rcu() to wait a grace period elapsed, so that
2601          * ldlm_lock_free() get a chance to be called. */
2602         synchronize_rcu();
2603 #endif
2604         rc = cfs_mem_cache_destroy(ldlm_lock_slab);
2605         LASSERTF(rc == 0, "couldn't free ldlm lock slab\n");
2606         rc = cfs_mem_cache_destroy(ldlm_interval_slab);
2607         LASSERTF(rc == 0, "couldn't free interval node slab\n");
2608 }
2609
2610 /* ldlm_extent.c */
2611 EXPORT_SYMBOL(ldlm_extent_shift_kms);
2612
2613 /* ldlm_lock.c */
2614 EXPORT_SYMBOL(ldlm_get_processing_policy);
2615 EXPORT_SYMBOL(ldlm_lock2desc);
2616 EXPORT_SYMBOL(ldlm_register_intent);
2617 EXPORT_SYMBOL(ldlm_lockname);
2618 EXPORT_SYMBOL(ldlm_typename);
2619 EXPORT_SYMBOL(ldlm_lock2handle);
2620 EXPORT_SYMBOL(__ldlm_handle2lock);
2621 EXPORT_SYMBOL(ldlm_lock_get);
2622 EXPORT_SYMBOL(ldlm_lock_put);
2623 EXPORT_SYMBOL(ldlm_lock_match);
2624 EXPORT_SYMBOL(ldlm_lock_cancel);
2625 EXPORT_SYMBOL(ldlm_lock_addref);
2626 EXPORT_SYMBOL(ldlm_lock_addref_try);
2627 EXPORT_SYMBOL(ldlm_lock_decref);
2628 EXPORT_SYMBOL(ldlm_lock_decref_and_cancel);
2629 EXPORT_SYMBOL(ldlm_lock_change_resource);
2630 EXPORT_SYMBOL(ldlm_it2str);
2631 EXPORT_SYMBOL(ldlm_lock_dump);
2632 EXPORT_SYMBOL(ldlm_lock_dump_handle);
2633 EXPORT_SYMBOL(ldlm_reprocess_all_ns);
2634 EXPORT_SYMBOL(ldlm_lock_allow_match_locked);
2635 EXPORT_SYMBOL(ldlm_lock_allow_match);
2636 EXPORT_SYMBOL(ldlm_lock_downgrade);
2637 EXPORT_SYMBOL(ldlm_lock_convert);
2638
2639 /* ldlm_request.c */
2640 EXPORT_SYMBOL(ldlm_completion_ast_async);
2641 EXPORT_SYMBOL(ldlm_blocking_ast_nocheck);
2642 EXPORT_SYMBOL(ldlm_completion_ast);
2643 EXPORT_SYMBOL(ldlm_blocking_ast);
2644 EXPORT_SYMBOL(ldlm_glimpse_ast);
2645 EXPORT_SYMBOL(ldlm_expired_completion_wait);
2646 EXPORT_SYMBOL(ldlm_prep_enqueue_req);
2647 EXPORT_SYMBOL(ldlm_prep_elc_req);
2648 EXPORT_SYMBOL(ldlm_cli_convert);
2649 EXPORT_SYMBOL(ldlm_cli_enqueue);
2650 EXPORT_SYMBOL(ldlm_cli_enqueue_fini);
2651 EXPORT_SYMBOL(ldlm_cli_enqueue_local);
2652 EXPORT_SYMBOL(ldlm_cli_cancel);
2653 EXPORT_SYMBOL(ldlm_cli_cancel_unused);
2654 EXPORT_SYMBOL(ldlm_cli_cancel_unused_resource);
2655 EXPORT_SYMBOL(ldlm_cli_cancel_req);
2656 EXPORT_SYMBOL(ldlm_replay_locks);
2657 EXPORT_SYMBOL(ldlm_resource_foreach);
2658 EXPORT_SYMBOL(ldlm_namespace_foreach);
2659 EXPORT_SYMBOL(ldlm_namespace_foreach_res);
2660 EXPORT_SYMBOL(ldlm_resource_iterate);
2661 EXPORT_SYMBOL(ldlm_cancel_resource_local);
2662 EXPORT_SYMBOL(ldlm_cli_cancel_list_local);
2663 EXPORT_SYMBOL(ldlm_cli_cancel_list);
2664
2665 /* ldlm_lockd.c */
2666 EXPORT_SYMBOL(ldlm_server_blocking_ast);
2667 EXPORT_SYMBOL(ldlm_server_completion_ast);
2668 EXPORT_SYMBOL(ldlm_server_glimpse_ast);
2669 EXPORT_SYMBOL(ldlm_handle_enqueue);
2670 EXPORT_SYMBOL(ldlm_handle_enqueue0);
2671 EXPORT_SYMBOL(ldlm_handle_cancel);
2672 EXPORT_SYMBOL(ldlm_request_cancel);
2673 EXPORT_SYMBOL(ldlm_handle_convert);
2674 EXPORT_SYMBOL(ldlm_handle_convert0);
2675 EXPORT_SYMBOL(ldlm_del_waiting_lock);
2676 EXPORT_SYMBOL(ldlm_get_ref);
2677 EXPORT_SYMBOL(ldlm_put_ref);
2678 EXPORT_SYMBOL(ldlm_refresh_waiting_lock);
2679 EXPORT_SYMBOL(ldlm_revoke_export_locks);
2680
2681 /* ldlm_resource.c */
2682 EXPORT_SYMBOL(ldlm_namespace_new);
2683 EXPORT_SYMBOL(ldlm_namespace_cleanup);
2684 EXPORT_SYMBOL(ldlm_namespace_free);
2685 EXPORT_SYMBOL(ldlm_namespace_dump);
2686 EXPORT_SYMBOL(ldlm_dump_all_namespaces);
2687 EXPORT_SYMBOL(ldlm_resource_get);
2688 EXPORT_SYMBOL(ldlm_resource_putref);
2689 EXPORT_SYMBOL(ldlm_resource_unlink_lock);
2690
2691 /* ldlm_lib.c */
2692 EXPORT_SYMBOL(client_import_add_conn);
2693 EXPORT_SYMBOL(client_import_del_conn);
2694 EXPORT_SYMBOL(client_obd_setup);
2695 EXPORT_SYMBOL(client_obd_cleanup);
2696 EXPORT_SYMBOL(client_connect_import);
2697 EXPORT_SYMBOL(client_disconnect_export);
2698 EXPORT_SYMBOL(server_disconnect_export);
2699 EXPORT_SYMBOL(target_stop_recovery_thread);
2700 EXPORT_SYMBOL(target_handle_connect);
2701 EXPORT_SYMBOL(target_cleanup_recovery);
2702 EXPORT_SYMBOL(target_destroy_export);
2703 EXPORT_SYMBOL(target_cancel_recovery_timer);
2704 EXPORT_SYMBOL(target_send_reply);
2705 EXPORT_SYMBOL(target_queue_recovery_request);
2706 EXPORT_SYMBOL(target_handle_ping);
2707 EXPORT_SYMBOL(target_pack_pool_reply);
2708 EXPORT_SYMBOL(target_handle_disconnect);
2709
2710 /* l_lock.c */
2711 EXPORT_SYMBOL(lock_res_and_lock);
2712 EXPORT_SYMBOL(unlock_res_and_lock);