Whamcloud - gitweb
- lost #define changes from 1_6
[fs/lustre-release.git] / lustre / ldlm / ldlm_lib.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  *  Copyright (c) 2003 Cluster File Systems, Inc.
5  *
6  *   This file is part of the Lustre file system, http://www.lustre.org
7  *   Lustre is a trademark of Cluster File Systems, Inc.
8  *
9  *   You may have signed or agreed to another license before downloading
10  *   this software.  If so, you are bound by the terms and conditions
11  *   of that agreement, and the following does not apply to you.  See the
12  *   LICENSE file included with this distribution for more information.
13  *
14  *   If you did not agree to a different license, then this copy of Lustre
15  *   is open source software; you can redistribute it and/or modify it
16  *   under the terms of version 2 of the GNU General Public License as
17  *   published by the Free Software Foundation.
18  *
19  *   In either case, Lustre is distributed in the hope that it will be
20  *   useful, but WITHOUT ANY WARRANTY; without even the implied warranty
21  *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  *   license text for more details.
23  */
24
25 #ifndef EXPORT_SYMTAB
26 # define EXPORT_SYMTAB
27 #endif
28 #define DEBUG_SUBSYSTEM S_LDLM
29
30 #ifdef __KERNEL__
31 # include <libcfs/libcfs.h>
32 #else
33 # include <liblustre.h>
34 #endif
35 #include <obd.h>
36 #include <lustre_mds.h>
37 #include <lustre_dlm.h>
38 #include <lustre_net.h>
39 #include <lustre_sec.h>
40
41 /* @priority: if non-zero, move the selected to the list head
42  * @create: if zero, only search in existed connections
43  */
44 static int import_set_conn(struct obd_import *imp, struct obd_uuid *uuid,
45                            int priority, int create)
46 {
47         struct ptlrpc_connection *ptlrpc_conn;
48         struct obd_import_conn *imp_conn = NULL, *item;
49         int rc = 0;
50         ENTRY;
51
52         if (!create && !priority) {
53                 CDEBUG(D_HA, "Nothing to do\n");
54                 RETURN(-EINVAL);
55         }
56
57         ptlrpc_conn = ptlrpc_uuid_to_connection(uuid);
58         if (!ptlrpc_conn) {
59                 CDEBUG(D_HA, "can't find connection %s\n", uuid->uuid);
60                 RETURN (-ENOENT);
61         }
62
63         if (create) {
64                 OBD_ALLOC(imp_conn, sizeof(*imp_conn));
65                 if (!imp_conn) {
66                         GOTO(out_put, rc = -ENOMEM);
67                 }
68         }
69
70         spin_lock(&imp->imp_lock);
71         list_for_each_entry(item, &imp->imp_conn_list, oic_item) {
72                 if (obd_uuid_equals(uuid, &item->oic_uuid)) {
73                         if (priority) {
74                                 list_del(&item->oic_item);
75                                 list_add(&item->oic_item, &imp->imp_conn_list);
76                                 item->oic_last_attempt = 0;
77                         }
78                         CDEBUG(D_HA, "imp %p@%s: found existing conn %s%s\n",
79                                imp, imp->imp_obd->obd_name, uuid->uuid,
80                                (priority ? ", moved to head" : ""));
81                         spin_unlock(&imp->imp_lock);
82                         GOTO(out_free, rc = 0);
83                 }
84         }
85         /* not found */
86         if (create) {
87                 imp_conn->oic_conn = ptlrpc_conn;
88                 imp_conn->oic_uuid = *uuid;
89                 item->oic_last_attempt = 0;
90                 if (priority)
91                         list_add(&imp_conn->oic_item, &imp->imp_conn_list);
92                 else
93                         list_add_tail(&imp_conn->oic_item, &imp->imp_conn_list);
94                 CDEBUG(D_HA, "imp %p@%s: add connection %s at %s\n",
95                        imp, imp->imp_obd->obd_name, uuid->uuid,
96                        (priority ? "head" : "tail"));
97         } else {
98                 spin_unlock(&imp->imp_lock);
99                 GOTO(out_free, rc = -ENOENT);
100         }
101
102         spin_unlock(&imp->imp_lock);
103         RETURN(0);
104 out_free:
105         if (imp_conn)
106                 OBD_FREE(imp_conn, sizeof(*imp_conn));
107 out_put:
108         ptlrpc_put_connection(ptlrpc_conn);
109         RETURN(rc);
110 }
111
112 int import_set_conn_priority(struct obd_import *imp, struct obd_uuid *uuid)
113 {
114         return import_set_conn(imp, uuid, 1, 0);
115 }
116
117 int client_import_add_conn(struct obd_import *imp, struct obd_uuid *uuid,
118                            int priority)
119 {
120         return import_set_conn(imp, uuid, priority, 1);
121 }
122
123 int client_import_del_conn(struct obd_import *imp, struct obd_uuid *uuid)
124 {
125         struct obd_import_conn *imp_conn;
126         struct obd_export *dlmexp;
127         int rc = -ENOENT;
128         ENTRY;
129
130         spin_lock(&imp->imp_lock);
131         if (list_empty(&imp->imp_conn_list)) {
132                 LASSERT(!imp->imp_connection);
133                 GOTO(out, rc);
134         }
135
136         list_for_each_entry(imp_conn, &imp->imp_conn_list, oic_item) {
137                 if (!obd_uuid_equals(uuid, &imp_conn->oic_uuid))
138                         continue;
139                 LASSERT(imp_conn->oic_conn);
140
141                 /* is current conn? */
142                 if (imp_conn == imp->imp_conn_current) {
143                         LASSERT(imp_conn->oic_conn == imp->imp_connection);
144
145                         if (imp->imp_state != LUSTRE_IMP_CLOSED &&
146                             imp->imp_state != LUSTRE_IMP_DISCON) {
147                                 CERROR("can't remove current connection\n");
148                                 GOTO(out, rc = -EBUSY);
149                         }
150
151                         ptlrpc_put_connection(imp->imp_connection);
152                         imp->imp_connection = NULL;
153
154                         dlmexp = class_conn2export(&imp->imp_dlm_handle);
155                         if (dlmexp && dlmexp->exp_connection) {
156                                 LASSERT(dlmexp->exp_connection ==
157                                         imp_conn->oic_conn);
158                                 ptlrpc_put_connection(dlmexp->exp_connection);
159                                 dlmexp->exp_connection = NULL;
160                         }
161                 }
162
163                 list_del(&imp_conn->oic_item);
164                 ptlrpc_put_connection(imp_conn->oic_conn);
165                 OBD_FREE(imp_conn, sizeof(*imp_conn));
166                 CDEBUG(D_HA, "imp %p@%s: remove connection %s\n",
167                        imp, imp->imp_obd->obd_name, uuid->uuid);
168                 rc = 0;
169                 break;
170         }
171 out:
172         spin_unlock(&imp->imp_lock);
173         if (rc == -ENOENT)
174                 CERROR("connection %s not found\n", uuid->uuid);
175         RETURN(rc);
176 }
177
178 static void destroy_import(struct obd_import *imp)
179 {
180         /* drop security policy instance after all rpc finished/aborted
181          * to let all busy credentials be released.
182          */
183         class_import_get(imp);
184         class_destroy_import(imp);
185         sptlrpc_import_put_sec(imp);
186         class_import_put(imp);
187 }
188
189 /* configure an RPC client OBD device
190  *
191  * lcfg parameters:
192  * 1 - client UUID
193  * 2 - server UUID
194  * 3 - inactive-on-startup
195  */
196 int client_obd_setup(struct obd_device *obddev, struct lustre_cfg *lcfg)
197 {
198         struct client_obd *cli = &obddev->u.cli;
199         struct obd_import *imp;
200         struct obd_uuid server_uuid;
201         int rq_portal, rp_portal, connect_op;
202         char *name = obddev->obd_type->typ_name;
203         int rc;
204         ENTRY;
205
206         /* In a more perfect world, we would hang a ptlrpc_client off of
207          * obd_type and just use the values from there. */
208         if (!strcmp(name, LUSTRE_OSC_NAME)) {
209                 rq_portal = OST_REQUEST_PORTAL;
210                 rp_portal = OSC_REPLY_PORTAL;
211                 connect_op = OST_CONNECT;
212         } else if (!strcmp(name, LUSTRE_MDC_NAME)) {
213                 rq_portal = MDS_REQUEST_PORTAL;
214                 rp_portal = MDC_REPLY_PORTAL;
215                 connect_op = MDS_CONNECT;
216         } else if (!strcmp(name, LUSTRE_MGC_NAME)) {
217                 rq_portal = MGS_REQUEST_PORTAL;
218                 rp_portal = MGC_REPLY_PORTAL;
219                 connect_op = MGS_CONNECT;
220         } else {
221                 CERROR("unknown client OBD type \"%s\", can't setup\n",
222                        name);
223                 RETURN(-EINVAL);
224         }
225
226         if (LUSTRE_CFG_BUFLEN(lcfg, 1) < 1) {
227                 CERROR("requires a TARGET UUID\n");
228                 RETURN(-EINVAL);
229         }
230
231         if (LUSTRE_CFG_BUFLEN(lcfg, 1) > 37) {
232                 CERROR("client UUID must be less than 38 characters\n");
233                 RETURN(-EINVAL);
234         }
235
236         if (LUSTRE_CFG_BUFLEN(lcfg, 2) < 1) {
237                 CERROR("setup requires a SERVER UUID\n");
238                 RETURN(-EINVAL);
239         }
240
241         if (LUSTRE_CFG_BUFLEN(lcfg, 2) > 37) {
242                 CERROR("target UUID must be less than 38 characters\n");
243                 RETURN(-EINVAL);
244         }
245
246         sema_init(&cli->cl_sem, 1);
247         sema_init(&cli->cl_mgc_sem, 1);
248         cli->cl_sec_conf.sfc_rpc_flavor = SPTLRPC_FLVR_NULL;
249         cli->cl_sec_conf.sfc_bulk_csum = BULK_CSUM_ALG_NULL;
250         cli->cl_sec_conf.sfc_bulk_priv = BULK_PRIV_ALG_NULL;
251         cli->cl_sec_conf.sfc_flags = 0;
252         cli->cl_conn_count = 0;
253         memcpy(server_uuid.uuid, lustre_cfg_buf(lcfg, 2),
254                min_t(unsigned int, LUSTRE_CFG_BUFLEN(lcfg, 2),
255                      sizeof(server_uuid)));
256
257         cli->cl_dirty = 0;
258         cli->cl_avail_grant = 0;
259         /* FIXME: should limit this for the sum of all cl_dirty_max */
260         cli->cl_dirty_max = OSC_MAX_DIRTY_DEFAULT * 1024 * 1024;
261         if (cli->cl_dirty_max >> CFS_PAGE_SHIFT > num_physpages / 8)
262                 cli->cl_dirty_max = num_physpages << (CFS_PAGE_SHIFT - 3);
263         CFS_INIT_LIST_HEAD(&cli->cl_cache_waiters);
264         CFS_INIT_LIST_HEAD(&cli->cl_loi_ready_list);
265         CFS_INIT_LIST_HEAD(&cli->cl_loi_write_list);
266         CFS_INIT_LIST_HEAD(&cli->cl_loi_read_list);
267         client_obd_list_lock_init(&cli->cl_loi_list_lock);
268         cli->cl_r_in_flight = 0;
269         cli->cl_w_in_flight = 0;
270
271         spin_lock_init(&cli->cl_read_rpc_hist.oh_lock);
272         spin_lock_init(&cli->cl_write_rpc_hist.oh_lock);
273         spin_lock_init(&cli->cl_read_page_hist.oh_lock);
274         spin_lock_init(&cli->cl_write_page_hist.oh_lock);
275         spin_lock_init(&cli->cl_read_offset_hist.oh_lock);
276         spin_lock_init(&cli->cl_write_offset_hist.oh_lock);
277 #ifdef ENABLE_CHECKSUM
278         cli->cl_checksum = 1;
279 #endif
280         atomic_set(&cli->cl_resends, OSC_DEFAULT_RESENDS);
281
282         /* This value may be changed at connect time in
283            ptlrpc_connect_interpret. */
284         cli->cl_max_pages_per_rpc = min((int)PTLRPC_MAX_BRW_PAGES,
285                                         (int)(1024 * 1024 >> CFS_PAGE_SHIFT));
286
287         if (!strcmp(name, LUSTRE_MDC_NAME)) {
288                 cli->cl_max_rpcs_in_flight = MDC_MAX_RIF_DEFAULT;
289         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 128 /* MB */) {
290                 cli->cl_max_rpcs_in_flight = 2;
291         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 256 /* MB */) {
292                 cli->cl_max_rpcs_in_flight = 3;
293         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 512 /* MB */) {
294                 cli->cl_max_rpcs_in_flight = 4;
295         } else {
296                 cli->cl_max_rpcs_in_flight = OSC_MAX_RIF_DEFAULT;
297         }
298
299         rc = ldlm_get_ref(LDLM_NAMESPACE_CLIENT);
300         if (rc) {
301                 CERROR("ldlm_get_ref failed: %d\n", rc);
302                 GOTO(err, rc);
303         }
304
305         ptlrpc_init_client(rq_portal, rp_portal, name,
306                            &obddev->obd_ldlm_client);
307
308         imp = class_new_import(obddev);
309         if (imp == NULL)
310                 GOTO(err_ldlm, rc = -ENOENT);
311         imp->imp_client = &obddev->obd_ldlm_client;
312         imp->imp_connect_op = connect_op;
313         imp->imp_initial_recov = 1;
314         imp->imp_initial_recov_bk = 0;
315         CFS_INIT_LIST_HEAD(&imp->imp_pinger_chain);
316         memcpy(cli->cl_target_uuid.uuid, lustre_cfg_buf(lcfg, 1),
317                LUSTRE_CFG_BUFLEN(lcfg, 1));
318         class_import_put(imp);
319
320         rc = client_import_add_conn(imp, &server_uuid, 1);
321         if (rc) {
322                 CERROR("can't add initial connection\n");
323                 GOTO(err_import, rc);
324         }
325
326         cli->cl_import = imp;
327         /* cli->cl_max_mds_{easize,cookiesize} updated by mdc_init_ea_size() */
328         cli->cl_max_mds_easize = sizeof(struct lov_mds_md);
329         cli->cl_max_mds_cookiesize = sizeof(struct llog_cookie);
330
331         if (LUSTRE_CFG_BUFLEN(lcfg, 3) > 0) {
332                 if (!strcmp(lustre_cfg_string(lcfg, 3), "inactive")) {
333                         CDEBUG(D_HA, "marking %s %s->%s as inactive\n",
334                                name, obddev->obd_name,
335                                cli->cl_target_uuid.uuid);
336                         spin_lock(&imp->imp_lock);
337                         imp->imp_invalid = 1;
338                         spin_unlock(&imp->imp_lock);
339                 }
340         }
341
342         cli->cl_qchk_stat = CL_NOT_QUOTACHECKED;
343
344         RETURN(rc);
345
346 err_import:
347         class_destroy_import(imp);
348 err_ldlm:
349         ldlm_put_ref(LDLM_NAMESPACE_CLIENT, 0);
350 err:
351         RETURN(rc);
352
353 }
354
355 int client_obd_cleanup(struct obd_device *obddev)
356 {
357         ENTRY;
358         ldlm_put_ref(LDLM_NAMESPACE_CLIENT, obddev->obd_force);
359         RETURN(0);
360 }
361
362 /* ->o_connect() method for client side (OSC and MDC and MGC) */
363 int client_connect_import(const struct lu_env *env,
364                           struct lustre_handle *dlm_handle,
365                           struct obd_device *obd, struct obd_uuid *cluuid,
366                           struct obd_connect_data *data)
367 {
368         struct client_obd *cli = &obd->u.cli;
369         struct obd_import *imp = cli->cl_import;
370         struct obd_export *exp;
371         struct obd_connect_data *ocd;
372         int rc;
373         ENTRY;
374
375         mutex_down(&cli->cl_sem);
376         rc = class_connect(dlm_handle, obd, cluuid);
377         if (rc)
378                 GOTO(out_sem, rc);
379
380         cli->cl_conn_count++;
381         if (cli->cl_conn_count > 1)
382                 GOTO(out_sem, rc);
383         exp = class_conn2export(dlm_handle);
384
385         if (obd->obd_namespace != NULL)
386                 CERROR("already have namespace!\n");
387         obd->obd_namespace = ldlm_namespace_new(obd->obd_name,
388                                                 LDLM_NAMESPACE_CLIENT,
389                                                 LDLM_NAMESPACE_GREEDY);
390         if (obd->obd_namespace == NULL)
391                 GOTO(out_disco, rc = -ENOMEM);
392
393         imp->imp_dlm_handle = *dlm_handle;
394         rc = ptlrpc_init_import(imp);
395         if (rc != 0)
396                 GOTO(out_ldlm, rc);
397
398         rc = sptlrpc_import_get_sec(imp, NULL, cli->cl_sec_conf.sfc_rpc_flavor,
399                                     cli->cl_sec_conf.sfc_flags);
400         if (rc)
401                 GOTO(out_ldlm, rc);
402
403         ocd = &imp->imp_connect_data;
404         if (data) {
405                 *ocd = *data;
406                 imp->imp_connect_flags_orig = data->ocd_connect_flags;
407         }
408
409         rc = ptlrpc_connect_import(imp, NULL);
410         if (rc != 0) {
411                 LASSERT (imp->imp_state == LUSTRE_IMP_DISCON);
412                 GOTO(out_ldlm, rc);
413         }
414         LASSERT(exp->exp_connection);
415
416         if (data) {
417                 LASSERT((ocd->ocd_connect_flags & data->ocd_connect_flags) ==
418                         ocd->ocd_connect_flags);
419                 data->ocd_connect_flags = ocd->ocd_connect_flags;
420         }
421
422         ptlrpc_pinger_add_import(imp);
423
424         EXIT;
425
426         if (rc) {
427 out_ldlm:
428                 ldlm_namespace_free(obd->obd_namespace, 0);
429                 obd->obd_namespace = NULL;
430 out_disco:
431                 cli->cl_conn_count--;
432                 class_disconnect(exp);
433         } else {
434                 class_export_put(exp);
435         }
436 out_sem:
437         mutex_up(&cli->cl_sem);
438         return rc;
439 }
440
441 int client_disconnect_export(struct obd_export *exp)
442 {
443         struct obd_device *obd = class_exp2obd(exp);
444         struct client_obd *cli;
445         struct obd_import *imp;
446         int rc = 0, err;
447         ENTRY;
448
449         if (!obd) {
450                 CERROR("invalid export for disconnect: exp %p cookie "LPX64"\n",
451                        exp, exp ? exp->exp_handle.h_cookie : -1);
452                 RETURN(-EINVAL);
453         }
454
455         cli = &obd->u.cli;
456         imp = cli->cl_import;
457
458         mutex_down(&cli->cl_sem);
459         if (!cli->cl_conn_count) {
460                 CERROR("disconnecting disconnected device (%s)\n",
461                        obd->obd_name);
462                 GOTO(out_sem, rc = -EINVAL);
463         }
464
465         cli->cl_conn_count--;
466         if (cli->cl_conn_count)
467                 GOTO(out_no_disconnect, rc = 0);
468
469         /* Mark import deactivated now, so we don't try to reconnect if any
470          * of the cleanup RPCs fails (e.g. ldlm cancel, etc).  We don't
471          * fully deactivate the import, or that would drop all requests. */
472         spin_lock(&imp->imp_lock);
473         imp->imp_deactive = 1;
474         spin_unlock(&imp->imp_lock);
475         
476         /* Some non-replayable imports (MDS's OSCs) are pinged, so just
477          * delete it regardless.  (It's safe to delete an import that was
478          * never added.) */
479         (void)ptlrpc_pinger_del_import(imp);
480
481         if (obd->obd_namespace != NULL) {
482                 /* obd_force == local only */
483                 ldlm_cli_cancel_unused(obd->obd_namespace, NULL,
484                                        obd->obd_force ? LDLM_FL_LOCAL_ONLY:0,
485                                        NULL);
486                 ldlm_namespace_free(obd->obd_namespace, obd->obd_force);
487                 obd->obd_namespace = NULL;
488         }
489
490         if (!obd->obd_force)
491                 rc = ptlrpc_disconnect_import(imp, 0);
492
493         ptlrpc_invalidate_import(imp);
494         ptlrpc_free_rq_pool(imp->imp_rq_pool);
495         destroy_import(imp);
496         cli->cl_import = NULL;
497
498         EXIT;
499  out_no_disconnect:
500         err = class_disconnect(exp);
501         if (!rc && err)
502                 rc = err;
503  out_sem:
504         mutex_up(&cli->cl_sem);
505         RETURN(rc);
506 }
507
508 /* --------------------------------------------------------------------------
509  * from old lib/target.c
510  * -------------------------------------------------------------------------- */
511
512 int target_handle_reconnect(struct lustre_handle *conn, struct obd_export *exp,
513                             struct obd_uuid *cluuid, int initial_conn)
514 {
515         ENTRY;
516         if (exp->exp_connection && exp->exp_imp_reverse && !initial_conn) {
517                 struct lustre_handle *hdl;
518                 hdl = &exp->exp_imp_reverse->imp_remote_handle;
519                 /* Might be a re-connect after a partition. */
520                 if (!memcmp(&conn->cookie, &hdl->cookie, sizeof conn->cookie)) {
521                         CWARN("%s: %s reconnecting\n", exp->exp_obd->obd_name,
522                               cluuid->uuid);
523                         conn->cookie = exp->exp_handle.h_cookie;
524                         /* target_handle_connect() treats EALREADY and
525                          * -EALREADY differently.  EALREADY means we are
526                          * doing a valid reconnect from the same client. */
527                         RETURN(EALREADY);
528                 } else {
529                         CERROR("%s reconnecting from %s, "
530                                "handle mismatch (ours "LPX64", theirs "
531                                LPX64")\n", cluuid->uuid,
532                                exp->exp_connection->c_remote_uuid.uuid,
533                                hdl->cookie, conn->cookie);
534                         memset(conn, 0, sizeof *conn);
535                         /* target_handle_connect() treats EALREADY and
536                          * -EALREADY differently.  -EALREADY is an error
537                          * (same UUID, different handle). */
538                         RETURN(-EALREADY);
539                 }
540         }
541
542         conn->cookie = exp->exp_handle.h_cookie;
543         CDEBUG(D_HA, "connect export for UUID '%s' at %p, cookie "LPX64"\n",
544                cluuid->uuid, exp, conn->cookie);
545         RETURN(0);
546 }
547
548 void target_client_add_cb(struct obd_device *obd, __u64 transno, void *cb_data,
549                           int error)
550 {
551         struct obd_export *exp = cb_data;
552
553         CDEBUG(D_RPCTRACE, "%s: committing for initial connect of %s\n",
554                obd->obd_name, exp->exp_client_uuid.uuid);
555
556         spin_lock(&exp->exp_lock);
557         exp->exp_need_sync = 0;
558         spin_unlock(&exp->exp_lock);
559 }
560 EXPORT_SYMBOL(target_client_add_cb);
561
562 int target_handle_connect(struct ptlrpc_request *req)
563 {
564         struct obd_device *target, *targref = NULL;
565         struct obd_export *export = NULL;
566         struct obd_import *revimp;
567         struct lustre_handle conn;
568         struct obd_uuid tgtuuid;
569         struct obd_uuid cluuid;
570         struct obd_uuid remote_uuid;
571         struct list_head *p;
572         char *str, *tmp;
573         int rc = 0;
574         int initial_conn = 0;
575         struct obd_connect_data *data;
576         int size[2] = { sizeof(struct ptlrpc_body), sizeof(*data) };
577         ENTRY;
578
579         OBD_RACE(OBD_FAIL_TGT_CONN_RACE);
580
581         LASSERT_REQSWAB(req, REQ_REC_OFF);
582         str = lustre_msg_string(req->rq_reqmsg, REQ_REC_OFF, sizeof(tgtuuid)-1);
583         if (str == NULL) {
584                 DEBUG_REQ(D_ERROR, req, "bad target UUID for connect");
585                 GOTO(out, rc = -EINVAL);
586         }
587
588         obd_str2uuid (&tgtuuid, str);
589         target = class_uuid2obd(&tgtuuid);
590         if (!target)
591                 target = class_name2obd(str);
592
593         if (!target || target->obd_stopping || !target->obd_set_up) {
594                 LCONSOLE_ERROR_MSG(0x137, "UUID '%s' is not available "
595                                    " for connect (%s)\n", str,
596                                    !target ? "no target" :
597                                    (target->obd_stopping ? "stopping" :
598                                    "not set up"));
599                 GOTO(out, rc = -ENODEV);
600         }
601
602         if (target->obd_no_conn) {
603                 LCONSOLE_WARN("%s: temporarily refusing client connection "
604                               "from %s\n", target->obd_name, 
605                               libcfs_nid2str(req->rq_peer.nid));
606                 GOTO(out, rc = -EAGAIN);
607         }
608
609         /* Make sure the target isn't cleaned up while we're here. Yes,
610            there's still a race between the above check and our incref here.
611            Really, class_uuid2obd should take the ref. */
612         targref = class_incref(target);
613
614         LASSERT_REQSWAB(req, REQ_REC_OFF + 1);
615         str = lustre_msg_string(req->rq_reqmsg, REQ_REC_OFF + 1,
616                                 sizeof(cluuid) - 1);
617         if (str == NULL) {
618                 DEBUG_REQ(D_ERROR, req, "bad client UUID for connect");
619                 GOTO(out, rc = -EINVAL);
620         }
621
622         obd_str2uuid (&cluuid, str);
623
624         /* XXX extract a nettype and format accordingly */
625         switch (sizeof(lnet_nid_t)) {
626                 /* NB the casts only avoid compiler warnings */
627         case 8:
628                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
629                          "NET_"LPX64"_UUID", (__u64)req->rq_peer.nid);
630                 break;
631         case 4:
632                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
633                          "NET_%x_UUID", (__u32)req->rq_peer.nid);
634                 break;
635         default:
636                 LBUG();
637         }
638
639         tmp = lustre_msg_buf(req->rq_reqmsg, REQ_REC_OFF + 2, sizeof conn);
640         if (tmp == NULL)
641                 GOTO(out, rc = -EPROTO);
642
643         memcpy(&conn, tmp, sizeof conn);
644
645         data = lustre_swab_reqbuf(req, REQ_REC_OFF + 3, sizeof(*data),
646                                   lustre_swab_connect);
647
648         if (!data)
649                 GOTO(out, rc = -EPROTO);
650
651         rc = lustre_pack_reply(req, 2, size, NULL);
652         if (rc)
653                 GOTO(out, rc);
654
655         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
656                 if (!data) {
657                         DEBUG_REQ(D_WARNING, req, "Refusing old (unversioned) "
658                                   "libclient connection attempt");
659                         GOTO(out, rc = -EPROTO);
660                 } else if (data->ocd_version < LUSTRE_VERSION_CODE -
661                                                LUSTRE_VERSION_ALLOWED_OFFSET ||
662                            data->ocd_version > LUSTRE_VERSION_CODE +
663                                                LUSTRE_VERSION_ALLOWED_OFFSET) {
664                         DEBUG_REQ(D_WARNING, req, "Refusing %s (%d.%d.%d.%d) "
665                                   "libclient connection attempt",
666                                   data->ocd_version < LUSTRE_VERSION_CODE ?
667                                   "old" : "new",
668                                   OBD_OCD_VERSION_MAJOR(data->ocd_version),
669                                   OBD_OCD_VERSION_MINOR(data->ocd_version),
670                                   OBD_OCD_VERSION_PATCH(data->ocd_version),
671                                   OBD_OCD_VERSION_FIX(data->ocd_version));
672                         data = lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
673                                               offsetof(typeof(*data),
674                                                        ocd_version) +
675                                               sizeof(data->ocd_version));
676                         if (data) {
677                                 data->ocd_connect_flags = OBD_CONNECT_VERSION;
678                                 data->ocd_version = LUSTRE_VERSION_CODE;
679                         }
680                         GOTO(out, rc = -EPROTO);
681                 }
682         }
683
684         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_INITIAL)
685                 initial_conn = 1;
686
687         /* lctl gets a backstage, all-access pass. */
688         if (obd_uuid_equals(&cluuid, &target->obd_uuid))
689                 goto dont_check_exports;
690
691         spin_lock(&target->obd_dev_lock);
692         list_for_each(p, &target->obd_exports) {
693                 export = list_entry(p, struct obd_export, exp_obd_chain);
694                 if (obd_uuid_equals(&cluuid, &export->exp_client_uuid)) {
695                         if (export->exp_connecting) { /* bug 9635, et. al. */
696                                 CWARN("%s: exp %p already connecting\n",
697                                       export->exp_obd->obd_name, export);
698                                 export = NULL;
699                                 rc = -EALREADY;
700                                 break;
701                         }
702
703                         /* make darn sure this is coming from the same peer
704                          * if the UUIDs matched */
705                         if ((export->exp_connection != NULL) &&
706                             (strcmp(libcfs_nid2str(req->rq_peer.nid),
707                                     libcfs_nid2str(export->exp_connection->c_peer.nid)))) {
708                                 CWARN("%s: cookie %s seen on new NID %s when "
709                                       "existing NID %s is already connected\n",
710                                       target->obd_name, cluuid.uuid,
711                                       libcfs_nid2str(req->rq_peer.nid),
712                                       libcfs_nid2str(export->exp_connection->c_peer.nid));
713                                 export = NULL;
714                                 rc = -EALREADY;
715                                 break;
716                         }
717
718                         spin_lock(&export->exp_lock);
719                         export->exp_connecting = 1;
720                         spin_unlock(&export->exp_lock);
721                         spin_unlock(&target->obd_dev_lock);
722                         LASSERT(export->exp_obd == target);
723
724                         rc = target_handle_reconnect(&conn, export, &cluuid,
725                                                      initial_conn);
726                         break;
727                 }
728                 export = NULL;
729         }
730
731         /* If we found an export, we already unlocked. */
732         if (!export) {
733                 spin_unlock(&target->obd_dev_lock);
734                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_CONNECT, 2 * obd_timeout);
735         } else if (req->rq_export == NULL &&
736                    atomic_read(&export->exp_rpc_count) > 0) {
737                 CWARN("%s: refuse connection from %s/%s to 0x%p/%d\n",
738                       target->obd_name, cluuid.uuid,
739                       libcfs_nid2str(req->rq_peer.nid),
740                       export, atomic_read(&export->exp_refcount));
741                 GOTO(out, rc = -EBUSY);
742         } else if (req->rq_export != NULL &&
743                    (atomic_read(&export->exp_rpc_count) > 1)) {
744                 CWARN("%s: refuse reconnection from %s@%s to 0x%p/%d\n",
745                       target->obd_name, cluuid.uuid,
746                       libcfs_nid2str(req->rq_peer.nid),
747                       export, atomic_read(&export->exp_rpc_count));
748                 GOTO(out, rc = -EBUSY);
749         } else if (lustre_msg_get_conn_cnt(req->rq_reqmsg) == 1 &&
750                    !initial_conn) {
751                 CERROR("%s: NID %s (%s) reconnected with 1 conn_cnt; "
752                        "cookies not random?\n", target->obd_name,
753                        libcfs_nid2str(req->rq_peer.nid), cluuid.uuid);
754                 GOTO(out, rc = -EALREADY);
755         } else {
756                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_RECONNECT, 2 * obd_timeout);
757                 if (req->rq_export == NULL && initial_conn)
758                        export->exp_last_request_time = 
759                                max(export->exp_last_request_time,
760                                    (time_t)CURRENT_SECONDS);
761         }
762
763         /* We want to handle EALREADY but *not* -EALREADY from
764          * target_handle_reconnect(), return reconnection state in a flag */
765         if (rc == EALREADY) {
766                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECONNECT);
767                 rc = 0;
768         } else if (rc) {
769                 GOTO(out, rc);
770         }
771         /* Tell the client if we're in recovery. */
772         /* If this is the first client, start the recovery timer */
773         CWARN("%s: connection from %s@%s %st"LPU64" exp %p cur %ld last %ld\n",
774                target->obd_name, cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
775               target->obd_recovering ? "recovering/" : "", data->ocd_transno,
776               export, (long)CURRENT_SECONDS, 
777               export ? (long)export->exp_last_request_time : 0);
778
779
780         if (target->obd_recovering) {
781                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
782                 target_start_recovery_timer(target);
783         }
784
785         /* Tell the client if we support replayable requests */
786         if (target->obd_replayable)
787                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
788
789         if (export == NULL) {
790                 if (target->obd_recovering) {
791                         CERROR("%s: denying connection for new client %s (%s): "
792                                "%d clients in recovery for %lds\n",
793                                target->obd_name,
794                                libcfs_nid2str(req->rq_peer.nid), cluuid.uuid,
795                                target->obd_recoverable_clients,
796                                cfs_duration_sec(cfs_time_sub(cfs_timer_deadline(&target->obd_recovery_timer),
797                                                              cfs_time_current())));
798                         rc = -EBUSY;
799                 } else {
800 dont_check_exports:
801                         rc = obd_connect(req->rq_svc_thread->t_env,
802                                          &conn, target, &cluuid, data);
803                 }
804         } else {
805                 rc = obd_reconnect(export, target, &cluuid, data);
806         }
807         if (rc)
808                 GOTO(out, rc);
809         /* Return only the parts of obd_connect_data that we understand, so the
810          * client knows that we don't understand the rest. */
811         if (data)
812                 memcpy(lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
813                                       sizeof(*data)),
814                        data, sizeof(*data));
815
816         /* If all else goes well, this is our RPC return code. */
817         req->rq_status = 0;
818
819         lustre_msg_set_handle(req->rq_repmsg, &conn);
820
821         /* ownership of this export ref transfers to the request AFTER we
822          * drop any previous reference the request had, but we don't want
823          * that to go to zero before we get our new export reference. */
824         export = class_conn2export(&conn);
825         if (!export) {
826                 DEBUG_REQ(D_ERROR, req, "Missing export!");
827                 GOTO(out, rc = -ENODEV);
828         }
829
830         /* If the client and the server are the same node, we will already
831          * have an export that really points to the client's DLM export,
832          * because we have a shared handles table.
833          *
834          * XXX this will go away when shaver stops sending the "connect" handle
835          * in the real "remote handle" field of the request --phik 24 Apr 2003
836          */
837         if (req->rq_export != NULL)
838                 class_export_put(req->rq_export);
839
840         req->rq_export = export;
841
842         spin_lock(&export->exp_lock);
843         if (initial_conn) {
844                 lustre_msg_set_conn_cnt(req->rq_repmsg, export->exp_conn_cnt + 1);
845         } else if (export->exp_conn_cnt >= lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
846                 spin_unlock(&export->exp_lock);
847                 CERROR("%s: %s already connected at higher conn_cnt: %d > %d\n",
848                        cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
849                        export->exp_conn_cnt,
850                        lustre_msg_get_conn_cnt(req->rq_reqmsg));
851
852                 GOTO(out, rc = -EALREADY);
853         }
854         export->exp_conn_cnt = lustre_msg_get_conn_cnt(req->rq_reqmsg);
855
856         /* request from liblustre?  Don't evict it for not pinging. */
857         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
858                 export->exp_libclient = 1;
859                 spin_unlock(&export->exp_lock);
860                 
861                 spin_lock(&target->obd_dev_lock);
862                 list_del_init(&export->exp_obd_chain_timed);
863                 spin_unlock(&target->obd_dev_lock);
864         } else {
865                 spin_unlock(&export->exp_lock);
866         }
867
868         if (export->exp_connection != NULL)
869                 ptlrpc_put_connection(export->exp_connection);
870         export->exp_connection = ptlrpc_get_connection(req->rq_peer,
871                                                        req->rq_self,
872                                                        &remote_uuid);
873
874         spin_lock_bh(&target->obd_processing_task_lock);
875         if (target->obd_recovering && !export->exp_in_recovery) {
876                 spin_lock(&export->exp_lock);
877                 export->exp_in_recovery = 1;
878                 export->exp_req_replay_needed = 1;
879                 export->exp_lock_replay_needed = 1;                
880                 spin_unlock(&export->exp_lock);
881                 if ((lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_TRANSNO)
882                      && data->ocd_transno < target->obd_next_recovery_transno)
883                         target->obd_next_recovery_transno = data->ocd_transno;
884                 target->obd_connected_clients++;
885                 /* each connected client is counted as recoverable */
886                 target->obd_recoverable_clients++;
887                 atomic_inc(&target->obd_req_replay_clients);
888                 atomic_inc(&target->obd_lock_replay_clients);
889                 if (target->obd_connected_clients == 
890                     target->obd_max_recoverable_clients)
891                         wake_up(&target->obd_next_transno_waitq);
892         }
893         spin_unlock_bh(&target->obd_processing_task_lock);
894         memcpy(&conn,
895                lustre_msg_buf(req->rq_reqmsg, REQ_REC_OFF + 2, sizeof conn),
896                sizeof conn);
897
898         if (export->exp_imp_reverse != NULL) {
899                 /* destroyed import can be still referenced in ctxt */
900                 obd_set_info_async(export, strlen(KEY_REVIMP_UPD), 
901                                    KEY_REVIMP_UPD, 0, NULL, NULL);
902                 destroy_import(export->exp_imp_reverse);
903         }
904
905         /* for the rest part, we return -ENOTCONN in case of errors
906          * in order to let client initialize connection again.
907          */
908         revimp = export->exp_imp_reverse = class_new_import(target);
909         if (!revimp) {
910                 CERROR("fail to alloc new reverse import.\n");
911                 GOTO(out, rc = -ENOTCONN);
912         }
913
914         revimp->imp_connection = ptlrpc_connection_addref(export->exp_connection);
915         revimp->imp_client = &export->exp_obd->obd_ldlm_client;
916         revimp->imp_remote_handle = conn;
917         revimp->imp_dlm_fake = 1;
918         revimp->imp_state = LUSTRE_IMP_FULL;
919
920         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_NEXT_VER) {
921                 revimp->imp_msg_magic = LUSTRE_MSG_MAGIC_V2;
922                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_NEXT_VER);
923         }
924
925         rc = sptlrpc_import_get_sec(revimp, req->rq_svc_ctx,
926                                     req->rq_sec_flavor, 0);
927         if (rc) {
928                 CERROR("Failed to get sec for reverse import: %d\n", rc);
929                 export->exp_imp_reverse = NULL;
930                 class_destroy_import(revimp);
931         }
932
933         class_import_put(revimp);
934 out:
935         if (export) {
936                 spin_lock(&export->exp_lock);
937                 export->exp_connecting = 0;
938                 spin_unlock(&export->exp_lock);
939         }
940         if (targref)
941                 class_decref(targref);
942         if (rc)
943                 req->rq_status = rc;
944         RETURN(rc);
945 }
946
947 int target_handle_disconnect(struct ptlrpc_request *req)
948 {
949         int rc;
950         ENTRY;
951
952         rc = lustre_pack_reply(req, 1, NULL, NULL);
953         if (rc)
954                 RETURN(rc);
955
956         /* keep the rq_export around so we can send the reply */
957         req->rq_status = obd_disconnect(class_export_get(req->rq_export));
958         
959         RETURN(0);
960 }
961
962 void target_destroy_export(struct obd_export *exp)
963 {
964         /* exports created from last_rcvd data, and "fake"
965            exports created by lctl don't have an import */
966         if (exp->exp_imp_reverse != NULL)
967                 destroy_import(exp->exp_imp_reverse);
968
969         /* We cancel locks at disconnect time, but this will catch any locks
970          * granted in a race with recovery-induced disconnect. */
971         if (exp->exp_obd->obd_namespace != NULL)
972                 ldlm_cancel_locks_for_export(exp);
973 }
974
975 /*
976  * Recovery functions
977  */
978
979 struct ptlrpc_request *ptlrpc_clone_req( struct ptlrpc_request *orig_req)
980 {
981         struct ptlrpc_request *copy_req;
982         struct lustre_msg *copy_reqmsg;
983         struct ptlrpc_user_desc *udesc = NULL;
984
985         OBD_ALLOC_PTR(copy_req);
986         if (!copy_req)
987                 return NULL;
988         OBD_ALLOC(copy_reqmsg, orig_req->rq_reqlen);
989         if (!copy_reqmsg){
990                 OBD_FREE_PTR(copy_req);
991                 return NULL;
992         }
993
994         if (orig_req->rq_user_desc) {
995                 int ngroups = orig_req->rq_user_desc->pud_ngroups;
996
997                 OBD_ALLOC(udesc, sptlrpc_user_desc_size(ngroups));
998                 if (!udesc) {
999                         OBD_FREE(copy_reqmsg, orig_req->rq_reqlen);
1000                         OBD_FREE_PTR(copy_req);
1001                         return NULL;
1002                 }
1003                 memcpy(udesc, orig_req->rq_user_desc,
1004                        sptlrpc_user_desc_size(ngroups));
1005         }
1006
1007         *copy_req = *orig_req;
1008         memcpy(copy_reqmsg, orig_req->rq_reqmsg, orig_req->rq_reqlen);
1009         copy_req->rq_reqmsg = copy_reqmsg;
1010         copy_req->rq_user_desc = udesc;
1011
1012         class_export_get(copy_req->rq_export);
1013         CFS_INIT_LIST_HEAD(&copy_req->rq_list);
1014         sptlrpc_svc_ctx_addref(copy_req);
1015
1016         if (copy_req->rq_reply_state) {
1017                 /* the copied req takes over the reply state */
1018                 orig_req->rq_reply_state = NULL;
1019                 /* to catch further access */
1020                 orig_req->rq_repmsg = NULL;
1021                 orig_req->rq_replen = 0;
1022         }
1023
1024         return copy_req;
1025 }
1026
1027 void ptlrpc_free_clone( struct ptlrpc_request *req)
1028 {
1029         if (req->rq_reply_state) {
1030                 ptlrpc_rs_decref(req->rq_reply_state);
1031                 req->rq_reply_state = NULL;
1032         }
1033
1034         sptlrpc_svc_ctx_decref(req);
1035         class_export_put(req->rq_export);
1036         list_del(&req->rq_list);
1037
1038         if (req->rq_user_desc) {
1039                 int ngroups = req->rq_user_desc->pud_ngroups;
1040                 OBD_FREE(req->rq_user_desc, sptlrpc_user_desc_size(ngroups));
1041         }
1042         OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
1043         OBD_FREE_PTR(req);
1044 }
1045
1046 #ifdef __KERNEL__
1047 static void target_finish_recovery(struct obd_device *obd)
1048 {
1049         ENTRY;
1050         LCONSOLE_INFO("%s: sending delayed replies to recovered clients\n",
1051                       obd->obd_name);
1052
1053         ldlm_reprocess_all_ns(obd->obd_namespace);
1054
1055         /* when recovery finished, cleanup orphans on mds and ost */
1056         if (OBT(obd) && OBP(obd, postrecov)) {
1057                 int rc = OBP(obd, postrecov)(obd);
1058                 LCONSOLE_WARN("%s: recovery %s: rc %d\n", obd->obd_name,
1059                               rc < 0 ? "failed" : "complete", rc);
1060         }
1061
1062         obd->obd_recovery_end = CURRENT_SECONDS;
1063         EXIT;
1064 }
1065
1066 static void abort_req_replay_queue(struct obd_device *obd)
1067 {
1068         struct ptlrpc_request *req, *n;
1069
1070         list_for_each_entry_safe(req, n, &obd->obd_req_replay_queue, rq_list) {
1071                 DEBUG_REQ(D_WARNING, req, "aborted:");
1072                 req->rq_status = -ENOTCONN;
1073                 if (ptlrpc_error(req)) {
1074                         DEBUG_REQ(D_ERROR, req,
1075                                   "failed abort_req_reply; skipping");
1076                 }
1077                 ptlrpc_free_clone(req);
1078         }
1079 }
1080
1081 static void abort_lock_replay_queue(struct obd_device *obd)
1082 {
1083         struct ptlrpc_request *req, *n;
1084
1085         list_for_each_entry_safe(req, n, &obd->obd_lock_replay_queue, rq_list){
1086                 DEBUG_REQ(D_ERROR, req, "aborted:");
1087                 req->rq_status = -ENOTCONN;
1088                 if (ptlrpc_error(req)) { 
1089                         DEBUG_REQ(D_ERROR, req,
1090                                   "failed abort_lock_reply; skipping");
1091                 }
1092                 ptlrpc_free_clone(req);
1093         }
1094 }
1095 #endif
1096
1097 /* Called from a cleanup function if the device is being cleaned up
1098    forcefully.  The exports should all have been disconnected already,
1099    the only thing left to do is
1100      - clear the recovery flags
1101      - cancel the timer
1102      - free queued requests and replies, but don't send replies
1103    Because the obd_stopping flag is set, no new requests should be received.
1104
1105 */
1106 void target_cleanup_recovery(struct obd_device *obd)
1107 {
1108         struct ptlrpc_request *req, *n;
1109         ENTRY;
1110
1111         LASSERT(obd->obd_stopping);
1112
1113         spin_lock_bh(&obd->obd_processing_task_lock);
1114         if (!obd->obd_recovering) {
1115                 spin_unlock_bh(&obd->obd_processing_task_lock);
1116                 EXIT;
1117                 return;
1118         }
1119         obd->obd_recovering = obd->obd_abort_recovery = 0;
1120         target_cancel_recovery_timer(obd);
1121         spin_unlock_bh(&obd->obd_processing_task_lock);
1122
1123         list_for_each_entry_safe(req, n, &obd->obd_req_replay_queue, rq_list) {
1124                 LASSERT (req->rq_reply_state == 0);
1125                 ptlrpc_free_clone(req);
1126         }
1127         list_for_each_entry_safe(req, n, &obd->obd_lock_replay_queue, rq_list){
1128                 LASSERT (req->rq_reply_state == 0);
1129                 ptlrpc_free_clone(req);
1130         }
1131         list_for_each_entry_safe(req, n, &obd->obd_final_req_queue, rq_list) {
1132                 LASSERT (req->rq_reply_state == 0);
1133                 ptlrpc_free_clone(req);
1134         }
1135
1136         EXIT;
1137 }
1138
1139 static void target_recovery_expired(unsigned long castmeharder)
1140 {
1141         struct obd_device *obd = (struct obd_device *)castmeharder;
1142         CERROR("%s: recovery timed out, aborting\n", obd->obd_name);
1143         spin_lock_bh(&obd->obd_processing_task_lock);
1144         if (obd->obd_recovering)
1145                 obd->obd_abort_recovery = 1;
1146         cfs_waitq_signal(&obd->obd_next_transno_waitq);
1147         spin_unlock_bh(&obd->obd_processing_task_lock);
1148 }
1149
1150
1151 /* obd_processing_task_lock should be held */
1152 void target_cancel_recovery_timer(struct obd_device *obd)
1153 {
1154         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1155         cfs_timer_disarm(&obd->obd_recovery_timer);
1156 }
1157
1158 static void reset_recovery_timer(struct obd_device *obd)
1159 {
1160         spin_lock_bh(&obd->obd_processing_task_lock);
1161         if (!obd->obd_recovering) {
1162                 spin_unlock_bh(&obd->obd_processing_task_lock);
1163                 return;
1164         }
1165         cfs_timer_arm(&obd->obd_recovery_timer,
1166                       cfs_time_shift(OBD_RECOVERY_TIMEOUT));
1167         spin_unlock_bh(&obd->obd_processing_task_lock);
1168         CDEBUG(D_HA, "%s: timer will expire in %u seconds\n", obd->obd_name,
1169                OBD_RECOVERY_TIMEOUT);
1170         /* Only used for lprocfs_status */
1171         obd->obd_recovery_end = CURRENT_SECONDS + OBD_RECOVERY_TIMEOUT;
1172 }
1173
1174
1175 /* Only start it the first time called */
1176 void target_start_recovery_timer(struct obd_device *obd)
1177 {
1178         spin_lock_bh(&obd->obd_processing_task_lock);
1179         if (obd->obd_recovery_handler
1180             || timer_pending((struct timer_list *)&obd->obd_recovery_timer)) {
1181                 spin_unlock_bh(&obd->obd_processing_task_lock);
1182                 return;
1183         }
1184         CWARN("%s: starting recovery timer (%us)\n", obd->obd_name,
1185               OBD_RECOVERY_TIMEOUT);
1186         cfs_timer_init(&obd->obd_recovery_timer, target_recovery_expired, obd);
1187         spin_unlock_bh(&obd->obd_processing_task_lock);
1188
1189         reset_recovery_timer(obd);
1190 }
1191
1192 #ifdef __KERNEL__
1193 static int check_for_next_transno(struct obd_device *obd)
1194 {
1195         struct ptlrpc_request *req = NULL;
1196         int wake_up = 0, connected, completed, queue_len, max;
1197         __u64 next_transno, req_transno;
1198         ENTRY;
1199         spin_lock_bh(&obd->obd_processing_task_lock);
1200
1201         if (!list_empty(&obd->obd_req_replay_queue)) {
1202                 req = list_entry(obd->obd_req_replay_queue.next,
1203                                  struct ptlrpc_request, rq_list);
1204                 req_transno = lustre_msg_get_transno(req->rq_reqmsg);
1205         } else {
1206                 req_transno = 0;
1207         }
1208
1209         max = obd->obd_max_recoverable_clients;
1210         connected = obd->obd_connected_clients;
1211         completed = connected - obd->obd_recoverable_clients;
1212         queue_len = obd->obd_requests_queued_for_recovery;
1213         next_transno = obd->obd_next_recovery_transno;
1214
1215         CDEBUG(D_HA, "max: %d, connected: %d, completed: %d, queue_len: %d, "
1216                "req_transno: "LPU64", next_transno: "LPU64"\n",
1217                max, connected, completed, queue_len, req_transno, next_transno);
1218
1219         if (obd->obd_abort_recovery) {
1220                 CDEBUG(D_HA, "waking for aborted recovery\n");
1221                 wake_up = 1;
1222         } else if (atomic_read(&obd->obd_req_replay_clients) == 0) {
1223                 CDEBUG(D_HA, "waking for completed recovery\n");
1224                 wake_up = 1;
1225         } else if (req_transno == next_transno) {
1226                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1227                 wake_up = 1;
1228         } else if (queue_len + completed == max) {
1229                 /* handle gaps occured due to lost reply. It is allowed gaps
1230                  * because all clients are connected and there will be resend
1231                  * for missed transaction */
1232                 LASSERTF(req_transno >= next_transno,
1233                          "req_transno: "LPU64", next_transno: "LPU64"\n",
1234                          req_transno, next_transno);
1235
1236                 CDEBUG(req_transno > obd->obd_last_committed ? D_ERROR : D_HA,
1237                        "waking for skipped transno (skip: "LPD64
1238                        ", ql: %d, comp: %d, conn: %d, next: "LPD64")\n",
1239                        next_transno, queue_len, completed, connected, req_transno);
1240                 obd->obd_next_recovery_transno = req_transno;
1241                 wake_up = 1;
1242         } else if (queue_len == atomic_read(&obd->obd_req_replay_clients)) {
1243                 /* some clients haven't connected in time, but we can try
1244                  * to replay requests that demand on already committed ones
1245                  * also, we can replay first non-committed transation */
1246                 LASSERT(req_transno != 0);
1247                 if (req_transno == obd->obd_last_committed + 1) {
1248                         obd->obd_next_recovery_transno = req_transno;
1249                 } else if (req_transno > obd->obd_last_committed) {
1250                         /* can't continue recovery: have no needed transno */
1251                         obd->obd_abort_recovery = 1;
1252                         CDEBUG(D_ERROR, "abort due to missed clients. max: %d, "
1253                                "connected: %d, completed: %d, queue_len: %d, "
1254                                "req_transno: "LPU64", next_transno: "LPU64"\n",
1255                                max, connected, completed, queue_len,
1256                                req_transno, next_transno);
1257                 }
1258                 wake_up = 1;
1259         }
1260
1261         spin_unlock_bh(&obd->obd_processing_task_lock);
1262         return wake_up;
1263 }
1264
1265 static struct ptlrpc_request *target_next_replay_req(struct obd_device *obd)
1266 {
1267         struct l_wait_info lwi = { 0 };
1268         struct ptlrpc_request *req;
1269
1270         CDEBUG(D_HA, "Waiting for transno "LPD64"\n",
1271                obd->obd_next_recovery_transno);
1272         l_wait_event(obd->obd_next_transno_waitq,
1273                      check_for_next_transno(obd), &lwi);
1274
1275         spin_lock_bh(&obd->obd_processing_task_lock);
1276         if (obd->obd_abort_recovery) {
1277                 req = NULL;
1278         } else if (!list_empty(&obd->obd_req_replay_queue)) {
1279                 req = list_entry(obd->obd_req_replay_queue.next,
1280                                  struct ptlrpc_request, rq_list);
1281                 list_del_init(&req->rq_list);
1282                 obd->obd_requests_queued_for_recovery--;
1283         } else {
1284                 req = NULL;
1285         }
1286         spin_unlock_bh(&obd->obd_processing_task_lock);
1287         RETURN(req);
1288 }
1289
1290 static int check_for_next_lock(struct obd_device *obd)
1291 {
1292         struct ptlrpc_request *req = NULL;
1293         int wake_up = 0;
1294
1295         spin_lock_bh(&obd->obd_processing_task_lock);
1296         if (!list_empty(&obd->obd_lock_replay_queue)) {
1297                 req = list_entry(obd->obd_lock_replay_queue.next,
1298                                  struct ptlrpc_request, rq_list);
1299                 CDEBUG(D_HA, "waking for next lock\n");
1300                 wake_up = 1;
1301         } else if (atomic_read(&obd->obd_lock_replay_clients) == 0) {
1302                 CDEBUG(D_HA, "waking for completed lock replay\n");
1303                 wake_up = 1;
1304         } else if (obd->obd_abort_recovery) {
1305                 CDEBUG(D_HA, "waking for aborted recovery\n");
1306                 wake_up = 1;
1307         }
1308         spin_unlock_bh(&obd->obd_processing_task_lock);
1309
1310         return wake_up;
1311 }
1312
1313 static struct ptlrpc_request *target_next_replay_lock(struct obd_device *obd)
1314 {
1315         struct l_wait_info lwi = { 0 };
1316         struct ptlrpc_request *req;
1317
1318         CDEBUG(D_HA, "Waiting for lock\n");
1319         l_wait_event(obd->obd_next_transno_waitq,
1320                      check_for_next_lock(obd), &lwi);
1321
1322         spin_lock_bh(&obd->obd_processing_task_lock);
1323         if (obd->obd_abort_recovery) {
1324                 req = NULL;
1325         } else if (!list_empty(&obd->obd_lock_replay_queue)) {
1326                 req = list_entry(obd->obd_lock_replay_queue.next,
1327                                  struct ptlrpc_request, rq_list);
1328                 list_del_init(&req->rq_list);
1329         } else {
1330                 req = NULL;
1331         }
1332         spin_unlock_bh(&obd->obd_processing_task_lock);
1333         return req;
1334 }
1335
1336 static struct ptlrpc_request *target_next_final_ping(struct obd_device *obd)
1337 {
1338         struct ptlrpc_request *req;
1339
1340         spin_lock_bh(&obd->obd_processing_task_lock);
1341         if (!list_empty(&obd->obd_final_req_queue)) {
1342                 req = list_entry(obd->obd_final_req_queue.next,
1343                                  struct ptlrpc_request, rq_list);
1344                 list_del_init(&req->rq_list);
1345         } else {
1346                 req = NULL;
1347         }
1348         spin_unlock_bh(&obd->obd_processing_task_lock);
1349         return req;
1350 }
1351
1352 static inline int req_replay_done(struct obd_export *exp)
1353 {
1354         return (exp->exp_req_replay_needed == 0);
1355 }
1356
1357 static inline int lock_replay_done(struct obd_export *exp)
1358 {
1359         return (exp->exp_lock_replay_needed == 0);
1360 }
1361
1362 static inline int connect_done(struct obd_export *exp)
1363 {
1364         return (exp->exp_in_recovery != 0);
1365 }
1366
1367 static int check_for_clients(struct obd_device *obd)
1368 {
1369         if (obd->obd_abort_recovery)
1370                 return 1;
1371         LASSERT(obd->obd_connected_clients <= obd->obd_max_recoverable_clients);
1372         if (obd->obd_no_conn == 0 &&
1373             obd->obd_connected_clients == obd->obd_max_recoverable_clients)
1374                 return 1;
1375         return 0;
1376 }
1377
1378 static int handle_recovery_req(struct ptlrpc_thread *thread,
1379                                struct ptlrpc_request *req,
1380                                svc_handler_t handler)
1381 {
1382         int rc;
1383         ENTRY;
1384
1385         rc = lu_context_init(&req->rq_session, LCT_SESSION);
1386         if (rc) {
1387                 CERROR("Failure to initialize session: %d\n", rc);
1388                 return rc;
1389         }
1390         req->rq_session.lc_thread = thread;
1391         lu_context_enter(&req->rq_session);
1392         req->rq_svc_thread = thread;
1393         req->rq_svc_thread->t_env->le_ses = &req->rq_session;
1394
1395         (void)handler(req);
1396
1397         lu_context_exit(&req->rq_session);
1398         lu_context_fini(&req->rq_session);
1399         /* don't reset timer for final stage */
1400         if (!req_replay_done(req->rq_export) ||
1401             !lock_replay_done(req->rq_export))
1402                 reset_recovery_timer(class_exp2obd(req->rq_export));
1403         ptlrpc_free_clone(req);
1404         RETURN(0);
1405 }
1406
1407 static int target_recovery_thread(void *arg)
1408 {
1409         struct obd_device *obd = arg;
1410         struct ptlrpc_request *req;
1411         struct target_recovery_data *trd = &obd->obd_recovery_data;
1412         struct l_wait_info lwi = { 0 };
1413         unsigned long delta;
1414         unsigned long flags;
1415         struct lu_env env;
1416         struct ptlrpc_thread fake_svc_thread, *thread = &fake_svc_thread;
1417         __u32 recov_ctx_tags = LCT_MD_THREAD;
1418         int rc = 0;
1419         ENTRY;
1420
1421         cfs_daemonize("tgt_recov");
1422
1423         SIGNAL_MASK_LOCK(current, flags);
1424         sigfillset(&current->blocked);
1425         RECALC_SIGPENDING;
1426         SIGNAL_MASK_UNLOCK(current, flags);
1427
1428         rc = lu_context_init(&env.le_ctx, recov_ctx_tags);
1429         if (rc)
1430                 RETURN(rc);
1431
1432         thread->t_env = &env;
1433         env.le_ctx.lc_thread = thread;
1434
1435         CERROR("%s: started recovery thread pid %d\n", obd->obd_name,
1436                current->pid);
1437         trd->trd_processing_task = current->pid;
1438
1439         obd->obd_recovering = 1;
1440         complete(&trd->trd_starting);
1441
1442         /* first of all, we have to know the first transno to replay */
1443         obd->obd_abort_recovery = 0;
1444         l_wait_event(obd->obd_next_transno_waitq,
1445                      check_for_clients(obd), &lwi);
1446
1447         spin_lock_bh(&obd->obd_processing_task_lock);
1448         target_cancel_recovery_timer(obd);
1449         spin_unlock_bh(&obd->obd_processing_task_lock);
1450
1451         /* If some clients haven't connected in time, evict them */
1452         if (obd->obd_abort_recovery) {
1453                 CWARN("Some clients haven't connect in time (%d/%d),"
1454                        "evict them\n", obd->obd_connected_clients,
1455                        obd->obd_max_recoverable_clients);
1456                 obd->obd_abort_recovery = obd->obd_stopping;
1457                 class_disconnect_stale_exports(obd, connect_done);
1458         }
1459         /* next stage: replay requests */
1460         delta = jiffies;
1461         obd->obd_req_replaying = 1;
1462         CDEBUG(D_INFO, "1: request replay stage - %d clients from t"LPU64"\n",
1463               atomic_read(&obd->obd_req_replay_clients),
1464               obd->obd_next_recovery_transno);
1465         while ((req = target_next_replay_req(obd))) {
1466                 LASSERT(trd->trd_processing_task == current->pid);
1467                 DEBUG_REQ(D_HA, req, "processing t"LPD64" from %s",
1468                           lustre_msg_get_transno(req->rq_reqmsg),
1469                           libcfs_nid2str(req->rq_peer.nid));
1470
1471                 handle_recovery_req(thread, req,
1472                                     trd->trd_recovery_handler);
1473                 obd->obd_replayed_requests++;
1474                 spin_lock_bh(&obd->obd_processing_task_lock);
1475                 obd->obd_next_recovery_transno++;
1476                 spin_unlock_bh(&obd->obd_processing_task_lock);
1477         }
1478
1479         spin_lock_bh(&obd->obd_processing_task_lock);
1480         target_cancel_recovery_timer(obd);
1481         spin_unlock_bh(&obd->obd_processing_task_lock);
1482
1483         /* If some clients haven't replayed requests in time, evict them */
1484         if (obd->obd_abort_recovery) {
1485                 CDEBUG(D_ERROR, "req replay timed out, aborting ...\n");
1486                 obd->obd_abort_recovery = obd->obd_stopping;
1487                 class_disconnect_stale_exports(obd, req_replay_done);
1488                 abort_req_replay_queue(obd);
1489         }
1490         /* The second stage: replay locks */
1491         CDEBUG(D_INFO, "2: lock replay stage - %d clients\n",
1492                atomic_read(&obd->obd_lock_replay_clients));
1493         while ((req = target_next_replay_lock(obd))) {
1494                 LASSERT(trd->trd_processing_task == current->pid);
1495                 DEBUG_REQ(D_HA|D_WARNING, req, "processing lock from %s: ",
1496                           libcfs_nid2str(req->rq_peer.nid));
1497                 handle_recovery_req(thread, req,
1498                                     trd->trd_recovery_handler);
1499                 obd->obd_replayed_locks++;
1500         }
1501
1502         spin_lock_bh(&obd->obd_processing_task_lock);
1503         target_cancel_recovery_timer(obd);
1504         spin_unlock_bh(&obd->obd_processing_task_lock);
1505         /* If some clients haven't replayed requests in time, evict them */
1506         if (obd->obd_abort_recovery) {
1507                 int stale;
1508                 CERROR("lock replay timed out, aborting ...\n");
1509                 obd->obd_abort_recovery = obd->obd_stopping;
1510                 stale = class_disconnect_stale_exports(obd, lock_replay_done);
1511                 abort_lock_replay_queue(obd);
1512         }
1513
1514         /* We drop recoverying flag to forward all new requests
1515          * to regular mds_handle() since now */
1516         spin_lock_bh(&obd->obd_processing_task_lock);
1517         obd->obd_recovering = obd->obd_abort_recovery = 0;
1518         spin_unlock_bh(&obd->obd_processing_task_lock);
1519         /* The third stage: reply on final pings */
1520         CDEBUG(D_INFO, "3: final stage - process recovery completion pings\n");
1521         while ((req = target_next_final_ping(obd))) {
1522                 LASSERT(trd->trd_processing_task == current->pid);
1523                 DEBUG_REQ(D_HA, req, "processing final ping from %s: ",
1524                           libcfs_nid2str(req->rq_peer.nid));
1525                 handle_recovery_req(thread, req,
1526                                     trd->trd_recovery_handler);
1527         }
1528
1529         delta = (jiffies - delta) / HZ;
1530         CDEBUG(D_INFO,"4: recovery completed in %lus - %d/%d reqs/locks\n",
1531               delta, obd->obd_replayed_requests, obd->obd_replayed_locks);
1532         LASSERT(atomic_read(&obd->obd_req_replay_clients) == 0);
1533         LASSERT(atomic_read(&obd->obd_lock_replay_clients) == 0);
1534         if (delta > obd_timeout * 2) {
1535                 CWARN("too long recovery - read logs\n");
1536                 libcfs_debug_dumplog();
1537         }
1538
1539         target_finish_recovery(obd);
1540
1541         lu_env_fini(&env);
1542         trd->trd_processing_task = 0;
1543         complete(&trd->trd_finishing);
1544         RETURN(rc);
1545 }
1546
1547 int target_start_recovery_thread(struct obd_device *obd, svc_handler_t handler)
1548 {
1549         int rc = 0;
1550         struct target_recovery_data *trd = &obd->obd_recovery_data;
1551
1552         memset(trd, 0, sizeof(*trd));
1553         init_completion(&trd->trd_starting);
1554         init_completion(&trd->trd_finishing);
1555         trd->trd_recovery_handler = handler;
1556
1557         if (kernel_thread(target_recovery_thread, obd, 0) > 0) {
1558                 wait_for_completion(&trd->trd_starting);
1559                 LASSERT(obd->obd_recovering != 0);
1560         } else
1561                 rc = -ECHILD;
1562
1563         return rc;
1564 }
1565
1566 void target_stop_recovery_thread(struct obd_device *obd)
1567 {
1568         spin_lock_bh(&obd->obd_processing_task_lock);
1569         if (obd->obd_recovery_data.trd_processing_task > 0) {
1570                 struct target_recovery_data *trd = &obd->obd_recovery_data;
1571                 CERROR("%s: Aborting recovery\n", obd->obd_name);
1572                 obd->obd_abort_recovery = 1;
1573                 wake_up(&obd->obd_next_transno_waitq);
1574                 spin_unlock_bh(&obd->obd_processing_task_lock);
1575                 wait_for_completion(&trd->trd_finishing);
1576         } else {
1577                 spin_unlock_bh(&obd->obd_processing_task_lock);
1578         }
1579 }
1580
1581 void target_recovery_fini(struct obd_device *obd)
1582 {
1583         class_disconnect_exports(obd);
1584         target_stop_recovery_thread(obd);
1585         target_cleanup_recovery(obd);
1586 }
1587 EXPORT_SYMBOL(target_recovery_fini);
1588
1589 void target_recovery_init(struct obd_device *obd, svc_handler_t handler)
1590 {
1591         if (obd->obd_max_recoverable_clients == 0)
1592                 return;
1593         
1594         CWARN("RECOVERY: service %s, %d recoverable clients, "
1595               "last_transno "LPU64"\n", obd->obd_name,
1596               obd->obd_max_recoverable_clients, obd->obd_last_committed);
1597         obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
1598         target_start_recovery_thread(obd, handler);
1599         obd->obd_recovery_start = CURRENT_SECONDS;
1600         /* Only used for lprocfs_status */
1601         obd->obd_recovery_end = obd->obd_recovery_start + OBD_RECOVERY_TIMEOUT;
1602 }
1603 EXPORT_SYMBOL(target_recovery_init);
1604
1605 #endif
1606
1607 int target_process_req_flags(struct obd_device *obd, struct ptlrpc_request *req)
1608 {
1609         struct obd_export *exp = req->rq_export;
1610         LASSERT(exp != NULL);
1611         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1612                 /* client declares he's ready to replay locks */
1613                 spin_lock_bh(&obd->obd_processing_task_lock);
1614                 if (exp->exp_req_replay_needed) {
1615                         LASSERT(atomic_read(&obd->obd_req_replay_clients) > 0);
1616                         spin_lock(&exp->exp_lock);
1617                         exp->exp_req_replay_needed = 0;
1618                         spin_unlock(&exp->exp_lock);
1619                         atomic_dec(&obd->obd_req_replay_clients);
1620                         LASSERT(obd->obd_recoverable_clients > 0);
1621                         obd->obd_recoverable_clients--;
1622                         if (atomic_read(&obd->obd_req_replay_clients) == 0)
1623                                 CDEBUG(D_HA, "all clients have replayed reqs\n");
1624                         wake_up(&obd->obd_next_transno_waitq);
1625                 }
1626                 spin_unlock_bh(&obd->obd_processing_task_lock);
1627         }
1628         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1629                 /* client declares he's ready to complete recovery
1630                  * so, we put the request on th final queue */
1631                 spin_lock_bh(&obd->obd_processing_task_lock);
1632                 if (exp->exp_lock_replay_needed) {
1633                         LASSERT(atomic_read(&obd->obd_lock_replay_clients) > 0);
1634                         spin_lock(&exp->exp_lock);
1635                         exp->exp_lock_replay_needed = 0;
1636                         spin_unlock(&exp->exp_lock);
1637                         atomic_dec(&obd->obd_lock_replay_clients);
1638                         if (atomic_read(&obd->obd_lock_replay_clients) == 0)
1639                                 CDEBUG(D_HA, "all clients have replayed locks\n");
1640                         wake_up(&obd->obd_next_transno_waitq);
1641                 }
1642                 spin_unlock_bh(&obd->obd_processing_task_lock);
1643         }
1644
1645         return 0;
1646 }
1647
1648 int target_queue_recovery_request(struct ptlrpc_request *req,
1649                                   struct obd_device *obd)
1650 {
1651         struct list_head *tmp;
1652         int inserted = 0;
1653         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
1654
1655         ENTRY;
1656
1657         if (obd->obd_recovery_data.trd_processing_task == cfs_curproc_pid()) {
1658                 /* Processing the queue right now, don't re-add. */
1659                 RETURN(1);
1660         }
1661
1662         target_process_req_flags(obd, req);
1663
1664         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1665                 /* client declares he's ready to complete recovery
1666                  * so, we put the request on th final queue */
1667                 req = ptlrpc_clone_req(req);
1668                 if (req == NULL)
1669                         RETURN(-ENOMEM);
1670                 DEBUG_REQ(D_HA, req, "queue final req");
1671                 spin_lock_bh(&obd->obd_processing_task_lock);
1672                 if (obd->obd_recovering)
1673                         list_add_tail(&req->rq_list, &obd->obd_final_req_queue);
1674                 else {
1675                         spin_unlock_bh(&obd->obd_processing_task_lock);
1676                         ptlrpc_free_clone(req);
1677                         if (obd->obd_stopping) {
1678                                 RETURN(-ENOTCONN);
1679                         } else {
1680                                 RETURN(1);
1681                         }
1682                 }
1683                 spin_unlock_bh(&obd->obd_processing_task_lock);
1684                 RETURN(0);
1685         }
1686         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1687                 /* client declares he's ready to replay locks */
1688                 req = ptlrpc_clone_req(req);
1689                 if (req == NULL)
1690                         RETURN(-ENOMEM);
1691                 DEBUG_REQ(D_HA, req, "queue lock replay req");
1692                 spin_lock_bh(&obd->obd_processing_task_lock);
1693                 LASSERT(obd->obd_recovering);
1694                 /* usually due to recovery abort */
1695                 if (!req->rq_export->exp_in_recovery) {
1696                         spin_unlock_bh(&obd->obd_processing_task_lock);
1697                         ptlrpc_free_clone(req);
1698                         RETURN(-ENOTCONN);
1699                 }
1700                 LASSERT(req->rq_export->exp_lock_replay_needed);
1701                 list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
1702                 spin_unlock_bh(&obd->obd_processing_task_lock);
1703                 wake_up(&obd->obd_next_transno_waitq);
1704                 RETURN(0);
1705         }
1706
1707         /* CAVEAT EMPTOR: The incoming request message has been swabbed
1708          * (i.e. buflens etc are in my own byte order), but type-dependent
1709          * buffers (eg mds_body, ost_body etc) have NOT been swabbed. */
1710
1711         if (!transno) {
1712                 CFS_INIT_LIST_HEAD(&req->rq_list);
1713                 DEBUG_REQ(D_HA, req, "not queueing");
1714                 RETURN(1);
1715         }
1716
1717         spin_lock_bh(&obd->obd_processing_task_lock);
1718
1719         /* If we're processing the queue, we want don't want to queue this
1720          * message.
1721          *
1722          * Also, if this request has a transno less than the one we're waiting
1723          * for, we should process it now.  It could (and currently always will)
1724          * be an open request for a descriptor that was opened some time ago.
1725          *
1726          * Also, a resent, replayed request that has already been
1727          * handled will pass through here and be processed immediately.
1728          */
1729         CWARN("Next recovery transno: "LPU64", current: "LPU64", replaying: %i\n",
1730               obd->obd_next_recovery_transno, transno, obd->obd_req_replaying);
1731         if (transno < obd->obd_next_recovery_transno && obd->obd_req_replaying) {
1732                 /* Processing the queue right now, don't re-add. */
1733                 LASSERT(list_empty(&req->rq_list));
1734                 spin_unlock_bh(&obd->obd_processing_task_lock);
1735                 RETURN(1);
1736         }
1737         spin_unlock_bh(&obd->obd_processing_task_lock);
1738
1739         /* A resent, replayed request that is still on the queue; just drop it.
1740            The queued request will handle this. */
1741         if ((lustre_msg_get_flags(req->rq_reqmsg) & (MSG_RESENT|MSG_REPLAY)) ==
1742             (MSG_RESENT | MSG_REPLAY)) {
1743                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
1744                 RETURN(0);
1745         }
1746
1747         req = ptlrpc_clone_req(req);
1748         if (req == NULL)
1749                 RETURN(-ENOMEM);
1750
1751         spin_lock_bh(&obd->obd_processing_task_lock);
1752         LASSERT(obd->obd_recovering);
1753         if (!req->rq_export->exp_in_recovery) {
1754                 spin_unlock_bh(&obd->obd_processing_task_lock);
1755                 ptlrpc_free_clone(req);
1756                 RETURN(-ENOTCONN);
1757         }
1758         LASSERT(req->rq_export->exp_req_replay_needed);
1759
1760         /* XXX O(n^2) */
1761         list_for_each(tmp, &obd->obd_req_replay_queue) {
1762                 struct ptlrpc_request *reqiter =
1763                         list_entry(tmp, struct ptlrpc_request, rq_list);
1764
1765                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
1766                         list_add_tail(&req->rq_list, &reqiter->rq_list);
1767                         inserted = 1;
1768                         break;
1769                 }
1770         }
1771
1772         if (!inserted)
1773                 list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
1774
1775         obd->obd_requests_queued_for_recovery++;
1776         wake_up(&obd->obd_next_transno_waitq);
1777         spin_unlock_bh(&obd->obd_processing_task_lock);
1778         RETURN(0);
1779
1780 }
1781
1782 struct obd_device * target_req2obd(struct ptlrpc_request *req)
1783 {
1784         return req->rq_export->exp_obd;
1785 }
1786
1787 static inline struct ldlm_pool *ldlm_exp2pl(struct obd_export *exp)
1788 {
1789         LASSERT(exp != NULL);
1790         return &exp->exp_obd->obd_namespace->ns_pool;
1791 }
1792
1793 int target_pack_pool_reply(struct ptlrpc_request *req)
1794 {
1795         struct ldlm_pool *pl;
1796         ENTRY;
1797    
1798         if (req->rq_export == NULL) {
1799                 lustre_msg_set_slv(req->rq_repmsg, 0);
1800                 lustre_msg_set_limit(req->rq_repmsg, 0);
1801                 RETURN(0);
1802         }
1803  
1804         if (!exp_connect_lru_resize(req->rq_export))
1805                 RETURN(0);
1806         
1807         pl = ldlm_exp2pl(req->rq_export);
1808
1809         spin_lock(&pl->pl_lock);
1810         lustre_msg_set_slv(req->rq_repmsg, ldlm_pool_get_slv(pl));
1811         lustre_msg_set_limit(req->rq_repmsg, ldlm_pool_get_limit(pl));
1812         spin_unlock(&pl->pl_lock);
1813
1814         RETURN(0);
1815 }
1816
1817 int target_send_reply_msg(struct ptlrpc_request *req, int rc, int fail_id)
1818 {
1819         if (OBD_FAIL_CHECK(fail_id | OBD_FAIL_ONCE)) {
1820                 obd_fail_loc |= OBD_FAIL_ONCE | OBD_FAILED;
1821                 DEBUG_REQ(D_ERROR, req, "dropping reply");
1822                 return (-ECOMM);
1823         }
1824
1825         if (unlikely(rc)) {
1826                 DEBUG_REQ(D_ERROR, req, "processing error (%d)", rc);
1827                 req->rq_status = rc;
1828                 return (ptlrpc_error(req));
1829         } else {
1830                 DEBUG_REQ(D_NET, req, "sending reply");
1831         }
1832
1833         target_pack_pool_reply(req);
1834         return (ptlrpc_send_reply(req, 1));
1835 }
1836
1837 void target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
1838 {
1839         int                        netrc;
1840         struct ptlrpc_reply_state *rs;
1841         struct obd_device         *obd;
1842         struct obd_export         *exp;
1843         struct ptlrpc_service     *svc;
1844
1845         if (req->rq_no_reply)
1846                 return;
1847
1848         svc = req->rq_rqbd->rqbd_service;
1849         rs = req->rq_reply_state;
1850         if (rs == NULL || !rs->rs_difficult) {
1851                 /* no notifiers */
1852                 target_send_reply_msg (req, rc, fail_id);
1853                 return;
1854         }
1855
1856         /* must be an export if locks saved */
1857         LASSERT (req->rq_export != NULL);
1858         /* req/reply consistent */
1859         LASSERT (rs->rs_service == svc);
1860
1861         /* "fresh" reply */
1862         LASSERT (!rs->rs_scheduled);
1863         LASSERT (!rs->rs_scheduled_ever);
1864         LASSERT (!rs->rs_handled);
1865         LASSERT (!rs->rs_on_net);
1866         LASSERT (rs->rs_export == NULL);
1867         LASSERT (list_empty(&rs->rs_obd_list));
1868         LASSERT (list_empty(&rs->rs_exp_list));
1869
1870         exp = class_export_get (req->rq_export);
1871         obd = exp->exp_obd;
1872
1873         /* disable reply scheduling onto srv_reply_queue while I'm setting up */
1874         rs->rs_scheduled = 1;
1875         rs->rs_on_net    = 1;
1876         rs->rs_xid       = req->rq_xid;
1877         rs->rs_transno   = req->rq_transno;
1878         rs->rs_export    = exp;
1879
1880         spin_lock(&obd->obd_uncommitted_replies_lock);
1881
1882         if (rs->rs_transno > obd->obd_last_committed) {
1883                 /* not committed already */
1884                 list_add_tail (&rs->rs_obd_list,
1885                                &obd->obd_uncommitted_replies);
1886         }
1887
1888         spin_unlock (&obd->obd_uncommitted_replies_lock);
1889         spin_lock (&exp->exp_lock);
1890
1891         list_add_tail (&rs->rs_exp_list, &exp->exp_outstanding_replies);
1892
1893         spin_unlock(&exp->exp_lock);
1894
1895         netrc = target_send_reply_msg (req, rc, fail_id);
1896
1897         spin_lock(&svc->srv_lock);
1898
1899         svc->srv_n_difficult_replies++;
1900
1901         if (netrc != 0) {
1902                 /* error sending: reply is off the net.  Also we need +1
1903                  * reply ref until ptlrpc_server_handle_reply() is done
1904                  * with the reply state (if the send was successful, there
1905                  * would have been +1 ref for the net, which
1906                  * reply_out_callback leaves alone) */
1907                 rs->rs_on_net = 0;
1908                 ptlrpc_rs_addref(rs);
1909                 atomic_inc (&svc->srv_outstanding_replies);
1910         }
1911
1912         if (!rs->rs_on_net ||                   /* some notifier */
1913             list_empty(&rs->rs_exp_list) ||     /* completed already */
1914             list_empty(&rs->rs_obd_list)) {
1915                 list_add_tail (&rs->rs_list, &svc->srv_reply_queue);
1916                 cfs_waitq_signal (&svc->srv_waitq);
1917         } else {
1918                 list_add (&rs->rs_list, &svc->srv_active_replies);
1919                 rs->rs_scheduled = 0;           /* allow notifier to schedule */
1920         }
1921
1922         spin_unlock(&svc->srv_lock);
1923 }
1924
1925 int target_handle_ping(struct ptlrpc_request *req)
1926 {
1927         obd_ping(req->rq_export);
1928         return lustre_pack_reply(req, 1, NULL, NULL);
1929 }
1930
1931 void target_committed_to_req(struct ptlrpc_request *req)
1932 {
1933         struct obd_device *obd;
1934
1935         if (req == NULL || req->rq_export == NULL)
1936                 return;
1937
1938         obd = req->rq_export->exp_obd;
1939         if (obd == NULL)
1940                 return;
1941
1942         if (!obd->obd_no_transno && req->rq_repmsg != NULL)
1943                 lustre_msg_set_last_committed(req->rq_repmsg,
1944                                               obd->obd_last_committed);
1945         else
1946                 DEBUG_REQ(D_IOCTL, req, "not sending last_committed update");
1947
1948         CDEBUG(D_INFO, "last_committed "LPU64", transno "LPU64", xid "LPU64"\n",
1949                obd->obd_last_committed, req->rq_transno, req->rq_xid);
1950 }
1951
1952 EXPORT_SYMBOL(target_committed_to_req);
1953
1954 #ifdef HAVE_QUOTA_SUPPORT
1955 int target_handle_qc_callback(struct ptlrpc_request *req)
1956 {
1957         struct obd_quotactl *oqctl;
1958         struct client_obd *cli = &req->rq_export->exp_obd->u.cli;
1959
1960         oqctl = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*oqctl),
1961                                    lustre_swab_obd_quotactl);
1962         if (oqctl == NULL) {
1963                 CERROR("Can't unpack obd_quotactl\n");
1964                 RETURN(-EPROTO);
1965         }
1966
1967         cli->cl_qchk_stat = oqctl->qc_stat;
1968
1969         return 0;
1970 }
1971
1972 int target_handle_dqacq_callback(struct ptlrpc_request *req)
1973 {
1974 #ifdef __KERNEL__
1975         struct obd_device *obd = req->rq_export->exp_obd;
1976         struct obd_device *master_obd;
1977         struct lustre_quota_ctxt *qctxt;
1978         struct qunit_data *qdata;
1979         void* rep;
1980         struct qunit_data_old *qdata_old;
1981         int rc = 0;
1982         int repsize[2] = { sizeof(struct ptlrpc_body),
1983                            sizeof(struct qunit_data) };
1984         ENTRY;
1985
1986         rc = lustre_pack_reply(req, 2, repsize, NULL);
1987         if (rc) {
1988                 CERROR("packing reply failed!: rc = %d\n", rc);
1989                 RETURN(rc);
1990         }
1991         LASSERT(req->rq_export);
1992
1993         /* fixed for bug10707 */
1994         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
1995             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
1996                 CDEBUG(D_QUOTA, "qd_count is 64bit!\n");
1997                 rep = lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
1998                                      sizeof(struct qunit_data));
1999                 LASSERT(rep);
2000                 qdata = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*qdata),
2001                                            lustre_swab_qdata);
2002         } else {
2003                 CDEBUG(D_QUOTA, "qd_count is 32bit!\n");
2004                 rep = lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
2005                                      sizeof(struct qunit_data_old));
2006                 LASSERT(rep);
2007                 qdata_old = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*qdata_old),
2008                                                lustre_swab_qdata_old);
2009                 qdata = lustre_quota_old_to_new(qdata_old);
2010         }
2011
2012         if (qdata == NULL) {
2013                 CERROR("Can't unpack qunit_data\n");
2014                 RETURN(-EPROTO);
2015         }
2016
2017         /* we use the observer */
2018         LASSERT(obd->obd_observer && obd->obd_observer->obd_observer);
2019         master_obd = obd->obd_observer->obd_observer;
2020         qctxt = &master_obd->u.obt.obt_qctxt;
2021
2022         LASSERT(qctxt->lqc_handler);
2023         rc = qctxt->lqc_handler(master_obd, qdata,
2024                                 lustre_msg_get_opc(req->rq_reqmsg));
2025         if (rc && rc != -EDQUOT)
2026                 CDEBUG(rc == -EBUSY  ? D_QUOTA : D_ERROR,
2027                        "dqacq failed! (rc:%d)\n", rc);
2028
2029         /* the qd_count might be changed in lqc_handler */
2030         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
2031             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
2032                 memcpy(rep,qdata,sizeof(*qdata));
2033         } else {
2034                 qdata_old = lustre_quota_new_to_old(qdata);
2035                 memcpy(rep,qdata_old,sizeof(*qdata_old));
2036         }
2037         req->rq_status = rc;
2038         rc = ptlrpc_reply(req);
2039
2040         RETURN(rc);
2041 #else
2042         return 0;
2043 #endif /* !__KERNEL__ */
2044 }
2045 #endif /* HAVE_QUOTA_SUPPORT */
2046
2047 ldlm_mode_t lck_compat_array[] = {
2048         [LCK_EX] LCK_COMPAT_EX,
2049         [LCK_PW] LCK_COMPAT_PW,
2050         [LCK_PR] LCK_COMPAT_PR,
2051         [LCK_CW] LCK_COMPAT_CW,
2052         [LCK_CR] LCK_COMPAT_CR,
2053         [LCK_NL] LCK_COMPAT_NL,
2054         [LCK_GROUP] LCK_COMPAT_GROUP
2055 };