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