Whamcloud - gitweb
b=18761
[fs/lustre-release.git] / lustre / ldlm / ldlm_request.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  */
36
37 #define DEBUG_SUBSYSTEM S_LDLM
38 #ifndef __KERNEL__
39 #include <signal.h>
40 #include <liblustre.h>
41 #endif
42
43 #include <lustre_dlm.h>
44 #include <obd_class.h>
45 #include <obd.h>
46
47 #include "ldlm_internal.h"
48
49 int ldlm_enqueue_min = OBD_TIMEOUT_DEFAULT;
50 CFS_MODULE_PARM(ldlm_enqueue_min, "i", int, 0644,
51                 "lock enqueue timeout minimum");
52
53 static void interrupted_completion_wait(void *data)
54 {
55 }
56
57 struct lock_wait_data {
58         struct ldlm_lock *lwd_lock;
59         __u32             lwd_conn_cnt;
60 };
61
62 struct ldlm_async_args {
63         struct lustre_handle lock_handle;
64 };
65
66 int ldlm_expired_completion_wait(void *data)
67 {
68         struct lock_wait_data *lwd = data;
69         struct ldlm_lock *lock = lwd->lwd_lock;
70         struct obd_import *imp;
71         struct obd_device *obd;
72
73         ENTRY;
74         if (lock->l_conn_export == NULL) {
75                 static cfs_time_t next_dump = 0, last_dump = 0;
76
77                 LDLM_ERROR(lock, "lock timed out (enqueued at %lu, %lus ago); "
78                            "not entering recovery in server code, just going "
79                            "back to sleep", lock->l_last_activity,
80                            cfs_time_current_sec() - lock->l_last_activity);
81                 if (cfs_time_after(cfs_time_current(), next_dump)) {
82                         last_dump = next_dump;
83                         next_dump = cfs_time_shift(300);
84                         ldlm_namespace_dump(D_DLMTRACE,
85                                             lock->l_resource->lr_namespace);
86                         if (last_dump == 0)
87                                 libcfs_debug_dumplog();
88                 }
89                 RETURN(0);
90         }
91
92         obd = lock->l_conn_export->exp_obd;
93         imp = obd->u.cli.cl_import;
94         ptlrpc_fail_import(imp, lwd->lwd_conn_cnt);
95         LDLM_ERROR(lock, "lock timed out (enqueued at %lu, %lus ago), entering "
96                    "recovery for %s@%s", lock->l_last_activity,
97                    cfs_time_current_sec() - lock->l_last_activity,
98                    obd2cli_tgt(obd), imp->imp_connection->c_remote_uuid.uuid);
99
100         RETURN(0);
101 }
102
103 /* We use the same basis for both server side and client side functions
104    from a single node. */
105 int ldlm_get_enq_timeout(struct ldlm_lock *lock)
106 {
107         int timeout = at_get(&lock->l_resource->lr_namespace->ns_at_estimate);
108         if (AT_OFF)
109                 return obd_timeout / 2;
110         /* Since these are non-updating timeouts, we should be conservative.
111            It would be nice to have some kind of "early reply" mechanism for
112            lock callbacks too... */
113         timeout = timeout + (timeout >> 1); /* 150% */
114         return max(timeout, ldlm_enqueue_min);
115 }
116 EXPORT_SYMBOL(ldlm_get_enq_timeout);
117
118 int ldlm_completion_ast(struct ldlm_lock *lock, int flags, void *data)
119 {
120         /* XXX ALLOCATE - 160 bytes */
121         struct lock_wait_data lwd;
122         struct obd_device *obd;
123         struct obd_import *imp = NULL;
124         struct l_wait_info lwi;
125         __u32 timeout;
126         int rc = 0;
127         ENTRY;
128
129         if (flags == LDLM_FL_WAIT_NOREPROC) {
130                 LDLM_DEBUG(lock, "client-side enqueue waiting on pending lock");
131                 goto noreproc;
132         }
133
134         if (!(flags & (LDLM_FL_BLOCK_WAIT | LDLM_FL_BLOCK_GRANTED |
135                        LDLM_FL_BLOCK_CONV))) {
136                 cfs_waitq_signal(&lock->l_waitq);
137                 RETURN(0);
138         }
139
140         LDLM_DEBUG(lock, "client-side enqueue returned a blocked lock, "
141                    "sleeping");
142         ldlm_lock_dump(D_OTHER, lock, 0);
143         ldlm_reprocess_all(lock->l_resource);
144
145 noreproc:
146
147         obd = class_exp2obd(lock->l_conn_export);
148
149         /* if this is a local lock, then there is no import */
150         if (obd != NULL) {
151                 imp = obd->u.cli.cl_import;
152         }
153
154         /* Wait a long time for enqueue - server may have to callback a
155            lock from another client.  Server will evict the other client if it
156            doesn't respond reasonably, and then give us the lock. */
157         timeout = ldlm_get_enq_timeout(lock) * 2;
158
159         lwd.lwd_lock = lock;
160
161         if (lock->l_flags & LDLM_FL_NO_TIMEOUT) {
162                 LDLM_DEBUG(lock, "waiting indefinitely because of NO_TIMEOUT");
163                 lwi = LWI_INTR(interrupted_completion_wait, &lwd);
164         } else {
165                 lwi = LWI_TIMEOUT_INTR(cfs_time_seconds(timeout),
166                                        ldlm_expired_completion_wait,
167                                        interrupted_completion_wait, &lwd);
168         }
169
170         if (imp != NULL) {
171                 spin_lock(&imp->imp_lock);
172                 lwd.lwd_conn_cnt = imp->imp_conn_cnt;
173                 spin_unlock(&imp->imp_lock);
174         }
175
176         if (ns_is_client(lock->l_resource->lr_namespace) &&
177             OBD_FAIL_CHECK(OBD_FAIL_LDLM_INTR_CP_AST | OBD_FAIL_ONCE)) {
178                 obd_fail_loc = OBD_FAIL_LDLM_CP_BL_RACE | OBD_FAIL_ONCE;
179                 lock->l_flags |= LDLM_FL_FAIL_LOC;
180                 rc = -EINTR;
181         } else {
182                 /* Go to sleep until the lock is granted or cancelled. */
183                 rc = l_wait_event(lock->l_waitq,
184                                   is_granted_or_cancelled(lock), &lwi);
185         }
186
187         if (lock->l_destroyed || lock->l_flags & LDLM_FL_FAILED) {
188                 LDLM_DEBUG(lock, "client-side enqueue waking up: destroyed");
189                 RETURN(-EIO);
190         }
191
192         if (rc) {
193                 LDLM_DEBUG(lock, "client-side enqueue waking up: failed (%d)",
194                            rc);
195                 RETURN(rc);
196         }
197
198         LDLM_DEBUG(lock, "client-side enqueue waking up: granted after %lds",
199                    cfs_time_current_sec() - lock->l_last_activity);
200
201         /* Update our time estimate */
202         at_add(&lock->l_resource->lr_namespace->ns_at_estimate,
203                cfs_time_current_sec() - lock->l_last_activity);
204
205         RETURN(0);
206 }
207
208 /*
209  * ->l_blocking_ast() callback for LDLM locks acquired by server-side OBDs.
210  */
211 int ldlm_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
212                       void *data, int flag)
213 {
214         int do_ast;
215         ENTRY;
216
217         if (flag == LDLM_CB_CANCELING) {
218                 /* Don't need to do anything here. */
219                 RETURN(0);
220         }
221
222         lock_res_and_lock(lock);
223         /* Get this: if ldlm_blocking_ast is racing with intent_policy, such
224          * that ldlm_blocking_ast is called just before intent_policy method
225          * takes the ns_lock, then by the time we get the lock, we might not
226          * be the correct blocking function anymore.  So check, and return
227          * early, if so. */
228         if (lock->l_blocking_ast != ldlm_blocking_ast) {
229                 unlock_res_and_lock(lock);
230                 RETURN(0);
231         }
232
233         lock->l_flags |= LDLM_FL_CBPENDING;
234         do_ast = (!lock->l_readers && !lock->l_writers);
235         unlock_res_and_lock(lock);
236
237         if (do_ast) {
238                 struct lustre_handle lockh;
239                 int rc;
240
241                 LDLM_DEBUG(lock, "already unused, calling ldlm_cli_cancel");
242                 ldlm_lock2handle(lock, &lockh);
243                 rc = ldlm_cli_cancel(&lockh);
244                 if (rc < 0)
245                         CERROR("ldlm_cli_cancel: %d\n", rc);
246         } else {
247                 LDLM_DEBUG(lock, "Lock still has references, will be "
248                            "cancelled later");
249         }
250         RETURN(0);
251 }
252
253 /*
254  * ->l_glimpse_ast() for DLM extent locks acquired on the server-side. See
255  * comment in filter_intent_policy() on why you may need this.
256  */
257 int ldlm_glimpse_ast(struct ldlm_lock *lock, void *reqp)
258 {
259         /*
260          * Returning -ELDLM_NO_LOCK_DATA actually works, but the reason for
261          * that is rather subtle: with OST-side locking, it may so happen that
262          * _all_ extent locks are held by the OST. If client wants to obtain
263          * current file size it calls ll{,u}_glimpse_size(), and (as locks are
264          * on the server), dummy glimpse callback fires and does
265          * nothing. Client still receives correct file size due to the
266          * following fragment in filter_intent_policy():
267          *
268          * rc = l->l_glimpse_ast(l, NULL); // this will update the LVB
269          * if (rc != 0 && res->lr_namespace->ns_lvbo &&
270          *     res->lr_namespace->ns_lvbo->lvbo_update) {
271          *         res->lr_namespace->ns_lvbo->lvbo_update(res, NULL, 0, 1);
272          * }
273          *
274          * that is, after glimpse_ast() fails, filter_lvbo_update() runs, and
275          * returns correct file size to the client.
276          */
277         return -ELDLM_NO_LOCK_DATA;
278 }
279
280 int ldlm_cli_enqueue_local(struct ldlm_namespace *ns,
281                            struct ldlm_res_id *res_id,
282                            ldlm_type_t type, ldlm_policy_data_t *policy,
283                            ldlm_mode_t mode, int *flags,
284                            ldlm_blocking_callback blocking,
285                            ldlm_completion_callback completion,
286                            ldlm_glimpse_callback glimpse,
287                            void *data, __u32 lvb_len, void *lvb_swabber,
288                            struct lustre_handle *lockh)
289 {
290         struct ldlm_lock *lock;
291         int err;
292         ENTRY;
293
294         LASSERT(!(*flags & LDLM_FL_REPLAY));
295         if (ns_is_client(ns)) {
296                 CERROR("Trying to enqueue local lock in a shadow namespace\n");
297                 LBUG();
298         }
299
300         lock = ldlm_lock_create(ns, *res_id, type, mode, blocking,
301                                 completion, glimpse, data, lvb_len);
302         if (!lock)
303                 GOTO(out_nolock, err = -ENOMEM);
304         LDLM_DEBUG(lock, "client-side local enqueue handler, new lock created");
305
306         ldlm_lock_addref_internal(lock, mode);
307         ldlm_lock2handle(lock, lockh);
308         lock_res_and_lock(lock);
309         lock->l_flags |= LDLM_FL_LOCAL;
310         if (*flags & LDLM_FL_ATOMIC_CB)
311                 lock->l_flags |= LDLM_FL_ATOMIC_CB;
312         lock->l_lvb_swabber = lvb_swabber;
313         unlock_res_and_lock(lock);
314         if (policy != NULL)
315                 lock->l_policy_data = *policy;
316         if (type == LDLM_EXTENT)
317                 lock->l_req_extent = policy->l_extent;
318
319         err = ldlm_lock_enqueue(ns, &lock, policy, flags);
320         if (err != ELDLM_OK)
321                 GOTO(out, err);
322
323         if (policy != NULL)
324                 *policy = lock->l_policy_data;
325         if ((*flags) & LDLM_FL_LOCK_CHANGED)
326                 *res_id = lock->l_resource->lr_name;
327
328         LDLM_DEBUG_NOLOCK("client-side local enqueue handler END (lock %p)",
329                           lock);
330
331         if (lock->l_completion_ast)
332                 lock->l_completion_ast(lock, *flags, NULL);
333
334         LDLM_DEBUG(lock, "client-side local enqueue END");
335         EXIT;
336  out:
337         LDLM_LOCK_PUT(lock);
338  out_nolock:
339         return err;
340 }
341
342 static void failed_lock_cleanup(struct ldlm_namespace *ns,
343                                 struct ldlm_lock *lock,
344                                 struct lustre_handle *lockh, int mode)
345 {
346         int need_cancel = 0;
347
348         /* Set a flag to prevent us from sending a CANCEL (bug 407) */
349         lock_res_and_lock(lock);
350         /* Check that lock is not granted or failed, we might race. */
351         if ((lock->l_req_mode != lock->l_granted_mode) &&
352             !(lock->l_flags & LDLM_FL_FAILED)) {
353                 /* Make sure that this lock will not be found by raced
354                  * bl_ast and -EINVAL reply is sent to server anyways.
355                  * bug 17645 */
356                 lock->l_flags |= LDLM_FL_LOCAL_ONLY | LDLM_FL_FAILED |
357                                  LDLM_FL_ATOMIC_CB;
358                 need_cancel = 1;
359         }
360         unlock_res_and_lock(lock);
361
362         if (need_cancel) {
363                 LDLM_DEBUG(lock,
364                            "setting FL_LOCAL_ONLY | LDLM_FL_FAILED | "
365                            "LDLM_FL_ATOMIC_CB");
366                 ldlm_lock_decref_and_cancel(lockh, mode);
367         } else {
368                 LDLM_DEBUG(lock, "lock was granted or failed in race");
369                 ldlm_lock_decref(lockh, mode);
370         }
371
372         /* XXX - HACK because we shouldn't call ldlm_lock_destroy()
373          *       from llite/file.c/ll_file_flock(). */
374         if (lock->l_resource->lr_type == LDLM_FLOCK) {
375                 ldlm_lock_destroy(lock);
376         }
377 }
378
379 int ldlm_cli_enqueue_fini(struct obd_export *exp, struct ptlrpc_request *req,
380                           ldlm_type_t type, __u8 with_policy, ldlm_mode_t mode,
381                           int *flags, void *lvb, __u32 lvb_len,
382                           void *lvb_swabber, struct lustre_handle *lockh,int rc)
383 {
384         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
385         int is_replay = *flags & LDLM_FL_REPLAY;
386         struct lustre_handle old_hash_key;
387         struct ldlm_lock *lock;
388         struct ldlm_reply *reply;
389         int cleanup_phase = 1;
390         ENTRY;
391
392         lock = ldlm_handle2lock(lockh);
393         /* ldlm_cli_enqueue is holding a reference on this lock. */
394         if (!lock) {
395                 LASSERT(type == LDLM_FLOCK);
396                 RETURN(-ENOLCK);
397         }
398
399         if (rc != ELDLM_OK) {
400                 LASSERT(!is_replay);
401                 LDLM_DEBUG(lock, "client-side enqueue END (%s)",
402                            rc == ELDLM_LOCK_ABORTED ? "ABORTED" : "FAILED");
403                 if (rc == ELDLM_LOCK_ABORTED) {
404                         /* Before we return, swab the reply */
405                         reply = lustre_swab_repbuf(req, DLM_LOCKREPLY_OFF,
406                                                    sizeof(*reply),
407                                                    lustre_swab_ldlm_reply);
408                         if (reply == NULL) {
409                                 CERROR("Can't unpack ldlm_reply\n");
410                                 rc = -EPROTO;
411                         }
412                         if (lvb_len) {
413                                 void *tmplvb;
414                                 tmplvb = lustre_swab_repbuf(req,
415                                                             DLM_REPLY_REC_OFF,
416                                                             lvb_len,
417                                                             lvb_swabber);
418                                 if (tmplvb == NULL)
419                                         GOTO(cleanup, rc = -EPROTO);
420                                 if (lvb != NULL)
421                                         memcpy(lvb, tmplvb, lvb_len);
422                         }
423                 }
424                 GOTO(cleanup, rc);
425         }
426
427         reply = lustre_swab_repbuf(req, DLM_LOCKREPLY_OFF, sizeof(*reply),
428                                    lustre_swab_ldlm_reply);
429         if (reply == NULL) {
430                 CERROR("Can't unpack ldlm_reply\n");
431                 GOTO(cleanup, rc = -EPROTO);
432         }
433
434         /* lock enqueued on the server */
435         cleanup_phase = 0;
436
437         lock_res_and_lock(lock);
438         old_hash_key = lock->l_remote_handle;
439         lock->l_remote_handle = reply->lock_handle;
440
441         /* Key change rehash lock in per-export hash with new key */
442         if (exp->exp_lock_hash)
443                 lustre_hash_rehash_key(exp->exp_lock_hash, &old_hash_key,
444                                        &lock->l_remote_handle,
445                                        &lock->l_exp_hash);
446
447         *flags = reply->lock_flags;
448         lock->l_flags |= reply->lock_flags & LDLM_INHERIT_FLAGS;
449         /* move NO_TIMEOUT flag to the lock to force ldlm_lock_match()
450          * to wait with no timeout as well */
451         lock->l_flags |= reply->lock_flags & LDLM_FL_NO_TIMEOUT;
452         unlock_res_and_lock(lock);
453
454         CDEBUG(D_INFO, "local: %p, remote cookie: "LPX64", flags: 0x%x\n",
455                lock, reply->lock_handle.cookie, *flags);
456
457         /* If enqueue returned a blocked lock but the completion handler has
458          * already run, then it fixed up the resource and we don't need to do it
459          * again. */
460         if ((*flags) & LDLM_FL_LOCK_CHANGED) {
461                 int newmode = reply->lock_desc.l_req_mode;
462                 LASSERT(!is_replay);
463                 if (newmode && newmode != lock->l_req_mode) {
464                         LDLM_DEBUG(lock, "server returned different mode %s",
465                                    ldlm_lockname[newmode]);
466                         lock->l_req_mode = newmode;
467                 }
468
469                 if (memcmp(reply->lock_desc.l_resource.lr_name.name,
470                           lock->l_resource->lr_name.name,
471                           sizeof(struct ldlm_res_id))) {
472                         CDEBUG(D_INFO, "remote intent success, locking "
473                                         "("LPU64"/"LPU64"/"LPU64") instead of "
474                                         "("LPU64"/"LPU64"/"LPU64")\n",
475                                reply->lock_desc.l_resource.lr_name.name[0],
476                                reply->lock_desc.l_resource.lr_name.name[1],
477                                reply->lock_desc.l_resource.lr_name.name[2],
478                                lock->l_resource->lr_name.name[0],
479                                lock->l_resource->lr_name.name[1],
480                                lock->l_resource->lr_name.name[2]);
481
482                         rc = ldlm_lock_change_resource(ns, lock,
483                                            reply->lock_desc.l_resource.lr_name);
484                         if (rc || lock->l_resource == NULL)
485                                 GOTO(cleanup, rc = -ENOMEM);
486                         LDLM_DEBUG(lock, "client-side enqueue, new resource");
487                 }
488                 if (with_policy)
489                         if (!(type == LDLM_IBITS && !(exp->exp_connect_flags &
490                                                     OBD_CONNECT_IBITS)))
491                                 lock->l_policy_data =
492                                                  reply->lock_desc.l_policy_data;
493                 if (type != LDLM_PLAIN)
494                         LDLM_DEBUG(lock,"client-side enqueue, new policy data");
495         }
496
497         if ((*flags) & LDLM_FL_AST_SENT ||
498             /* Cancel extent locks as soon as possible on a liblustre client,
499              * because it cannot handle asynchronous ASTs robustly (see
500              * bug 7311). */
501             (LIBLUSTRE_CLIENT && type == LDLM_EXTENT)) {
502                 lock_res_and_lock(lock);
503                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_BL_AST;
504                 unlock_res_and_lock(lock);
505                 LDLM_DEBUG(lock, "enqueue reply includes blocking AST");
506         }
507
508         /* If the lock has already been granted by a completion AST, don't
509          * clobber the LVB with an older one. */
510         if (lvb_len && (lock->l_req_mode != lock->l_granted_mode)) {
511                 void *tmplvb;
512                 tmplvb = lustre_swab_repbuf(req, DLM_REPLY_REC_OFF, lvb_len,
513                                             lvb_swabber);
514                 if (tmplvb == NULL)
515                         GOTO(cleanup, rc = -EPROTO);
516                 memcpy(lock->l_lvb_data, tmplvb, lvb_len);
517         }
518
519         if (!is_replay) {
520                 rc = ldlm_lock_enqueue(ns, &lock, NULL, flags);
521                 if (lock->l_completion_ast != NULL) {
522                         int err = lock->l_completion_ast(lock, *flags, NULL);
523                         if (!rc)
524                                 rc = err;
525                         if (rc && type != LDLM_FLOCK) /* bug 9425, bug 10250 */
526                                 cleanup_phase = 1;
527                 }
528         }
529
530         if (lvb_len && lvb != NULL) {
531                 /* Copy the LVB here, and not earlier, because the completion
532                  * AST (if any) can override what we got in the reply */
533                 memcpy(lvb, lock->l_lvb_data, lvb_len);
534         }
535
536         LDLM_DEBUG(lock, "client-side enqueue END");
537         EXIT;
538 cleanup:
539         if (cleanup_phase == 1 && rc)
540                 failed_lock_cleanup(ns, lock, lockh, mode);
541         /* Put lock 2 times, the second reference is held by ldlm_cli_enqueue */
542         LDLM_LOCK_PUT(lock);
543         LDLM_LOCK_PUT(lock);
544         return rc;
545 }
546
547 /* PAGE_SIZE-512 is to allow TCP/IP and LNET headers to fit into
548  * a single page on the send/receive side. XXX: 512 should be changed
549  * to more adequate value. */
550 static inline int ldlm_req_handles_avail(struct obd_export *exp,
551                                          __u32 *size, int bufcount, int off)
552 {
553         int avail = min_t(int, LDLM_MAXREQSIZE, CFS_PAGE_SIZE - 512);
554
555         avail -= lustre_msg_size(class_exp2cliimp(exp)->imp_msg_magic,
556                                  bufcount, size);
557         if (likely(avail >= 0))
558                 avail /= (int)sizeof(struct lustre_handle);
559         else
560                 avail = 0;
561         avail += LDLM_LOCKREQ_HANDLES - off;
562
563         return avail;
564 }
565
566 static inline int ldlm_cancel_handles_avail(struct obd_export *exp)
567 {
568         __u32 size[2] = { sizeof(struct ptlrpc_body),
569                         sizeof(struct ldlm_request) };
570         return ldlm_req_handles_avail(exp, size, 2, 0);
571 }
572
573 /* Cancel lru locks and pack them into the enqueue request. Pack there the given
574  * @count locks in @cancels. */
575 struct ptlrpc_request *ldlm_prep_elc_req(struct obd_export *exp, int version,
576                                          int opc, int bufcount, __u32 *size,
577                                          int bufoff, int canceloff,
578                                          struct list_head *cancels, int count)
579 {
580         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
581         int flags, avail, to_free, pack = 0;
582         struct ldlm_request *dlm = NULL;
583         struct ptlrpc_request *req;
584         CFS_LIST_HEAD(head);
585         ENTRY;
586
587         if (cancels == NULL)
588                 cancels = &head;
589         if (exp_connect_cancelset(exp)) {
590                 /* Estimate the amount of free space in the request. */
591                 LASSERT(bufoff < bufcount);
592
593                 avail = ldlm_req_handles_avail(exp, size, bufcount, canceloff);
594                 flags = ns_connect_lru_resize(ns) ?
595                         LDLM_CANCEL_LRUR : LDLM_CANCEL_AGED;
596                 to_free = !ns_connect_lru_resize(ns) &&
597                           opc == LDLM_ENQUEUE ? 1 : 0;
598
599                 /* Cancel lru locks here _only_ if the server supports
600                  * EARLY_CANCEL. Otherwise we have to send extra CANCEL
601                  * rpc, what will make us slower. */
602                 if (avail > count)
603                         count += ldlm_cancel_lru_local(ns, cancels, to_free,
604                                                        avail - count, 0, flags);
605                 if (avail > count)
606                         pack = count;
607                 else
608                         pack = avail;
609                 size[bufoff] = ldlm_request_bufsize(pack, opc);
610         }
611
612         req = ptlrpc_prep_req(class_exp2cliimp(exp), version,
613                               opc, bufcount, size, NULL);
614         req->rq_export = class_export_get(exp);
615         if (exp_connect_cancelset(exp) && req) {
616                 if (canceloff) {
617                         dlm = lustre_msg_buf(req->rq_reqmsg, bufoff,
618                                              sizeof(*dlm));
619                         /* Skip first lock handler in ldlm_request_pack(),
620                          * this method will incrment @lock_count according
621                          * to the lock handle amount actually written to
622                          * the buffer. */
623                         dlm->lock_count = canceloff;
624                 }
625                 /* Pack into the request @pack lock handles. */
626                 ldlm_cli_cancel_list(cancels, pack, req, bufoff);
627                 /* Prepare and send separate cancel rpc for others. */
628                 ldlm_cli_cancel_list(cancels, count - pack, NULL, 0);
629         } else {
630                 ldlm_lock_list_put(cancels, l_bl_ast, count);
631         }
632         RETURN(req);
633 }
634
635 struct ptlrpc_request *ldlm_prep_enqueue_req(struct obd_export *exp,
636                                              int bufcount, __u32 *size,
637                                              struct list_head *cancels,
638                                              int count)
639 {
640         return ldlm_prep_elc_req(exp, LUSTRE_DLM_VERSION, LDLM_ENQUEUE,
641                                  bufcount, size, DLM_LOCKREQ_OFF,
642                                  LDLM_ENQUEUE_CANCEL_OFF, cancels, count);
643 }
644
645 /* If a request has some specific initialisation it is passed in @reqp,
646  * otherwise it is created in ldlm_cli_enqueue.
647  *
648  * Supports sync and async requests, pass @async flag accordingly. If a
649  * request was created in ldlm_cli_enqueue and it is the async request,
650  * pass it to the caller in @reqp. */
651 int ldlm_cli_enqueue(struct obd_export *exp, struct ptlrpc_request **reqp,
652                      struct ldlm_enqueue_info *einfo, struct ldlm_res_id res_id,
653                      ldlm_policy_data_t *policy, int *flags,
654                      void *lvb, __u32 lvb_len, void *lvb_swabber,
655                      struct lustre_handle *lockh, int async)
656 {
657         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
658         struct ldlm_lock *lock;
659         struct ldlm_request *body;
660         struct ldlm_reply *reply;
661         __u32 size[3] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
662                         [DLM_LOCKREQ_OFF]     = sizeof(*body),
663                         [DLM_REPLY_REC_OFF]   = lvb_len ? lvb_len :
664                                                 sizeof(struct ost_lvb) };
665         int is_replay = *flags & LDLM_FL_REPLAY;
666         int req_passed_in = 1, rc, err;
667         struct ptlrpc_request *req;
668         ENTRY;
669
670         LASSERT(exp != NULL);
671
672         /* If we're replaying this lock, just check some invariants.
673          * If we're creating a new lock, get everything all setup nice. */
674         if (is_replay) {
675                 lock = ldlm_handle2lock(lockh);
676                 LASSERT(lock != NULL);
677                 LDLM_DEBUG(lock, "client-side enqueue START");
678                 LASSERT(exp == lock->l_conn_export);
679         } else {
680                 lock = ldlm_lock_create(ns, res_id, einfo->ei_type,
681                                         einfo->ei_mode, einfo->ei_cb_bl,
682                                         einfo->ei_cb_cp, einfo->ei_cb_gl,
683                                         einfo->ei_cbdata, lvb_len);
684                 if (lock == NULL)
685                         RETURN(-ENOMEM);
686                 /* for the local lock, add the reference */
687                 ldlm_lock_addref_internal(lock, einfo->ei_mode);
688                 ldlm_lock2handle(lock, lockh);
689                 lock->l_lvb_swabber = lvb_swabber;
690                 if (policy != NULL) {
691                         /* INODEBITS_INTEROP: If the server does not support
692                          * inodebits, we will request a plain lock in the
693                          * descriptor (ldlm_lock2desc() below) but use an
694                          * inodebits lock internally with both bits set.
695                          */
696                         if (einfo->ei_type == LDLM_IBITS &&
697                             !(exp->exp_connect_flags & OBD_CONNECT_IBITS))
698                                 lock->l_policy_data.l_inodebits.bits =
699                                         MDS_INODELOCK_LOOKUP |
700                                         MDS_INODELOCK_UPDATE;
701                         else
702                                 lock->l_policy_data = *policy;
703                 }
704
705                 if (einfo->ei_type == LDLM_EXTENT)
706                         lock->l_req_extent = policy->l_extent;
707                 LDLM_DEBUG(lock, "client-side enqueue START");
708         }
709
710         /* lock not sent to server yet */
711
712         if (reqp == NULL || *reqp == NULL) {
713                 req = ldlm_prep_enqueue_req(exp, 2, size, NULL, 0);
714                 if (req == NULL) {
715                         failed_lock_cleanup(ns, lock, lockh, einfo->ei_mode);
716                         LDLM_LOCK_PUT(lock);
717                         RETURN(-ENOMEM);
718                 }
719                 req_passed_in = 0;
720                 if (reqp)
721                         *reqp = req;
722         } else {
723                 req = *reqp;
724                 LASSERTF(lustre_msg_buflen(req->rq_reqmsg, DLM_LOCKREQ_OFF) >=
725                          sizeof(*body), "buflen[%d] = %d, not %d\n",
726                          DLM_LOCKREQ_OFF,
727                          lustre_msg_buflen(req->rq_reqmsg, DLM_LOCKREQ_OFF),
728                          (int)sizeof(*body));
729         }
730
731         lock->l_conn_export = exp;
732         lock->l_export = NULL;
733         lock->l_blocking_ast = einfo->ei_cb_bl;
734
735         /* Dump lock data into the request buffer */
736         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
737         ldlm_lock2desc(lock, &body->lock_desc);
738         body->lock_flags = *flags;
739         body->lock_handle[0] = *lockh;
740
741         /* Continue as normal. */
742         if (!req_passed_in) {
743                 size[DLM_LOCKREPLY_OFF] = sizeof(*reply);
744                 ptlrpc_req_set_repsize(req, 3, size);
745         }
746
747         /*
748          * Liblustre client doesn't get extent locks, except for O_APPEND case
749          * where [0, OBD_OBJECT_EOF] lock is taken, or truncate, where
750          * [i_size, OBD_OBJECT_EOF] lock is taken.
751          */
752         LASSERT(ergo(LIBLUSTRE_CLIENT, einfo->ei_type != LDLM_EXTENT ||
753                      policy->l_extent.end == OBD_OBJECT_EOF));
754
755         if (async) {
756                 LASSERT(reqp != NULL);
757                 RETURN(0);
758         }
759
760         LDLM_DEBUG(lock, "sending request");
761         rc = ptlrpc_queue_wait(req);
762         err = ldlm_cli_enqueue_fini(exp, req, einfo->ei_type, policy ? 1 : 0,
763                                     einfo->ei_mode, flags, lvb, lvb_len,
764                                     lvb_swabber, lockh, rc);
765
766         /* If ldlm_cli_enqueue_fini did not find the lock, we need to free
767          * one reference that we took */
768         if (err == -ENOLCK)
769                 LDLM_LOCK_PUT(lock);
770         else
771                 rc = err;
772
773         if (!req_passed_in && req != NULL) {
774                 ptlrpc_req_finished(req);
775                 if (reqp)
776                         *reqp = NULL;
777         }
778
779         RETURN(rc);
780 }
781
782 static int ldlm_cli_convert_local(struct ldlm_lock *lock, int new_mode,
783                                   __u32 *flags)
784 {
785         struct ldlm_resource *res;
786         int rc;
787         ENTRY;
788         if (ns_is_client(lock->l_resource->lr_namespace)) {
789                 CERROR("Trying to cancel local lock\n");
790                 LBUG();
791         }
792         LDLM_DEBUG(lock, "client-side local convert");
793
794         res = ldlm_lock_convert(lock, new_mode, flags);
795         if (res) {
796                 ldlm_reprocess_all(res);
797                 rc = 0;
798         } else {
799                 rc = EDEADLOCK;
800         }
801         LDLM_DEBUG(lock, "client-side local convert handler END");
802         LDLM_LOCK_PUT(lock);
803         RETURN(rc);
804 }
805
806 /* FIXME: one of ldlm_cli_convert or the server side should reject attempted
807  * conversion of locks which are on the waiting or converting queue */
808 /* Caller of this code is supposed to take care of lock readers/writers
809    accounting */
810 int ldlm_cli_convert(struct lustre_handle *lockh, int new_mode, __u32 *flags)
811 {
812         struct ldlm_request *body;
813         struct ldlm_reply *reply;
814         struct ldlm_lock *lock;
815         struct ldlm_resource *res;
816         struct ptlrpc_request *req;
817         __u32 size[2] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
818                         [DLM_LOCKREQ_OFF]     = sizeof(*body) };
819         int rc;
820         ENTRY;
821
822         lock = ldlm_handle2lock(lockh);
823         if (!lock) {
824                 LBUG();
825                 RETURN(-EINVAL);
826         }
827         *flags = 0;
828
829         if (lock->l_conn_export == NULL)
830                 RETURN(ldlm_cli_convert_local(lock, new_mode, flags));
831
832         LDLM_DEBUG(lock, "client-side convert");
833
834         req = ptlrpc_prep_req(class_exp2cliimp(lock->l_conn_export),
835                               LUSTRE_DLM_VERSION, LDLM_CONVERT, 2, size, NULL);
836         if (!req)
837                 GOTO(out, rc = -ENOMEM);
838
839         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
840         body->lock_handle[0] = lock->l_remote_handle;
841
842         body->lock_desc.l_req_mode = new_mode;
843         body->lock_flags = *flags;
844
845         size[DLM_LOCKREPLY_OFF] = sizeof(*reply);
846         ptlrpc_req_set_repsize(req, 2, size);
847
848         rc = ptlrpc_queue_wait(req);
849         if (rc != ELDLM_OK)
850                 GOTO(out, rc);
851
852         reply = lustre_swab_repbuf(req, DLM_LOCKREPLY_OFF, sizeof(*reply),
853                                    lustre_swab_ldlm_reply);
854         if (reply == NULL) {
855                 CERROR ("Can't unpack ldlm_reply\n");
856                 GOTO (out, rc = -EPROTO);
857         }
858
859         if (req->rq_status)
860                 GOTO(out, rc = req->rq_status);
861
862         res = ldlm_lock_convert(lock, new_mode, &reply->lock_flags);
863         if (res != NULL) {
864                 ldlm_reprocess_all(res);
865                 /* Go to sleep until the lock is granted. */
866                 /* FIXME: or cancelled. */
867                 if (lock->l_completion_ast) {
868                         rc = lock->l_completion_ast(lock, LDLM_FL_WAIT_NOREPROC,
869                                                     NULL);
870                         if (rc)
871                                 GOTO(out, rc);
872                 }
873         } else {
874                 rc = EDEADLOCK;
875         }
876         EXIT;
877  out:
878         LDLM_LOCK_PUT(lock);
879         ptlrpc_req_finished(req);
880         return rc;
881 }
882
883 /* Cancel locks locally.
884  * Returns:
885  * LDLM_FL_LOCAL_ONLY if tere is no need in a CANCEL rpc to the server;
886  * LDLM_FL_CANCELING otherwise;
887  * LDLM_FL_BL_AST if there is a need in a separate CANCEL rpc. */
888 static int ldlm_cli_cancel_local(struct ldlm_lock *lock)
889 {
890         int rc = LDLM_FL_LOCAL_ONLY;
891         ENTRY;
892
893         if (lock->l_conn_export) {
894                 int local_only;
895
896                 LDLM_DEBUG(lock, "client-side cancel");
897                 /* Set this flag to prevent others from getting new references*/
898                 lock_res_and_lock(lock);
899                 lock->l_flags |= LDLM_FL_CBPENDING;
900                 local_only = (lock->l_flags &
901                               (LDLM_FL_LOCAL_ONLY|LDLM_FL_CANCEL_ON_BLOCK));
902                 ldlm_cancel_callback(lock);
903                 rc = (lock->l_flags & LDLM_FL_BL_AST) ?
904                         LDLM_FL_BL_AST : LDLM_FL_CANCELING;
905                 unlock_res_and_lock(lock);
906
907                 if (local_only) {
908                         CDEBUG(D_DLMTRACE, "not sending request (at caller's "
909                                "instruction)\n");
910                         rc = LDLM_FL_LOCAL_ONLY;
911                 }
912                 ldlm_lock_cancel(lock);
913         } else {
914                 if (ns_is_client(lock->l_resource->lr_namespace)) {
915                         LDLM_ERROR(lock, "Trying to cancel local lock");
916                         LBUG();
917                 }
918                 LDLM_DEBUG(lock, "server-side local cancel");
919                 ldlm_lock_cancel(lock);
920                 ldlm_reprocess_all(lock->l_resource);
921                 LDLM_DEBUG(lock, "server-side local cancel handler END");
922         }
923
924         RETURN(rc);
925 }
926
927 /* Pack @count locks in @head into ldlm_request buffer at the offset @off,
928    of the request @req. */
929 static void ldlm_cancel_pack(struct ptlrpc_request *req, int off,
930                              struct list_head *head, int count)
931 {
932         struct ldlm_request *dlm;
933         struct ldlm_lock *lock;
934         int max, packed = 0;
935         ENTRY;
936
937         dlm = lustre_msg_buf(req->rq_reqmsg, off, sizeof(*dlm));
938         LASSERT(dlm != NULL);
939
940         /* Check the room in the request buffer. */
941         max = lustre_msg_buflen(req->rq_reqmsg, off) -
942                 sizeof(struct ldlm_request);
943         max /= sizeof(struct lustre_handle);
944         max += LDLM_LOCKREQ_HANDLES;
945         LASSERT(max >= dlm->lock_count + count);
946
947         /* XXX: it would be better to pack lock handles grouped by resource.
948          * so that the server cancel would call filter_lvbo_update() less
949          * frequently. */
950         list_for_each_entry(lock, head, l_bl_ast) {
951                 if (!count--)
952                         break;
953                 LASSERT(lock->l_conn_export);
954                 /* Pack the lock handle to the given request buffer. */
955                 LDLM_DEBUG(lock, "packing");
956                 dlm->lock_handle[dlm->lock_count++] = lock->l_remote_handle;
957                 packed++;
958         }
959         CDEBUG(D_DLMTRACE, "%d locks packed\n", packed);
960         EXIT;
961 }
962
963 /* Prepare and send a batched cancel rpc, it will include count lock handles
964  * of locks given in @head. */
965 int ldlm_cli_cancel_req(struct obd_export *exp,
966                         struct list_head *cancels, int count)
967 {
968         struct ptlrpc_request *req = NULL;
969         __u32 size[2] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
970                         [DLM_LOCKREQ_OFF]     = sizeof(struct ldlm_request) };
971         struct obd_import *imp;
972         int free, sent = 0;
973         int rc = 0;
974         ENTRY;
975
976         LASSERT(exp != NULL);
977         LASSERT(count > 0);
978
979         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_PAUSE_CANCEL, obd_fail_val);
980
981         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_RACE))
982                 RETURN(count);
983
984         free = ldlm_req_handles_avail(exp, size, 2, 0);
985         if (count > free)
986                 count = free;
987
988         size[DLM_LOCKREQ_OFF] = ldlm_request_bufsize(count, LDLM_CANCEL);
989         while (1) {
990                 imp = class_exp2cliimp(exp);
991                 if (imp == NULL || imp->imp_invalid) {
992                         CDEBUG(D_DLMTRACE,
993                                "skipping cancel on invalid import %p\n", imp);
994                         RETURN(count);
995                 }
996
997                 req = ptlrpc_prep_req(imp, LUSTRE_DLM_VERSION, LDLM_CANCEL, 2,
998                                       size, NULL);
999                 if (!req)
1000                         GOTO(out, rc = -ENOMEM);
1001
1002                 req->rq_no_resend = 1;
1003                 req->rq_no_delay = 1;
1004
1005                 req->rq_request_portal = LDLM_CANCEL_REQUEST_PORTAL;
1006                 req->rq_reply_portal = LDLM_CANCEL_REPLY_PORTAL;
1007                 ptlrpc_at_set_req_timeout(req);
1008
1009                 /*
1010                 body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF,
1011                                       sizeof(*body));
1012                 */
1013                 ldlm_cancel_pack(req, DLM_LOCKREQ_OFF, cancels, count);
1014
1015                 ptlrpc_req_set_repsize(req, 1, NULL);
1016                 rc = ptlrpc_queue_wait(req);
1017
1018                 if (rc == ESTALE) {
1019                         CDEBUG(D_DLMTRACE, "client/server (nid %s) "
1020                                "out of sync -- not fatal\n",
1021                                libcfs_nid2str(req->rq_import->
1022                                               imp_connection->c_peer.nid));
1023                         rc = 0;
1024                 } else if (rc == -ETIMEDOUT && /* check there was no reconnect*/
1025                            req->rq_import_generation == imp->imp_generation) {
1026                         ptlrpc_req_finished(req);
1027                         continue;
1028                 } else if (rc != ELDLM_OK) {
1029                         CERROR("Got rc %d from cancel RPC: canceling "
1030                                "anyway\n", rc);
1031                         break;
1032                 }
1033                 sent = count;
1034                 break;
1035         }
1036
1037         ptlrpc_req_finished(req);
1038         EXIT;
1039 out:
1040         return sent ? sent : rc;
1041 }
1042
1043 static inline struct ldlm_pool *ldlm_imp2pl(struct obd_import *imp)
1044 {
1045         LASSERT(imp != NULL);
1046         return &imp->imp_obd->obd_namespace->ns_pool;
1047 }
1048
1049 int ldlm_cli_update_pool(struct ptlrpc_request *req)
1050 {
1051         struct obd_device *obd;
1052         __u64 old_slv, new_slv;
1053         __u32 new_limit;
1054         ENTRY;
1055
1056         if (unlikely(!req->rq_import || !req->rq_import->imp_obd ||
1057                      !imp_connect_lru_resize(req->rq_import)))
1058         {
1059                 /*
1060                  * Do nothing for corner cases.
1061                  */
1062                 RETURN(0);
1063         }
1064
1065         /*
1066          * In some cases RPC may contain slv and limit zeroed out. This is
1067          * the case when server does not support lru resize feature. This is
1068          * also possible in some recovery cases when server side reqs have no
1069          * ref to obd export and thus access to server side namespace is no
1070          * possible.
1071          */
1072         if (lustre_msg_get_slv(req->rq_repmsg) == 0 ||
1073             lustre_msg_get_limit(req->rq_repmsg) == 0) {
1074                 DEBUG_REQ(D_HA, req, "Zero SLV or Limit found "
1075                           "(SLV: "LPU64", Limit: %u)",
1076                           lustre_msg_get_slv(req->rq_repmsg),
1077                           lustre_msg_get_limit(req->rq_repmsg));
1078                 RETURN(0);
1079         }
1080
1081         new_limit = lustre_msg_get_limit(req->rq_repmsg);
1082         new_slv = lustre_msg_get_slv(req->rq_repmsg);
1083         obd = req->rq_import->imp_obd;
1084
1085         /*
1086          * Set new SLV and Limit to obd fields to make accessible for pool
1087          * thread. We do not access obd_namespace and pool directly here
1088          * as there is no reliable way to make sure that they are still
1089          * alive in cleanup time. Evil races are possible which may cause
1090          * oops in that time.
1091          */
1092         write_lock(&obd->obd_pool_lock);
1093         old_slv = obd->obd_pool_slv;
1094         obd->obd_pool_slv = new_slv;
1095         obd->obd_pool_limit = new_limit;
1096         write_unlock(&obd->obd_pool_lock);
1097
1098         RETURN(0);
1099 }
1100 EXPORT_SYMBOL(ldlm_cli_update_pool);
1101
1102 int ldlm_cli_cancel(struct lustre_handle *lockh)
1103 {
1104         struct ldlm_namespace *ns;
1105         int avail, flags, count = 1, rc = 0;
1106         struct ldlm_lock *lock;
1107         CFS_LIST_HEAD(cancels);
1108         ENTRY;
1109
1110         /* concurrent cancels on the same handle can happen */
1111         lock = __ldlm_handle2lock(lockh, LDLM_FL_CANCELING);
1112         if (lock == NULL) {
1113                 LDLM_DEBUG_NOLOCK("lock is already being destroyed\n");
1114                 RETURN(0);
1115         }
1116
1117         rc = ldlm_cli_cancel_local(lock);
1118         if (rc < 0 || rc == LDLM_FL_LOCAL_ONLY) {
1119                 LDLM_LOCK_PUT(lock);
1120                 RETURN(rc < 0 ? rc : 0);
1121         }
1122         /* Even if the lock is marked as LDLM_FL_BL_AST, this is a LDLM_CANCEL
1123          * rpc which goes to canceld portal, so we can cancel other lru locks
1124          * here and send them all as one LDLM_CANCEL rpc. */
1125         LASSERT(list_empty(&lock->l_bl_ast));
1126         list_add(&lock->l_bl_ast, &cancels);
1127
1128         if (exp_connect_cancelset(lock->l_conn_export)) {
1129                 avail = ldlm_cancel_handles_avail(lock->l_conn_export);
1130                 LASSERT(avail > 0);
1131
1132                 ns = lock->l_resource->lr_namespace;
1133                 flags = ns_connect_lru_resize(ns) ?
1134                         LDLM_CANCEL_LRUR : LDLM_CANCEL_AGED;
1135                 count += ldlm_cancel_lru_local(ns, &cancels, 0, avail - 1,
1136                                                LDLM_FL_BL_AST, flags);
1137         }
1138         ldlm_cli_cancel_list(&cancels, count, NULL, 0);
1139         RETURN(0);
1140 }
1141
1142 /* XXX until we will have compound requests and can cut cancels from generic rpc
1143  * we need send cancels with LDLM_FL_BL_AST flag as separate rpc */
1144 static int ldlm_cancel_list(struct list_head *cancels, int count, int flags)
1145 {
1146         CFS_LIST_HEAD(head);
1147         struct ldlm_lock *lock, *next;
1148         int left = 0, bl_ast = 0, rc;
1149
1150         left = count;
1151         list_for_each_entry_safe(lock, next, cancels, l_bl_ast) {
1152                 if (left-- == 0)
1153                         break;
1154
1155                 if (flags & LDLM_FL_LOCAL_ONLY) {
1156                         rc = LDLM_FL_LOCAL_ONLY;
1157                         ldlm_lock_cancel(lock);
1158                 } else {
1159                         rc = ldlm_cli_cancel_local(lock);
1160                 }
1161                 if (!(flags & LDLM_FL_BL_AST) && (rc == LDLM_FL_BL_AST)) {
1162                         LDLM_DEBUG(lock, "Cancel lock separately");
1163                         list_del_init(&lock->l_bl_ast);
1164                         list_add(&lock->l_bl_ast, &head);
1165                         bl_ast ++;
1166                         continue;
1167                 }
1168                 if (rc == LDLM_FL_LOCAL_ONLY) {
1169                         /* CANCEL RPC should not be sent to server. */
1170                         list_del_init(&lock->l_bl_ast);
1171                         LDLM_LOCK_PUT(lock);
1172                         count--;
1173                 }
1174
1175         }
1176         if (bl_ast > 0) {
1177                 count -= bl_ast;
1178                 ldlm_cli_cancel_list(&head, bl_ast, NULL, 0);
1179         }
1180
1181         RETURN(count);
1182 }
1183
1184 /* Return 1 to stop lru processing and keep current lock cached. Return zero
1185  * otherwise. */
1186 static ldlm_policy_res_t ldlm_cancel_lrur_policy(struct ldlm_namespace *ns,
1187                                                  struct ldlm_lock *lock,
1188                                                  int unused, int added,
1189                                                  int count)
1190 {
1191         cfs_time_t cur = cfs_time_current();
1192         struct ldlm_pool *pl = &ns->ns_pool;
1193         __u64 slv, lvf, lv;
1194         cfs_time_t la;
1195
1196         /* Stop lru processing when we reached passed @count or checked all
1197          * locks in lru. */
1198         if (count && added >= count)
1199                 return LDLM_POLICY_KEEP_LOCK;
1200
1201         slv = ldlm_pool_get_slv(pl);
1202         lvf = ldlm_pool_get_lvf(pl);
1203
1204         la = cfs_duration_sec(cfs_time_sub(cur,
1205                               lock->l_last_used));
1206
1207         /* Stop when slv is not yet come from server or
1208          * lv is smaller than it is. */
1209         lv = lvf * la * unused;
1210
1211         /* Inform pool about current CLV to see it via proc. */
1212         ldlm_pool_set_clv(pl, lv);
1213         return (slv == 1 || lv < slv) ?
1214                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1215 }
1216
1217 /* Return 1 to stop lru processing and keep current lock cached. Return zero
1218  * otherwise. */
1219 static ldlm_policy_res_t ldlm_cancel_passed_policy(struct ldlm_namespace *ns,
1220                                                    struct ldlm_lock *lock,
1221                                                    int unused, int added,
1222                                                    int count)
1223 {
1224         /* Stop lru processing when we reached passed @count or checked all
1225          * locks in lru. */
1226         return (added >= count) ?
1227                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1228 }
1229
1230 /* Return 1 to stop lru processing and keep current lock cached. Return zero
1231  * otherwise. */
1232 static ldlm_policy_res_t ldlm_cancel_aged_policy(struct ldlm_namespace *ns,
1233                                                  struct ldlm_lock *lock,
1234                                                  int unused, int added,
1235                                                  int count)
1236 {
1237         /* Stop lru processing if young lock is found and we reached passed
1238          * @count. */
1239         return ((added >= count) &&
1240                 cfs_time_before(cfs_time_current(),
1241                                 cfs_time_add(lock->l_last_used,
1242                                              ns->ns_max_age))) ?
1243                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1244 }
1245
1246 /* Return 1 to stop lru processing and keep current lock cached. Return zero
1247  * otherwise. */
1248 static ldlm_policy_res_t ldlm_cancel_default_policy(struct ldlm_namespace *ns,
1249                                                     struct ldlm_lock *lock,
1250                                                     int unused, int added,
1251                                                     int count)
1252 {
1253         /* Stop lru processing when we reached passed @count or checked all
1254          * locks in lru. */
1255         return (added >= count) ?
1256                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1257 }
1258
1259 typedef ldlm_policy_res_t (*ldlm_cancel_lru_policy_t)(struct ldlm_namespace *,
1260                                                       struct ldlm_lock *, int,
1261                                                       int, int);
1262
1263 static ldlm_cancel_lru_policy_t
1264 ldlm_cancel_lru_policy(struct ldlm_namespace *ns, int flags)
1265 {
1266         if (ns_connect_lru_resize(ns)) {
1267                 if (flags & LDLM_CANCEL_SHRINK)
1268                         /* We kill passed number of old locks. */
1269                         return ldlm_cancel_passed_policy;
1270                 else if (flags & LDLM_CANCEL_LRUR)
1271                         return ldlm_cancel_lrur_policy;
1272                 else if (flags & LDLM_CANCEL_PASSED)
1273                         return ldlm_cancel_passed_policy;
1274         } else {
1275                 if (flags & LDLM_CANCEL_AGED)
1276                         return ldlm_cancel_aged_policy;
1277         }
1278
1279         return ldlm_cancel_default_policy;
1280 }
1281
1282 /* - Free space in lru for @count new locks,
1283  *   redundant unused locks are canceled locally;
1284  * - also cancel locally unused aged locks;
1285  * - do not cancel more than @max locks;
1286  * - GET the found locks and add them into the @cancels list.
1287  *
1288  * A client lock can be added to the l_bl_ast list only when it is
1289  * marked LDLM_FL_CANCELING. Otherwise, somebody is already doing CANCEL.
1290  * There are the following use cases: ldlm_cancel_resource_local(),
1291  * ldlm_cancel_lru_local() and ldlm_cli_cancel(), which check&set this
1292  * flag properly. As any attempt to cancel a lock rely on this flag,
1293  * l_bl_ast list is accessed later without any special locking.
1294  *
1295  * Calling policies for enabled lru resize:
1296  * ----------------------------------------
1297  * flags & LDLM_CANCEL_LRUR - use lru resize policy (SLV from server) to
1298  *                            cancel not more than @count locks;
1299  *
1300  * flags & LDLM_CANCEL_PASSED - cancel @count number of old locks (located at
1301  *                              the beginning of lru list);
1302  *
1303  * flags & LDLM_CANCEL_SHRINK - cancel not more than @count locks according to
1304  *                              memory pressre policy function;
1305  *
1306  * flags & LDLM_CANCEL_AGED -   cancel locks according to "aged policy".
1307  */
1308 int ldlm_cancel_lru_local(struct ldlm_namespace *ns, struct list_head *cancels,
1309                           int count, int max, int cancel_flags, int flags)
1310 {
1311         ldlm_cancel_lru_policy_t pf;
1312         struct ldlm_lock *lock, *next;
1313         int added = 0, unused;
1314         ENTRY;
1315
1316         spin_lock(&ns->ns_unused_lock);
1317         unused = ns->ns_nr_unused;
1318
1319         if (!ns_connect_lru_resize(ns))
1320                 count += unused - ns->ns_max_unused;
1321
1322         pf = ldlm_cancel_lru_policy(ns, flags);
1323         LASSERT(pf != NULL);
1324
1325         while (!list_empty(&ns->ns_unused_list)) {
1326                 /* For any flags, stop scanning if @max is reached. */
1327                 if (max && added >= max)
1328                         break;
1329
1330                 list_for_each_entry_safe(lock, next, &ns->ns_unused_list, l_lru){
1331                         /* No locks which got blocking requests. */
1332                         LASSERT(!(lock->l_flags & LDLM_FL_BL_AST));
1333
1334                         /* Somebody is already doing CANCEL. No need in this
1335                          * lock in lru, do not traverse it again. */
1336                         if (!(lock->l_flags & LDLM_FL_CANCELING))
1337                                 break;
1338
1339                         ldlm_lock_remove_from_lru_nolock(lock);
1340                 }
1341                 if (&lock->l_lru == &ns->ns_unused_list)
1342                         break;
1343
1344                 /* Pass the lock through the policy filter and see if it
1345                  * should stay in lru.
1346                  *
1347                  * Even for shrinker policy we stop scanning if
1348                  * we find a lock that should stay in the cache.
1349                  * We should take into account lock age anyway
1350                  * as new lock even if it is small of weight is
1351                  * valuable resource.
1352                  *
1353                  * That is, for shrinker policy we drop only
1354                  * old locks, but additionally chose them by
1355                  * their weight. Big extent locks will stay in
1356                  * the cache. */
1357                 if (pf(ns, lock, unused, added, count) == LDLM_POLICY_KEEP_LOCK)
1358                         break;
1359
1360                 LDLM_LOCK_GET(lock); /* dropped by bl thread */
1361                 spin_unlock(&ns->ns_unused_lock);
1362
1363                 lock_res_and_lock(lock);
1364                 /* Check flags again under the lock. */
1365                 if ((lock->l_flags & LDLM_FL_CANCELING) ||
1366                     (ldlm_lock_remove_from_lru(lock) == 0)) {
1367                         /* other thread is removing lock from lru or
1368                          * somebody is already doing CANCEL or
1369                          * there is a blocking request which will send
1370                          * cancel by itseft or the lock is matched
1371                          * is already not unused. */
1372                         unlock_res_and_lock(lock);
1373                         LDLM_LOCK_PUT(lock);
1374                         spin_lock(&ns->ns_unused_lock);
1375                         continue;
1376                 }
1377                 LASSERT(!lock->l_readers && !lock->l_writers);
1378
1379                 /* If we have chosen to cancel this lock voluntarily, we
1380                  * better send cancel notification to server, so that it
1381                  * frees appropriate state. This might lead to a race
1382                  * where while we are doing cancel here, server is also
1383                  * silently cancelling this lock. */
1384                 lock->l_flags &= ~LDLM_FL_CANCEL_ON_BLOCK;
1385
1386                 /* Setting the CBPENDING flag is a little misleading,
1387                  * but prevents an important race; namely, once
1388                  * CBPENDING is set, the lock can accumulate no more
1389                  * readers/writers. Since readers and writers are
1390                  * already zero here, ldlm_lock_decref() won't see
1391                  * this flag and call l_blocking_ast */
1392                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING;
1393
1394                 /* We can't re-add to l_lru as it confuses the
1395                  * refcounting in ldlm_lock_remove_from_lru() if an AST
1396                  * arrives after we drop ns_lock below. We use l_bl_ast
1397                  * and can't use l_pending_chain as it is used both on
1398                  * server and client nevertheless bug 5666 says it is
1399                  * used only on server */
1400                 LASSERT(list_empty(&lock->l_bl_ast));
1401                 list_add(&lock->l_bl_ast, cancels);
1402                 unlock_res_and_lock(lock);
1403                 spin_lock(&ns->ns_unused_lock);
1404                 added++;
1405                 unused--;
1406         }
1407         spin_unlock(&ns->ns_unused_lock);
1408         RETURN(ldlm_cancel_list(cancels, added, cancel_flags));
1409 }
1410
1411 /* when called with LDLM_ASYNC the blocking callback will be handled
1412  * in a thread and this function will return after the thread has been
1413  * asked to call the callback.  when called with LDLM_SYNC the blocking
1414  * callback will be performed in this function. */
1415 int ldlm_cancel_lru(struct ldlm_namespace *ns, int nr, ldlm_sync_t sync,
1416                     int flags)
1417 {
1418         CFS_LIST_HEAD(cancels);
1419         int count, rc;
1420         ENTRY;
1421
1422 #ifndef __KERNEL__
1423         sync = LDLM_SYNC; /* force to be sync in user space */
1424 #endif
1425         count = ldlm_cancel_lru_local(ns, &cancels, nr, 0, 0, flags);
1426         if (sync == LDLM_ASYNC) {
1427                 rc = ldlm_bl_to_thread_list(ns, NULL, &cancels, count);
1428                 if (rc == 0)
1429                         RETURN(count);
1430         }
1431
1432         /* If an error occured in ASYNC mode, or this is SYNC mode,
1433          * cancel the list. */
1434         ldlm_cli_cancel_list(&cancels, count, NULL, 0);
1435         RETURN(count);
1436 }
1437
1438 /* Find and cancel locally unused locks found on resource, matched to the
1439  * given policy, mode. GET the found locks and add them into the @cancels
1440  * list. */
1441 int ldlm_cancel_resource_local(struct ldlm_resource *res,
1442                                struct list_head *cancels,
1443                                ldlm_policy_data_t *policy,
1444                                ldlm_mode_t mode, int lock_flags,
1445                                int cancel_flags, void *opaque)
1446 {
1447         struct ldlm_lock *lock;
1448         int count = 0;
1449         ENTRY;
1450
1451         lock_res(res);
1452         list_for_each_entry(lock, &res->lr_granted, l_res_link) {
1453                 if (opaque != NULL && lock->l_ast_data != opaque) {
1454                         LDLM_ERROR(lock, "data %p doesn't match opaque %p",
1455                                    lock->l_ast_data, opaque);
1456                         //LBUG();
1457                         continue;
1458                 }
1459
1460                 if (lock->l_readers || lock->l_writers) {
1461                         if (cancel_flags & LDLM_FL_WARN) {
1462                                 LDLM_ERROR(lock, "lock in use");
1463                                 //LBUG();
1464                         }
1465                         continue;
1466                 }
1467
1468                 /* If somebody is already doing CANCEL, or blocking ast came,
1469                  * skip this lock. */
1470                 if (lock->l_flags & LDLM_FL_BL_AST ||
1471                     lock->l_flags & LDLM_FL_CANCELING)
1472                         continue;
1473
1474                 if (lockmode_compat(lock->l_granted_mode, mode))
1475                         continue;
1476
1477                 /* If policy is given and this is IBITS lock, add to list only
1478                  * those locks that match by policy. */
1479                 if (policy && (lock->l_resource->lr_type == LDLM_IBITS) &&
1480                     !(lock->l_policy_data.l_inodebits.bits &
1481                       policy->l_inodebits.bits))
1482                         continue;
1483
1484                 /* See CBPENDING comment in ldlm_cancel_lru */
1485                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING |
1486                         lock_flags;
1487
1488                 LASSERT(list_empty(&lock->l_bl_ast));
1489                 list_add(&lock->l_bl_ast, cancels);
1490                 LDLM_LOCK_GET(lock);
1491                 count++;
1492         }
1493         unlock_res(res);
1494
1495         /* Handle only @count inserted locks. */
1496         RETURN(ldlm_cancel_list(cancels, count, cancel_flags));
1497 }
1498
1499 /* If @req is NULL, send CANCEL request to server with handles of locks
1500  * in the @cancels. If EARLY_CANCEL is not supported, send CANCEL requests
1501  * separately per lock.
1502  * If @req is not NULL, put handles of locks in @cancels into the request
1503  * buffer at the offset @off.
1504  * Destroy @cancels at the end. */
1505 int ldlm_cli_cancel_list(struct list_head *cancels, int count,
1506                          struct ptlrpc_request *req, int off)
1507 {
1508         struct ldlm_lock *lock;
1509         int res = 0;
1510         ENTRY;
1511
1512         if (list_empty(cancels) || count == 0)
1513                 RETURN(0);
1514
1515         while (count) {
1516                 LASSERT(!list_empty(cancels));
1517                 lock = list_entry(cancels->next, struct ldlm_lock, l_bl_ast);
1518                 LASSERT(lock->l_conn_export);
1519
1520                 if (exp_connect_cancelset(lock->l_conn_export)) {
1521                         res = count;
1522                         if (req)
1523                                 ldlm_cancel_pack(req, off, cancels, count);
1524                         else
1525                                 res = ldlm_cli_cancel_req(lock->l_conn_export,
1526                                                           cancels, count);
1527                 } else {
1528                         res = ldlm_cli_cancel_req(lock->l_conn_export,
1529                                                   cancels, 1);
1530                 }
1531
1532                 if (res < 0) {
1533                         CERROR("ldlm_cli_cancel_list: %d\n", res);
1534                         res = count;
1535                 }
1536
1537                 count -= res;
1538                 ldlm_lock_list_put(cancels, l_bl_ast, res);
1539         }
1540         RETURN(0);
1541 }
1542
1543 static int ldlm_cli_cancel_unused_resource(struct ldlm_namespace *ns,
1544                                            struct ldlm_res_id res_id,
1545                                            int flags, void *opaque)
1546 {
1547         struct ldlm_resource *res;
1548         CFS_LIST_HEAD(cancels);
1549         int count;
1550         int rc;
1551         ENTRY;
1552
1553         res = ldlm_resource_get(ns, NULL, res_id, 0, 0);
1554         if (res == NULL) {
1555                 /* This is not a problem. */
1556                 CDEBUG(D_INFO, "No resource "LPU64"\n", res_id.name[0]);
1557                 RETURN(0);
1558         }
1559
1560         count = ldlm_cancel_resource_local(res, &cancels, NULL, LCK_MINMODE,
1561                                            0, flags, opaque);
1562         rc = ldlm_cli_cancel_list(&cancels, count, NULL, 0);
1563         if (rc != ELDLM_OK)
1564                 CERROR("ldlm_cli_cancel_unused_resource: %d\n", rc);
1565
1566         ldlm_resource_putref(res);
1567         RETURN(0);
1568 }
1569
1570 static inline int have_no_nsresource(struct ldlm_namespace *ns)
1571 {
1572         int no_resource = 0;
1573
1574         spin_lock(&ns->ns_hash_lock);
1575         if (ns->ns_resources == 0)
1576                 no_resource = 1;
1577         spin_unlock(&ns->ns_hash_lock);
1578
1579         RETURN(no_resource);
1580 }
1581
1582 /* Cancel all locks on a namespace (or a specific resource, if given)
1583  * that have 0 readers/writers.
1584  *
1585  * If flags & LDLM_FL_LOCAL_ONLY, throw the locks away without trying
1586  * to notify the server. */
1587 int ldlm_cli_cancel_unused(struct ldlm_namespace *ns,
1588                            struct ldlm_res_id *res_id, int flags, void *opaque)
1589 {
1590         int i;
1591         ENTRY;
1592
1593         if (ns == NULL)
1594                 RETURN(ELDLM_OK);
1595
1596         if (res_id)
1597                 RETURN(ldlm_cli_cancel_unused_resource(ns, *res_id, flags,
1598                                                        opaque));
1599
1600         spin_lock(&ns->ns_hash_lock);
1601         for (i = 0; i < RES_HASH_SIZE; i++) {
1602                 struct list_head *tmp;
1603                 tmp = ns->ns_hash[i].next;
1604                 while (tmp != &(ns->ns_hash[i])) {
1605                         struct ldlm_resource *res;
1606                         int rc;
1607
1608                         res = list_entry(tmp, struct ldlm_resource, lr_hash);
1609                         ldlm_resource_getref(res);
1610                         spin_unlock(&ns->ns_hash_lock);
1611
1612                         rc = ldlm_cli_cancel_unused_resource(ns, res->lr_name,
1613                                                              flags, opaque);
1614
1615                         if (rc)
1616                                 CERROR("ldlm_cli_cancel_unused ("LPU64"): %d\n",
1617                                        res->lr_name.name[0], rc);
1618
1619                         spin_lock(&ns->ns_hash_lock);
1620                         tmp = tmp->next;
1621                         ldlm_resource_putref_locked(res);
1622                 }
1623         }
1624         spin_unlock(&ns->ns_hash_lock);
1625
1626         RETURN(ELDLM_OK);
1627 }
1628
1629 /* join/split resource locks to/from lru list */
1630 int ldlm_cli_join_lru(struct ldlm_namespace *ns,
1631                       struct ldlm_res_id *res_id, int join)
1632 {
1633         struct ldlm_resource *res;
1634         struct ldlm_lock *lock, *n;
1635         int count = 0;
1636         ENTRY;
1637
1638         LASSERT(ns_is_client(ns));
1639
1640         res = ldlm_resource_get(ns, NULL, *res_id, LDLM_EXTENT, 0);
1641         if (res == NULL)
1642                 RETURN(count);
1643         LASSERT(res->lr_type == LDLM_EXTENT);
1644
1645         lock_res(res);
1646         if (!join)
1647                 goto split;
1648
1649         list_for_each_entry_safe (lock, n, &res->lr_granted, l_res_link) {
1650                 if (list_empty(&lock->l_lru) &&
1651                     !lock->l_readers && !lock->l_writers &&
1652                     !(lock->l_flags & LDLM_FL_LOCAL) &&
1653                     !(lock->l_flags & LDLM_FL_CBPENDING) &&
1654                     !(lock->l_flags & LDLM_FL_BL_AST)) {
1655                         ldlm_lock_add_to_lru(lock);
1656                         lock->l_flags &= ~LDLM_FL_NO_LRU;
1657                         LDLM_DEBUG(lock, "join lock to lru");
1658                         count++;
1659                 }
1660         }
1661         goto unlock;
1662 split:
1663         spin_lock(&ns->ns_unused_lock);
1664         list_for_each_entry_safe (lock, n, &ns->ns_unused_list, l_lru) {
1665                 if (lock->l_resource == res) {
1666                         ldlm_lock_remove_from_lru_nolock(lock);
1667                         lock->l_flags |= LDLM_FL_NO_LRU;
1668                         LDLM_DEBUG(lock, "split lock from lru");
1669                         count++;
1670                 }
1671         }
1672         spin_unlock(&ns->ns_unused_lock);
1673 unlock:
1674         unlock_res(res);
1675         ldlm_resource_putref(res);
1676         RETURN(count);
1677 }
1678
1679 /* Lock iterators. */
1680
1681 int ldlm_resource_foreach(struct ldlm_resource *res, ldlm_iterator_t iter,
1682                           void *closure)
1683 {
1684         struct list_head *tmp, *next;
1685         struct ldlm_lock *lock;
1686         int rc = LDLM_ITER_CONTINUE;
1687
1688         ENTRY;
1689
1690         if (!res)
1691                 RETURN(LDLM_ITER_CONTINUE);
1692
1693         lock_res(res);
1694         list_for_each_safe(tmp, next, &res->lr_granted) {
1695                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1696
1697                 if (iter(lock, closure) == LDLM_ITER_STOP)
1698                         GOTO(out, rc = LDLM_ITER_STOP);
1699         }
1700
1701         list_for_each_safe(tmp, next, &res->lr_converting) {
1702                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1703
1704                 if (iter(lock, closure) == LDLM_ITER_STOP)
1705                         GOTO(out, rc = LDLM_ITER_STOP);
1706         }
1707
1708         list_for_each_safe(tmp, next, &res->lr_waiting) {
1709                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1710
1711                 if (iter(lock, closure) == LDLM_ITER_STOP)
1712                         GOTO(out, rc = LDLM_ITER_STOP);
1713         }
1714  out:
1715         unlock_res(res);
1716         RETURN(rc);
1717 }
1718
1719 struct iter_helper_data {
1720         ldlm_iterator_t iter;
1721         void *closure;
1722 };
1723
1724 static int ldlm_iter_helper(struct ldlm_lock *lock, void *closure)
1725 {
1726         struct iter_helper_data *helper = closure;
1727         return helper->iter(lock, helper->closure);
1728 }
1729
1730 static int ldlm_res_iter_helper(struct ldlm_resource *res, void *closure)
1731 {
1732         return ldlm_resource_foreach(res, ldlm_iter_helper, closure);
1733 }
1734
1735 int ldlm_namespace_foreach(struct ldlm_namespace *ns, ldlm_iterator_t iter,
1736                            void *closure)
1737 {
1738         struct iter_helper_data helper = { iter: iter, closure: closure };
1739         return ldlm_namespace_foreach_res(ns, ldlm_res_iter_helper, &helper);
1740 }
1741
1742 int ldlm_namespace_foreach_res(struct ldlm_namespace *ns,
1743                                ldlm_res_iterator_t iter, void *closure)
1744 {
1745         int i, rc = LDLM_ITER_CONTINUE;
1746         struct ldlm_resource *res;
1747         struct list_head *tmp;
1748
1749         ENTRY;
1750         spin_lock(&ns->ns_hash_lock);
1751         for (i = 0; i < RES_HASH_SIZE; i++) {
1752                 tmp = ns->ns_hash[i].next;
1753                 while (tmp != &(ns->ns_hash[i])) {
1754                         res = list_entry(tmp, struct ldlm_resource, lr_hash);
1755                         ldlm_resource_getref(res);
1756                         spin_unlock(&ns->ns_hash_lock);
1757
1758                         rc = iter(res, closure);
1759
1760                         spin_lock(&ns->ns_hash_lock);
1761                         tmp = tmp->next;
1762                         ldlm_resource_putref_locked(res);
1763                         if (rc == LDLM_ITER_STOP)
1764                                 GOTO(out, rc);
1765                 }
1766         }
1767  out:
1768         spin_unlock(&ns->ns_hash_lock);
1769         RETURN(rc);
1770 }
1771
1772 /* non-blocking function to manipulate a lock whose cb_data is being put away.*/
1773 void ldlm_resource_iterate(struct ldlm_namespace *ns, struct ldlm_res_id *res_id,
1774                            ldlm_iterator_t iter, void *data)
1775 {
1776         struct ldlm_resource *res;
1777         ENTRY;
1778
1779         if (ns == NULL) {
1780                 CERROR("must pass in namespace\n");
1781                 LBUG();
1782         }
1783
1784         res = ldlm_resource_get(ns, NULL, *res_id, 0, 0);
1785         if (res == NULL) {
1786                 EXIT;
1787                 return;
1788         }
1789
1790         ldlm_resource_foreach(res, iter, data);
1791         ldlm_resource_putref(res);
1792         EXIT;
1793 }
1794
1795 /* Lock replay */
1796
1797 static int ldlm_chain_lock_for_replay(struct ldlm_lock *lock, void *closure)
1798 {
1799         struct list_head *list = closure;
1800
1801         /* we use l_pending_chain here, because it's unused on clients. */
1802         LASSERTF(list_empty(&lock->l_pending_chain),"lock %p next %p prev %p\n",
1803                  lock, &lock->l_pending_chain.next,&lock->l_pending_chain.prev);
1804         /* bug 9573: don't replay locks left after eviction, or
1805          * bug 17614: locks being actively cancelled. Get a reference
1806          * on a lock so that it does not disapear under us (e.g. due to cancel)
1807          */
1808         if (!(lock->l_flags & (LDLM_FL_FAILED|LDLM_FL_CANCELING))) {
1809                 list_add(&lock->l_pending_chain, list);
1810                 LDLM_LOCK_GET(lock);
1811         }
1812
1813         return LDLM_ITER_CONTINUE;
1814 }
1815
1816 static int replay_lock_interpret(struct ptlrpc_request *req,
1817                                  struct ldlm_async_args *aa, int rc)
1818 {
1819         struct lustre_handle  old_hash_key;
1820         struct ldlm_lock     *lock;
1821         struct ldlm_reply    *reply;
1822         struct obd_export    *exp;
1823
1824         ENTRY;
1825         atomic_dec(&req->rq_import->imp_replay_inflight);
1826         if (rc != ELDLM_OK)
1827                 GOTO(out, rc);
1828
1829         reply = lustre_swab_repbuf(req, DLM_LOCKREPLY_OFF, sizeof(*reply),
1830                                    lustre_swab_ldlm_reply);
1831         if (reply == NULL) {
1832                 CERROR("Can't unpack ldlm_reply\n");
1833                 GOTO (out, rc = -EPROTO);
1834         }
1835
1836         lock = ldlm_handle2lock(&aa->lock_handle);
1837         if (!lock) {
1838                 CERROR("received replay ack for unknown local cookie "LPX64
1839                        " remote cookie "LPX64 " from server %s id %s\n",
1840                        aa->lock_handle.cookie, reply->lock_handle.cookie,
1841                        req->rq_export->exp_client_uuid.uuid,
1842                        libcfs_id2str(req->rq_peer));
1843                 GOTO(out, rc = -ESTALE);
1844         }
1845
1846         old_hash_key = lock->l_remote_handle;
1847         lock->l_remote_handle = reply->lock_handle;
1848
1849         /* Key change rehash lock in per-export hash with new key */
1850         exp = req->rq_export;
1851         if (exp && exp->exp_lock_hash)
1852                 lustre_hash_rehash_key(exp->exp_lock_hash, &old_hash_key,
1853                                        &lock->l_remote_handle,
1854                                        &lock->l_exp_hash);
1855
1856         LDLM_DEBUG(lock, "replayed lock:");
1857         ptlrpc_import_recovery_state_machine(req->rq_import);
1858         LDLM_LOCK_PUT(lock);
1859 out:
1860         if (rc != ELDLM_OK)
1861                 ptlrpc_connect_import(req->rq_import, NULL);
1862
1863
1864         RETURN(rc);
1865 }
1866
1867 static int replay_one_lock(struct obd_import *imp, struct ldlm_lock *lock)
1868 {
1869         struct ptlrpc_request *req;
1870         struct ldlm_request *body;
1871         struct ldlm_reply *reply;
1872         struct ldlm_async_args *aa;
1873         int buffers = 2;
1874         __u32 size[3] = { sizeof(struct ptlrpc_body) };
1875         int flags;
1876         ENTRY;
1877
1878
1879         /* Bug 11974: Do not replay a lock which is actively being canceled */
1880         if (lock->l_flags & LDLM_FL_CANCELING) {
1881                 LDLM_DEBUG(lock, "Not replaying canceled lock:");
1882                 RETURN(0);
1883         }
1884
1885         /* If this is reply-less callback lock, we cannot replay it, since
1886          * server might have long dropped it, but notification of that event was
1887          * lost by network. (and server granted conflicting lock already) */
1888         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1889                 LDLM_DEBUG(lock, "Not replaying reply-less lock:");
1890                 ldlm_lock_cancel(lock);
1891                 RETURN(0);
1892         }
1893
1894         /*
1895          * If granted mode matches the requested mode, this lock is granted.
1896          *
1897          * If they differ, but we have a granted mode, then we were granted
1898          * one mode and now want another: ergo, converting.
1899          *
1900          * If we haven't been granted anything and are on a resource list,
1901          * then we're blocked/waiting.
1902          *
1903          * If we haven't been granted anything and we're NOT on a resource list,
1904          * then we haven't got a reply yet and don't have a known disposition.
1905          * This happens whenever a lock enqueue is the request that triggers
1906          * recovery.
1907          */
1908         if (lock->l_granted_mode == lock->l_req_mode)
1909                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_GRANTED;
1910         else if (lock->l_granted_mode)
1911                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_CONV;
1912         else if (!list_empty(&lock->l_res_link))
1913                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_WAIT;
1914         else
1915                 flags = LDLM_FL_REPLAY;
1916
1917         size[DLM_LOCKREQ_OFF] = sizeof(*body);
1918         req = ptlrpc_prep_req(imp, LUSTRE_DLM_VERSION, LDLM_ENQUEUE, 2, size,
1919                               NULL);
1920         if (!req)
1921                 RETURN(-ENOMEM);
1922
1923         /* We're part of recovery, so don't wait for it. */
1924         req->rq_send_state = LUSTRE_IMP_REPLAY_LOCKS;
1925
1926         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
1927         ldlm_lock2desc(lock, &body->lock_desc);
1928         body->lock_flags = flags;
1929
1930         ldlm_lock2handle(lock, &body->lock_handle[0]);
1931         size[DLM_LOCKREPLY_OFF] = sizeof(*reply);
1932         buffers = 3;
1933         if (lock->l_lvb_len != 0) {
1934                 size[DLM_REPLY_REC_OFF] = lock->l_lvb_len;
1935         } else
1936                 size[DLM_REPLY_REC_OFF] = sizeof (struct ost_lvb);
1937         ptlrpc_req_set_repsize(req, buffers, size);
1938
1939         LDLM_DEBUG(lock, "replaying lock:");
1940
1941         atomic_inc(&req->rq_import->imp_replay_inflight);
1942         CLASSERT(sizeof(*aa) <= sizeof(req->rq_async_args));
1943         aa = ptlrpc_req_async_args(req);
1944         aa->lock_handle = body->lock_handle[0];
1945         req->rq_interpret_reply = replay_lock_interpret;
1946         ptlrpcd_add_req(req);
1947
1948         RETURN(0);
1949 }
1950
1951 int ldlm_replay_locks(struct obd_import *imp)
1952 {
1953         struct ldlm_namespace *ns = imp->imp_obd->obd_namespace;
1954         struct list_head list;
1955         struct ldlm_lock *lock, *next;
1956         int rc = 0;
1957
1958         ENTRY;
1959         CFS_INIT_LIST_HEAD(&list);
1960
1961         LASSERT(atomic_read(&imp->imp_replay_inflight) == 0);
1962
1963         /* ensure this doesn't fall to 0 before all have been queued */
1964         atomic_inc(&imp->imp_replay_inflight);
1965
1966         if (imp->imp_no_lock_replay) {
1967                 /* VBR: locks should be cancelled here */
1968                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
1969                 spin_lock(&imp->imp_lock);
1970                 imp->imp_no_lock_replay = 0;
1971                 spin_unlock(&imp->imp_lock);
1972         } else {
1973                 (void)ldlm_namespace_foreach(ns, ldlm_chain_lock_for_replay,
1974                                              &list);
1975                 list_for_each_entry_safe(lock, next, &list, l_pending_chain) {
1976                         list_del_init(&lock->l_pending_chain);
1977                         if (rc) {
1978                                 LDLM_LOCK_PUT(lock);
1979                                 continue; /* or try to do the rest? */
1980                         }
1981                         rc = replay_one_lock(imp, lock);
1982                         LDLM_LOCK_PUT(lock);
1983                 }
1984         }
1985         atomic_dec(&imp->imp_replay_inflight);
1986
1987         RETURN(rc);
1988 }