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