Whamcloud - gitweb
b=6063
[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 Lustre, http://www.lustre.org.
7  *
8  *   Lustre is free software; you can redistribute it and/or
9  *   modify it under the terms of version 2 of the GNU General Public
10  *   License as published by the Free Software Foundation.
11  *
12  *   Lustre is distributed in the hope that it will be useful,
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *   GNU General Public License for more details.
16  *
17  *   You should have received a copy of the GNU General Public License
18  *   along with Lustre; if not, write to the Free Software
19  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  */
21
22 #ifndef EXPORT_SYMTAB
23 # define EXPORT_SYMTAB
24 #endif
25 #define DEBUG_SUBSYSTEM S_LDLM
26
27 #ifdef __KERNEL__
28 # include <linux/module.h>
29 #else
30 # include <liblustre.h>
31 #endif
32 #include <linux/obd.h>
33 #include <linux/obd_ost.h> /* for LUSTRE_OSC_NAME */
34 #include <linux/lustre_mds.h> /* for LUSTRE_MDC_NAME */
35 #include <linux/lustre_mgmt.h>
36 #include <linux/lustre_dlm.h>
37 #include <linux/lustre_net.h>
38 #include <linux/lustre_sec.h>
39
40 /* @priority: if non-zero, move the selected to the list head
41  * @nocreate: if non-zero, only search in existed connections
42  */
43 static int import_set_conn(struct obd_import *imp, struct obd_uuid *uuid,
44                            int priority, int nocreate)
45 {
46         struct ptlrpc_connection *ptlrpc_conn;
47         struct obd_import_conn *imp_conn = NULL, *item;
48         int rc = 0;
49         ENTRY;
50
51         LASSERT(!(nocreate && !priority));
52
53         ptlrpc_conn = ptlrpc_uuid_to_connection(uuid);
54         if (!ptlrpc_conn) {
55                 CERROR("can't find connection %s\n", uuid->uuid);
56                 RETURN (-EINVAL);
57         }
58
59         if (!nocreate) {
60                 OBD_ALLOC(imp_conn, sizeof(*imp_conn));
61                 if (!imp_conn) {
62                         CERROR("fail to alloc memory\n");
63                         GOTO(out_put, rc = -ENOMEM);
64                 }
65         }
66
67         spin_lock(&imp->imp_lock);
68         list_for_each_entry(item, &imp->imp_conn_list, oic_item) {
69                 if (obd_uuid_equals(uuid, &item->oic_uuid)) {
70                         if (priority) {
71                                 list_del(&item->oic_item);
72                                 list_add(&item->oic_item, &imp->imp_conn_list);
73                                 item->oic_last_attempt = 0;
74                         }
75                         CDEBUG(D_HA, "imp %p@%s: find existed conn %s%s\n",
76                                imp, imp->imp_obd->obd_name, uuid->uuid,
77                                (priority ? ", move to head." : ""));
78                         spin_unlock(&imp->imp_lock);
79                         GOTO(out_free, rc = 0);
80                 }
81         }
82         /* not found */
83         if (!nocreate) {
84                 imp_conn->oic_conn = ptlrpc_conn;
85                 imp_conn->oic_uuid = *uuid;
86                 imp_conn->oic_last_attempt = 0;
87                 if (priority)
88                         list_add(&imp_conn->oic_item, &imp->imp_conn_list);
89                 else
90                         list_add_tail(&imp_conn->oic_item, &imp->imp_conn_list);
91                 CDEBUG(D_HA, "imp %p@%s: add connection %s at %s\n",
92                        imp, imp->imp_obd->obd_name, uuid->uuid,
93                        (priority ? "head" : "tail"));
94         } else
95                 rc = -ENOENT;
96
97         spin_unlock(&imp->imp_lock);
98         RETURN(0);
99 out_free:
100         if (imp_conn)
101                 OBD_FREE(imp_conn, sizeof(*imp_conn));
102 out_put:
103         ptlrpc_put_connection(ptlrpc_conn);
104         RETURN(rc);
105 }
106
107 int import_set_conn_priority(struct obd_import *imp, struct obd_uuid *uuid)
108 {
109         return import_set_conn(imp, uuid, 1, 1);
110 }
111
112 int client_import_add_conn(struct obd_import *imp, struct obd_uuid *uuid,
113                            int priority)
114 {
115         return import_set_conn(imp, uuid, priority, 0);
116 }
117
118 int client_import_del_conn(struct obd_import *imp, struct obd_uuid *uuid)
119 {
120         struct obd_import_conn *imp_conn;
121         struct obd_export *dlmexp;
122         int rc = -ENOENT;
123         ENTRY;
124
125         spin_lock(&imp->imp_lock);
126         if (list_empty(&imp->imp_conn_list)) {
127                 LASSERT(!imp->imp_conn_current);
128                 LASSERT(!imp->imp_connection);
129                 GOTO(out, rc);
130         }
131
132         list_for_each_entry(imp_conn, &imp->imp_conn_list, oic_item) {
133                 if (!obd_uuid_equals(uuid, &imp_conn->oic_uuid))
134                         continue;
135                 LASSERT(imp_conn->oic_conn);
136
137                 /* is current conn? */
138                 if (imp_conn == imp->imp_conn_current) {
139                         LASSERT(imp_conn->oic_conn == imp->imp_connection);
140
141                         if (imp->imp_state != LUSTRE_IMP_CLOSED &&
142                             imp->imp_state != LUSTRE_IMP_DISCON) {
143                                 CERROR("can't remove current connection\n");
144                                 GOTO(out, rc = -EBUSY);
145                         }
146
147                         ptlrpc_put_connection(imp->imp_connection);
148                         imp->imp_connection = NULL;
149
150                         dlmexp = class_conn2export(&imp->imp_dlm_handle);
151                         if (dlmexp && dlmexp->exp_connection) {
152                                 LASSERT(dlmexp->exp_connection ==
153                                         imp_conn->oic_conn);
154                                 ptlrpc_put_connection(dlmexp->exp_connection);
155                                 dlmexp->exp_connection = NULL;
156                         }
157                 }
158
159                 list_del(&imp_conn->oic_item);
160                 ptlrpc_put_connection(imp_conn->oic_conn);
161                 OBD_FREE(imp_conn, sizeof(*imp_conn));
162                 CDEBUG(D_HA, "imp %p@%s: remove connection %s\n",
163                        imp, imp->imp_obd->obd_name, uuid->uuid);
164                 rc = 0;
165                 break;
166         }
167 out:
168         spin_unlock(&imp->imp_lock);
169         if (rc == -ENOENT)
170                 CERROR("connection %s not found\n", uuid->uuid);
171         RETURN(rc);
172 }
173
174 int client_obd_setup(struct obd_device *obddev, obd_count len, void *buf)
175 {
176         struct lustre_cfg* lcfg = buf;
177         struct client_obd *cli = &obddev->u.cli;
178         struct obd_import *imp;
179         struct obd_uuid server_uuid;
180         int rq_portal, rp_portal, connect_op;
181         char *name = obddev->obd_type->typ_name;
182         char *mgmt_name = NULL;
183         int rc;
184         struct obd_device *mgmt_obd;
185         mgmtcli_register_for_events_t register_f;
186         ENTRY;
187
188         /* In a more perfect world, we would hang a ptlrpc_client off of
189          * obd_type and just use the values from there. */
190         if (!strcmp(name, LUSTRE_OSC_NAME)) {
191                 rq_portal = OST_REQUEST_PORTAL;
192                 rp_portal = OSC_REPLY_PORTAL;
193                 connect_op = OST_CONNECT;
194         } else if (!strcmp(name, LUSTRE_MDC_NAME)) {
195                 rq_portal = MDS_REQUEST_PORTAL;
196                 rp_portal = MDC_REPLY_PORTAL;
197                 connect_op = MDS_CONNECT;
198         } else if (!strcmp(name, LUSTRE_MGMTCLI_NAME)) {
199                 rq_portal = MGMT_REQUEST_PORTAL;
200                 rp_portal = MGMT_REPLY_PORTAL;
201                 connect_op = MGMT_CONNECT;
202         } else {
203                 CERROR("unknown client OBD type \"%s\", can't setup\n",
204                        name);
205                 RETURN(-EINVAL);
206         }
207
208         if (lcfg->lcfg_inllen1 < 1) {
209                 CERROR("requires a TARGET UUID\n");
210                 RETURN(-EINVAL);
211         }
212
213         if (lcfg->lcfg_inllen1 > 37) {
214                 CERROR("client UUID must be less than 38 characters\n");
215                 RETURN(-EINVAL);
216         }
217
218         if (lcfg->lcfg_inllen2 < 1) {
219                 CERROR("setup requires a SERVER UUID\n");
220                 RETURN(-EINVAL);
221         }
222
223         if (lcfg->lcfg_inllen2 > 37) {
224                 CERROR("target UUID must be less than 38 characters\n");
225                 RETURN(-EINVAL);
226         }
227
228         sema_init(&cli->cl_sem, 1);
229         cli->cl_conn_count = 0;
230         memcpy(server_uuid.uuid, lcfg->lcfg_inlbuf2,
231                min_t(unsigned int, lcfg->lcfg_inllen2, sizeof(server_uuid)));
232
233         cli->cl_dirty = 0;
234         cli->cl_avail_grant = 0;
235         /* FIXME: should limit this for the sum of all cl_dirty_max */
236         cli->cl_dirty_max = OSC_MAX_DIRTY_DEFAULT * 1024 * 1024;
237         if (cli->cl_dirty_max >> PAGE_SHIFT > num_physpages / 8)
238                 cli->cl_dirty_max = num_physpages << (PAGE_SHIFT - 3);
239         INIT_LIST_HEAD(&cli->cl_cache_waiters);
240         INIT_LIST_HEAD(&cli->cl_loi_ready_list);
241         INIT_LIST_HEAD(&cli->cl_loi_write_list);
242         INIT_LIST_HEAD(&cli->cl_loi_read_list);
243         spin_lock_init(&cli->cl_loi_list_lock);
244         cli->cl_r_in_flight = 0;
245         cli->cl_w_in_flight = 0;
246         spin_lock_init(&cli->cl_read_rpc_hist.oh_lock);
247         spin_lock_init(&cli->cl_write_rpc_hist.oh_lock);
248         spin_lock_init(&cli->cl_read_page_hist.oh_lock);
249         spin_lock_init(&cli->cl_write_page_hist.oh_lock);
250
251         if (num_physpages >> (20 - PAGE_SHIFT) <= 128) { /* <= 128 MB */
252                 cli->cl_max_pages_per_rpc = PTLRPC_MAX_BRW_PAGES / 4;
253                 cli->cl_max_rpcs_in_flight = OSC_MAX_RIF_DEFAULT / 4;
254         } else if (num_physpages >> (20 - PAGE_SHIFT) <= 512) { /* <= 512 MB */
255                 cli->cl_max_pages_per_rpc = PTLRPC_MAX_BRW_PAGES / 2;
256                 cli->cl_max_rpcs_in_flight = OSC_MAX_RIF_DEFAULT / 2;
257         } else {
258                 cli->cl_max_pages_per_rpc = PTLRPC_MAX_BRW_PAGES;
259                 cli->cl_max_rpcs_in_flight = OSC_MAX_RIF_DEFAULT;
260         }
261
262         rc = ldlm_get_ref();
263         if (rc) {
264                 CERROR("ldlm_get_ref failed: %d\n", rc);
265                 GOTO(err, rc);
266         }
267
268         ptlrpc_init_client(rq_portal, rp_portal, name,
269                            &obddev->obd_ldlm_client);
270
271         imp = class_new_import();
272         if (imp == NULL) 
273                 GOTO(err_ldlm, rc = -ENOENT);
274         imp->imp_client = &obddev->obd_ldlm_client;
275         imp->imp_obd = obddev;
276         imp->imp_connect_op = connect_op;
277         imp->imp_generation = 0;
278         imp->imp_initial_recov = 1;
279         INIT_LIST_HEAD(&imp->imp_pinger_chain);
280         memcpy(imp->imp_target_uuid.uuid, lcfg->lcfg_inlbuf1,
281               lcfg->lcfg_inllen1);
282         class_import_put(imp);
283
284         rc = client_import_add_conn(imp, &server_uuid, 1);
285         if (rc) {
286                 CERROR("can't add initial connection\n");
287                 GOTO(err_import, rc);
288         }
289
290         cli->cl_import = imp;
291         cli->cl_max_mds_easize = sizeof(struct lov_mds_md);
292         cli->cl_max_mds_cookiesize = sizeof(struct llog_cookie);
293         cli->cl_sandev = to_kdev_t(0);
294
295         if (lcfg->lcfg_inllen3 != 0) {
296                 if (!strcmp(lcfg->lcfg_inlbuf3, "inactive")) {
297                         CDEBUG(D_HA, "marking %s %s->%s as inactive\n",
298                                name, obddev->obd_name,
299                                imp->imp_target_uuid.uuid);
300                         imp->imp_invalid = 1;
301
302                         if (lcfg->lcfg_inllen4 != 0)
303                                 mgmt_name = lcfg->lcfg_inlbuf4;
304                 } else {
305                         mgmt_name = lcfg->lcfg_inlbuf3;
306                 }
307         }
308
309         if (mgmt_name != NULL) {
310                 /* Register with management client if we need to. */
311                 CDEBUG(D_HA, "%s registering with %s for events about %s\n",
312                        obddev->obd_name, mgmt_name, server_uuid.uuid);
313
314                 mgmt_obd = class_name2obd(mgmt_name);
315                 if (!mgmt_obd) {
316                         CERROR("can't find mgmtcli %s to register\n",
317                                mgmt_name);
318                         GOTO(err_import, rc = -ENOSYS);
319                 }
320
321                 register_f = (mgmtcli_register_for_events_t)symbol_get("mgmtcli_register_for_events");
322                 if (!register_f) {
323                         CERROR("can't i_m_g mgmtcli_register_for_events\n");
324                         GOTO(err_import, rc = -ENOSYS);
325                 }
326
327                 rc = register_f(mgmt_obd, obddev, &imp->imp_target_uuid);
328                 symbol_put("mgmtcli_register_for_events");
329
330                 if (!rc)
331                         cli->cl_mgmtcli_obd = mgmt_obd;
332         }
333
334         RETURN(rc);
335
336 err_import:
337         class_destroy_import(imp);
338 err_ldlm:
339         ldlm_put_ref(0);
340 err:
341         RETURN(rc);
342
343 }
344
345 int client_obd_cleanup(struct obd_device *obddev, int flags)
346 {
347         struct client_obd *cli = &obddev->u.cli;
348         ENTRY;
349
350         if (!cli->cl_import)
351                 RETURN(-EINVAL);
352         if (cli->cl_mgmtcli_obd) {
353                 mgmtcli_deregister_for_events_t dereg_f;
354
355                 dereg_f = (mgmtcli_deregister_for_events_t)symbol_get("mgmtcli_deregister_for_events");
356                 dereg_f(cli->cl_mgmtcli_obd, obddev);
357                 symbol_put("mgmtcli_deregister_for_events");
358         }
359
360         /* Here we try to drop the security structure after destroy import,
361          * to avoid issue of "sleep in spinlock".
362          */
363         class_import_get(cli->cl_import);
364         class_destroy_import(cli->cl_import);
365         ptlrpcs_import_drop_sec(cli->cl_import);
366         class_import_put(cli->cl_import);
367         cli->cl_import = NULL;
368
369         ldlm_put_ref(flags & OBD_OPT_FORCE);
370
371         RETURN(0);
372 }
373
374 int client_connect_import(struct lustre_handle *dlm_handle,
375                           struct obd_device *obd,
376                           struct obd_uuid *cluuid,
377                           struct obd_connect_data *conn_data,
378                           unsigned long connect_flags)
379 {
380         struct client_obd *cli = &obd->u.cli;
381         struct obd_import *imp = cli->cl_import;
382         struct obd_export *exp;
383         int rc;
384         ENTRY;
385
386         down(&cli->cl_sem);
387         rc = class_connect(dlm_handle, obd, cluuid);
388         if (rc)
389                 GOTO(out_sem, rc);
390
391         cli->cl_conn_count++;
392         if (cli->cl_conn_count > 1)
393                 GOTO(out_sem, rc);
394         exp = class_conn2export(dlm_handle);
395
396         if (obd->obd_namespace != NULL)
397                 CERROR("already have namespace!\n");
398         obd->obd_namespace = ldlm_namespace_new(obd->obd_name,
399                                                 LDLM_NAMESPACE_CLIENT);
400         if (obd->obd_namespace == NULL)
401                 GOTO(out_disco, rc = -ENOMEM);
402
403         rc = ptlrpcs_import_get_sec(imp);
404         if (rc != 0)
405                 GOTO(out_ldlm, rc);
406
407         imp->imp_dlm_handle = *dlm_handle;
408         rc = ptlrpc_init_import(imp);
409         if (rc != 0) 
410                 GOTO(out_ldlm, rc);
411
412         imp->imp_connect_flags = connect_flags;
413         if (conn_data)
414                 memcpy(&imp->imp_connect_data, conn_data, sizeof(*conn_data));
415
416         rc = ptlrpc_connect_import(imp, NULL);
417         if (rc != 0) {
418                 LASSERT (imp->imp_state == LUSTRE_IMP_DISCON);
419                 GOTO(out_ldlm, rc);
420         }
421         LASSERT(exp->exp_connection);
422         ptlrpc_pinger_add_import(imp);
423         EXIT;
424
425         if (rc) {
426 out_ldlm:
427                 ldlm_namespace_free(obd->obd_namespace, 0);
428                 obd->obd_namespace = NULL;
429 out_disco:
430                 cli->cl_conn_count--;
431                 class_disconnect(exp, 0);
432         } else {
433                 class_export_put(exp);
434         }
435 out_sem:
436         up(&cli->cl_sem);
437         return rc;
438 }
439
440 int client_disconnect_export(struct obd_export *exp, unsigned long flags)
441 {
442         struct obd_device *obd = class_exp2obd(exp);
443         struct client_obd *cli = &obd->u.cli;
444         struct obd_import *imp = cli->cl_import;
445         int rc = 0, err;
446         ENTRY;
447
448         if (!obd) {
449                 CERROR("invalid export for disconnect: exp %p cookie "LPX64"\n",
450                        exp, exp ? exp->exp_handle.h_cookie : -1);
451                 RETURN(-EINVAL);
452         }
453
454         down(&cli->cl_sem);
455         if (!cli->cl_conn_count) {
456                 CERROR("disconnecting disconnected device (%s)\n",
457                        obd->obd_name);
458                 GOTO(out_sem, rc = -EINVAL);
459         }
460
461         cli->cl_conn_count--;
462         if (cli->cl_conn_count)
463                 GOTO(out_no_disconnect, rc = 0);
464
465         /* Some non-replayable imports (MDS's OSCs) are pinged, so just
466          * delete it regardless.  (It's safe to delete an import that was
467          * never added.) */
468         (void)ptlrpc_pinger_del_import(imp);
469
470         if (obd->obd_namespace != NULL) {
471                 /* obd_no_recov == local only */
472                 ldlm_cli_cancel_unused(obd->obd_namespace, NULL,
473                                        obd->obd_no_recov, NULL);
474                 ldlm_namespace_free(obd->obd_namespace, obd->obd_no_recov);
475                 obd->obd_namespace = NULL;
476         }
477
478         /* 
479          * Yeah, obd_no_recov also (mainly) means "forced shutdown".
480          */
481         if (obd->obd_no_recov)
482                 ptlrpc_invalidate_import(imp, 0);
483         else
484                 rc = ptlrpc_disconnect_import(imp);
485
486         EXIT;
487  out_no_disconnect:
488         err = class_disconnect(exp, 0);
489         if (!rc && err)
490                 rc = err;
491  out_sem:
492         up(&cli->cl_sem);
493         RETURN(rc);
494 }
495
496 /* --------------------------------------------------------------------------
497  * from old lib/target.c
498  * -------------------------------------------------------------------------- */
499
500 int target_handle_reconnect(struct lustre_handle *conn, struct obd_export *exp,
501                             struct obd_uuid *cluuid, int initial_conn)
502 {
503         if (exp->exp_connection && !initial_conn) {
504                 struct lustre_handle *hdl;
505                 hdl = &exp->exp_imp_reverse->imp_remote_handle;
506                 /* Might be a re-connect after a partition. */
507                 if (!memcmp(&conn->cookie, &hdl->cookie, sizeof conn->cookie)) {
508                         CERROR("%s reconnecting\n", cluuid->uuid);
509                         conn->cookie = exp->exp_handle.h_cookie;
510                         RETURN(EALREADY);
511                 } else {
512                         CERROR("%s reconnecting from %s, "
513                                "handle mismatch (ours "LPX64", theirs "
514                                LPX64")\n", cluuid->uuid,
515                                exp->exp_connection->c_remote_uuid.uuid,
516                                hdl->cookie, conn->cookie);
517                         memset(conn, 0, sizeof *conn);
518                         RETURN(-EALREADY);
519                 }
520         }
521
522         conn->cookie = exp->exp_handle.h_cookie;
523         CDEBUG(D_INFO, "existing export for UUID '%s' at %p\n",
524                cluuid->uuid, exp);
525         CDEBUG(D_IOCTL,"connect: cookie "LPX64"\n", conn->cookie);
526         RETURN(0);
527 }
528
529 static inline int ptlrpc_peer_is_local(struct ptlrpc_peer *peer)
530 {
531         ptl_process_id_t myid;
532
533         PtlGetId(peer->peer_ni->pni_ni_h, &myid);
534         return (memcmp(&peer->peer_id, &myid, sizeof(myid)) == 0);
535 }
536
537 int target_handle_connect(struct ptlrpc_request *req)
538 {
539         unsigned long connect_flags = 0, *cfp;
540         struct obd_device *target;
541         struct obd_export *export = NULL;
542         struct obd_import *revimp;
543         struct lustre_handle conn;
544         struct obd_uuid tgtuuid;
545         struct obd_uuid cluuid;
546         struct obd_uuid remote_uuid;
547         struct list_head *p;
548         struct obd_connect_data *conn_data;
549         int conn_data_size = sizeof(*conn_data);
550         char *str, *tmp;
551         int rc = 0;
552         unsigned long flags;
553         int initial_conn = 0;
554         char peer_str[PTL_NALFMT_SIZE];
555         const int offset = 1;
556         ENTRY;
557
558         OBD_RACE(OBD_FAIL_TGT_CONN_RACE); 
559
560         LASSERT_REQSWAB (req, offset + 0);
561         str = lustre_msg_string(req->rq_reqmsg, offset + 0,
562                                 sizeof(tgtuuid) - 1);
563         if (str == NULL) {
564                 CERROR("bad target UUID for connect\n");
565                 GOTO(out, rc = -EINVAL);
566         }
567
568         obd_str2uuid (&tgtuuid, str);
569         target = class_uuid2obd(&tgtuuid);
570         if (!target)
571                 target = class_name2obd(str);
572         
573         if (!target || target->obd_stopping || !target->obd_set_up) {
574                 CERROR("UUID '%s' is not available for connect from %s\n",
575                        str, req->rq_peerstr);
576                 GOTO(out, rc = -ENODEV);
577         }
578
579         LASSERT_REQSWAB (req, offset + 1);
580         str = lustre_msg_string(req->rq_reqmsg, offset + 1, sizeof(cluuid) - 1);
581         if (str == NULL) {
582                 CERROR("bad client UUID for connect\n");
583                 GOTO(out, rc = -EINVAL);
584         }
585
586         obd_str2uuid (&cluuid, str);
587
588         /* XXX extract a nettype and format accordingly */
589         switch (sizeof(ptl_nid_t)) {
590                 /* NB the casts only avoid compiler warnings */
591         case 8:
592                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
593                          "NET_"LPX64"_UUID", (__u64)req->rq_peer.peer_id.nid);
594                 break;
595         case 4:
596                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
597                          "NET_%x_UUID", (__u32)req->rq_peer.peer_id.nid);
598                 break;
599         default:
600                 LBUG();
601         }
602
603         tmp = lustre_msg_buf(req->rq_reqmsg, offset + 2, sizeof conn);
604         if (tmp == NULL)
605                 GOTO(out, rc = -EPROTO);
606
607         memcpy(&conn, tmp, sizeof conn);
608
609         cfp = lustre_msg_buf(req->rq_reqmsg, offset + 3, sizeof(unsigned long));
610         LASSERT(cfp != NULL);
611         connect_flags = *cfp;
612
613         conn_data = lustre_swab_reqbuf(req, offset + 4, sizeof(*conn_data),
614                                        lustre_swab_connect);
615         if (!conn_data)
616                 GOTO(out, rc = -EPROTO);
617
618         rc = lustre_pack_reply(req, 1, &conn_data_size, NULL);
619         if (rc)
620                 GOTO(out, rc);
621         
622         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_INITIAL)
623                 initial_conn = 1;
624         
625         /* lctl gets a backstage, all-access pass. */
626         if (obd_uuid_equals(&cluuid, &target->obd_uuid))
627                 goto dont_check_exports;
628
629         spin_lock(&target->obd_dev_lock);
630         list_for_each(p, &target->obd_exports) {
631                 export = list_entry(p, struct obd_export, exp_obd_chain);
632                 if (obd_uuid_equals(&cluuid, &export->exp_client_uuid)) {
633                         spin_unlock(&target->obd_dev_lock);
634                         LASSERT(export->exp_obd == target);
635
636                         rc = target_handle_reconnect(&conn, export, &cluuid,
637                                                      initial_conn);
638                         break;
639                 }
640                 export = NULL;
641         }
642         /* If we found an export, we already unlocked. */
643         if (!export) {
644                 spin_unlock(&target->obd_dev_lock);
645         } else if (req->rq_export == NULL && 
646                    atomic_read(&export->exp_rpc_count) > 0) {
647                 CWARN("%s: refuse connection from %s/%s to 0x%p/%d\n",
648                       target->obd_name, cluuid.uuid,
649                       ptlrpc_peernid2str(&req->rq_peer, peer_str),
650                       export, atomic_read(&export->exp_refcount));
651                 GOTO(out, rc = -EBUSY);
652         } else if (req->rq_export != NULL &&
653                    atomic_read(&export->exp_rpc_count) > 1) {
654                 CWARN("%s: refuse reconnection from %s@%s to 0x%p/%d\n",
655                       target->obd_name, cluuid.uuid,
656                       ptlrpc_peernid2str(&req->rq_peer, peer_str),
657                       export, atomic_read(&export->exp_rpc_count));
658                 GOTO(out, rc = -EBUSY);
659         } else if (req->rq_reqmsg->conn_cnt == 1 && !initial_conn) {
660                 CERROR("%s reconnected with 1 conn_cnt; cookies not random?\n",
661                        cluuid.uuid);
662                 GOTO(out, rc = -EALREADY);
663         }
664
665         /* Tell the client if we're in recovery. */
666         /* If this is the first client, start the recovery timer */
667         CWARN("%s: connection from %s@%s/%lu %s\n", target->obd_name, cluuid.uuid,
668               ptlrpc_peernid2str(&req->rq_peer, peer_str), *cfp,
669               target->obd_recovering ? "(recovering)" : "");
670
671         if (target->obd_recovering) {
672                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
673                 target_start_recovery_timer(target);
674         }
675
676 #if 0
677         /* Tell the client if we support replayable requests */
678         if (target->obd_replayable)
679                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
680 #endif
681
682         if (export == NULL) {
683                 if (target->obd_recovering) {
684                         CERROR("%s denying connection for new client %s@%s: "
685                                "%d clients in recovery for %lds\n", target->obd_name, 
686                                cluuid.uuid,
687                                ptlrpc_peernid2str(&req->rq_peer, peer_str),
688                                target->obd_recoverable_clients,
689                                (target->obd_recovery_timer.expires-jiffies)/HZ);
690                         rc = -EBUSY;
691                 } else {
692  dont_check_exports:
693                         rc = obd_connect(&conn, target, &cluuid, conn_data,
694                                          connect_flags);
695                 }
696         }
697
698         /* Return only the parts of obd_connect_data that we understand, so the
699          * client knows that we don't understand the rest. */
700         conn_data->ocd_connect_flags &= OBD_CONNECT_SUPPORTED;
701         memcpy(lustre_msg_buf(req->rq_repmsg, 0, sizeof(*conn_data)), conn_data,
702                sizeof(*conn_data));
703
704         /* Tell the client if we support replayable requests */
705         if (target->obd_replayable)
706                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
707
708         /* If all else goes well, this is our RPC return code. */
709         req->rq_status = 0;
710
711         if (rc && rc != EALREADY)
712                 GOTO(out, rc);
713
714         req->rq_repmsg->handle = conn;
715
716         /* If the client and the server are the same node, we will already
717          * have an export that really points to the client's DLM export,
718          * because we have a shared handles table.
719          *
720          * XXX this will go away when shaver stops sending the "connect" handle
721          * in the real "remote handle" field of the request --phik 24 Apr 2003
722          */
723         if (req->rq_export != NULL)
724                 class_export_put(req->rq_export);
725
726         /* ownership of this export ref transfers to the request */
727         export = req->rq_export = class_conn2export(&conn);
728         LASSERT(export != NULL);
729
730         spin_lock_irqsave(&export->exp_lock, flags);
731         if (initial_conn) {
732                 req->rq_repmsg->conn_cnt = export->exp_conn_cnt + 1;
733         } else if (export->exp_conn_cnt >= req->rq_reqmsg->conn_cnt) {
734                 CERROR("%s@%s: already connected at a higher conn_cnt: %d > %d\n",
735                        cluuid.uuid, ptlrpc_peernid2str(&req->rq_peer, peer_str),
736                        export->exp_conn_cnt, 
737                        req->rq_reqmsg->conn_cnt);
738                 spin_unlock_irqrestore(&export->exp_lock, flags);
739                 GOTO(out, rc = -EALREADY);
740         } 
741         export->exp_conn_cnt = req->rq_reqmsg->conn_cnt;
742         spin_unlock_irqrestore(&export->exp_lock, flags);
743
744         /* request from liblustre? */
745         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT)
746                 export->exp_libclient = 1;
747
748         if (!(lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_ASYNC) &&
749             ptlrpc_peer_is_local(&req->rq_peer)) {
750                 CWARN("%s: exp %p set sync\n", target->obd_name, export);
751                 export->exp_sync = 1;
752         } else {
753                 CDEBUG(D_HA, "%s: exp %p set async\n",target->obd_name,export);
754                 export->exp_sync = 0;
755         }
756
757         if (export->exp_connection != NULL)
758                 ptlrpc_put_connection(export->exp_connection);
759         export->exp_connection = ptlrpc_get_connection(&req->rq_peer,
760                                                        &remote_uuid);
761
762         if (rc == EALREADY) {
763                 /* We indicate the reconnection in a flag, not an error code. */
764                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECONNECT);
765                 GOTO(out, rc = 0);
766         }
767
768         if (target->obd_recovering)
769                 target->obd_connected_clients++;
770
771         memcpy(&conn, lustre_msg_buf(req->rq_reqmsg, offset + 2, sizeof(conn)),
772                sizeof(conn));
773
774         if (export->exp_imp_reverse != NULL) {
775                 /* same logic as client_obd_cleanup */
776                 class_import_get(export->exp_imp_reverse);
777                 class_destroy_import(export->exp_imp_reverse);
778                 ptlrpcs_import_drop_sec(export->exp_imp_reverse);
779                 class_import_put(export->exp_imp_reverse);
780         }
781
782         /* for the rest part, we return -ENOTCONN in case of errors
783          * in order to let client initialize connection again.
784          */
785         revimp = export->exp_imp_reverse = class_new_import();
786         if (!revimp) {
787                 CERROR("fail to alloc new reverse import.\n");
788                 GOTO(out, rc = -ENOTCONN);
789         }
790
791         revimp->imp_connection = ptlrpc_connection_addref(export->exp_connection);
792         revimp->imp_client = &export->exp_obd->obd_ldlm_client;
793         revimp->imp_remote_handle = conn;
794         revimp->imp_obd = target;
795         revimp->imp_dlm_fake = 1;
796         revimp->imp_state = LUSTRE_IMP_FULL;
797
798         rc = ptlrpcs_import_get_sec(revimp);
799         if (rc) {
800                 CERROR("reverse import can not get sec: %d\n", rc);
801                 class_destroy_import(revimp);
802                 export->exp_imp_reverse = NULL;
803                 GOTO(out, rc = -ENOTCONN);
804         }
805
806         class_import_put(revimp);
807
808         rc = obd_connect_post(export, initial_conn, connect_flags);
809 out:
810         if (rc)
811                 req->rq_status = rc;
812         RETURN(rc);
813 }
814
815 int target_handle_disconnect(struct ptlrpc_request *req)
816 {
817         struct obd_export *exp;
818         int rc;
819         ENTRY;
820
821         rc = lustre_pack_reply(req, 0, NULL, NULL);
822         if (rc)
823                 RETURN(rc);
824
825         /* keep the rq_export around so we can send the reply */
826         exp = class_export_get(req->rq_export);
827         req->rq_status = obd_disconnect(exp, 0);
828         RETURN(0);
829 }
830
831 void target_destroy_export(struct obd_export *exp)
832 {
833         /* exports created from last_rcvd data, and "fake"
834            exports created by lctl don't have an import */
835         if (exp->exp_imp_reverse != NULL) {
836                 ptlrpcs_import_drop_sec(exp->exp_imp_reverse);
837                 class_destroy_import(exp->exp_imp_reverse);
838         }
839
840         /* We cancel locks at disconnect time, but this will catch any locks
841          * granted in a race with recovery-induced disconnect. */
842         if (exp->exp_obd->obd_namespace != NULL)
843                 ldlm_cancel_locks_for_export(exp);
844 }
845
846 /*
847  * Recovery functions
848  */
849
850 struct ptlrpc_request *
851 ptlrpc_clone_req( struct ptlrpc_request *orig_req) 
852 {
853         struct ptlrpc_request *copy_req;
854         struct lustre_msg *copy_reqmsg;
855
856         OBD_ALLOC(copy_req, sizeof *copy_req);
857         if (!copy_req)
858                 return NULL;
859         OBD_ALLOC(copy_reqmsg, orig_req->rq_reqlen);
860         if (!copy_reqmsg){
861                 OBD_FREE(copy_req, sizeof *copy_req);
862                 return NULL;
863         }
864
865         memcpy(copy_req, orig_req, sizeof *copy_req);
866         memcpy(copy_reqmsg, orig_req->rq_reqmsg, orig_req->rq_reqlen);
867         /* the copied req takes over the reply state and security data */
868         orig_req->rq_reply_state = NULL;
869         orig_req->rq_sec_svcdata = NULL;
870
871         copy_req->rq_reqmsg = copy_reqmsg;
872         class_export_get(copy_req->rq_export);
873         INIT_LIST_HEAD(&copy_req->rq_list);
874
875         return copy_req;
876 }
877
878 void ptlrpc_free_clone( struct ptlrpc_request *req) 
879 {
880         if (req->rq_svcsec)
881                 svcsec_cleanup_req(req);
882
883         class_export_put(req->rq_export);
884         list_del(&req->rq_list);
885         OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
886         OBD_FREE(req, sizeof *req);
887 }
888
889 static void target_release_saved_req(struct ptlrpc_request *req)
890 {
891         if (req->rq_svcsec)
892                 svcsec_cleanup_req(req);
893
894         class_export_put(req->rq_export);
895         OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
896         OBD_FREE(req, sizeof *req);
897 }
898
899 static void target_finish_recovery(struct obd_device *obd)
900 {
901         int rc;
902
903         ldlm_reprocess_all_ns(obd->obd_namespace);
904
905         /* when recovery finished, cleanup orphans on mds and ost */
906         if (OBT(obd) && OBP(obd, postrecov)) {
907                 rc = OBP(obd, postrecov)(obd);
908                 if (rc >= 0)
909                         CWARN("%s: all clients recovered, %d MDS "
910                               "orphans deleted\n", obd->obd_name, rc);
911                 else
912                         CERROR("postrecov failed %d\n", rc);
913         }
914
915         obd->obd_recovery_end = LTIME_S(CURRENT_TIME);
916         return;
917 }
918
919 static void abort_req_replay_queue(struct obd_device *obd)
920 {
921         struct ptlrpc_request *req;
922         struct list_head *tmp, *n;
923         int rc;
924
925         list_for_each_safe(tmp, n, &obd->obd_req_replay_queue) {
926                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
927                 list_del(&req->rq_list);
928                 DEBUG_REQ(D_ERROR, req, "aborted:");
929                 req->rq_status = -ENOTCONN;
930                 req->rq_type = PTL_RPC_MSG_ERR;
931                 rc = lustre_pack_reply(req, 0, NULL, NULL);
932                 if (rc == 0) {
933                         ptlrpc_reply(req);
934                 } else {
935                         DEBUG_REQ(D_ERROR, req,
936                                   "packing failed for abort-reply; skipping");
937                 }
938                 target_release_saved_req(req);
939         }
940 }
941
942 static void abort_lock_replay_queue(struct obd_device *obd)
943 {
944         struct ptlrpc_request *req;
945         struct list_head *tmp, *n;
946         int rc;
947
948         list_for_each_safe(tmp, n, &obd->obd_lock_replay_queue) {
949                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
950                 list_del(&req->rq_list);
951                 DEBUG_REQ(D_ERROR, req, "aborted:");
952                 req->rq_status = -ENOTCONN;
953                 req->rq_type = PTL_RPC_MSG_ERR;
954                 rc = lustre_pack_reply(req, 0, NULL, NULL);
955                 if (rc == 0) {
956                         ptlrpc_reply(req);
957                 } else {
958                         DEBUG_REQ(D_ERROR, req,
959                                   "packing failed for abort-reply; skipping");
960                 }
961                 target_release_saved_req(req);
962         }
963 }
964
965 /* Called from a cleanup function if the device is being cleaned up
966    forcefully.  The exports should all have been disconnected already,
967    the only thing left to do is
968      - clear the recovery flags
969      - cancel the timer
970      - free queued requests and replies, but don't send replies
971    Because the obd_stopping flag is set, no new requests should be received.
972
973 */
974 void target_cleanup_recovery(struct obd_device *obd)
975 {
976         struct list_head *tmp, *n;
977         struct ptlrpc_request *req;
978
979         spin_lock_bh(&obd->obd_processing_task_lock);
980         if (!obd->obd_recovering) {
981                 spin_unlock_bh(&obd->obd_processing_task_lock);
982                 EXIT;
983                 return;
984         }
985         obd->obd_recovering = obd->obd_abort_recovery = 0;
986         target_cancel_recovery_timer(obd);
987         spin_unlock_bh(&obd->obd_processing_task_lock);
988
989         list_for_each_safe(tmp, n, &obd->obd_req_replay_queue) {
990                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
991                 list_del(&req->rq_list);
992                 LASSERT (req->rq_reply_state == 0);
993                 target_release_saved_req(req);
994         }
995         list_for_each_safe(tmp, n, &obd->obd_lock_replay_queue) {
996                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
997                 list_del(&req->rq_list);
998                 LASSERT (req->rq_reply_state == 0);
999                 target_release_saved_req(req);
1000         }
1001         list_for_each_safe(tmp, n, &obd->obd_final_req_queue) {
1002                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
1003                 list_del(&req->rq_list);
1004                 LASSERT (req->rq_reply_state == 0);
1005                 target_release_saved_req(req);
1006         }
1007 }
1008
1009 #if 0
1010 static void target_abort_recovery(void *data)
1011 {
1012         struct obd_device *obd = data;
1013
1014         LASSERT(!obd->obd_recovering);
1015
1016         class_disconnect_stale_exports(obd, 0);
1017
1018         CERROR("%s: recovery period over; disconnecting unfinished clients.\n",
1019                obd->obd_name);
1020
1021         abort_recovery_queue(obd);
1022         target_finish_recovery(obd);
1023         ptlrpc_run_recovery_over_upcall(obd);
1024 }
1025 #endif
1026
1027 static void target_recovery_expired(unsigned long castmeharder)
1028 {
1029         struct obd_device *obd = (struct obd_device *)castmeharder;
1030         spin_lock_bh(&obd->obd_processing_task_lock);
1031         if (obd->obd_recovering)
1032                 obd->obd_abort_recovery = 1;
1033
1034         wake_up(&obd->obd_next_transno_waitq);
1035         spin_unlock_bh(&obd->obd_processing_task_lock);
1036 }
1037
1038
1039 /* obd_processing_task_lock should be held */
1040 void target_cancel_recovery_timer(struct obd_device *obd)
1041 {
1042         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1043         del_timer(&obd->obd_recovery_timer);
1044 }
1045
1046 #ifdef __KERNEL__
1047 static void reset_recovery_timer(struct obd_device *obd)
1048 {
1049         spin_lock_bh(&obd->obd_processing_task_lock);
1050         if (!obd->obd_recovering) {
1051                 spin_unlock_bh(&obd->obd_processing_task_lock);
1052                 return;
1053         }                
1054         CDEBUG(D_HA, "timer will expire in %u seconds\n",
1055                OBD_RECOVERY_TIMEOUT / HZ);
1056         mod_timer(&obd->obd_recovery_timer, jiffies + OBD_RECOVERY_TIMEOUT);
1057         spin_unlock_bh(&obd->obd_processing_task_lock);
1058 }
1059 #endif
1060
1061 /* Only start it the first time called */
1062 void target_start_recovery_timer(struct obd_device *obd)
1063 {
1064         spin_lock_bh(&obd->obd_processing_task_lock);
1065         if (!obd->obd_recovering || timer_pending(&obd->obd_recovery_timer)) {
1066                 spin_unlock_bh(&obd->obd_processing_task_lock);
1067                 return;
1068         }
1069         CWARN("%s: starting recovery timer (%us)\n", obd->obd_name,
1070                OBD_RECOVERY_TIMEOUT / HZ);
1071         obd->obd_recovery_timer.function = target_recovery_expired;
1072         obd->obd_recovery_timer.data = (unsigned long)obd;
1073         mod_timer(&obd->obd_recovery_timer, jiffies + OBD_RECOVERY_TIMEOUT);
1074         spin_unlock_bh(&obd->obd_processing_task_lock);
1075 }
1076
1077 #ifdef __KERNEL__
1078 static int check_for_next_transno(struct obd_device *obd)
1079 {
1080         struct ptlrpc_request *req = NULL;
1081         int wake_up = 0, connected, completed, queue_len, max;
1082         __u64 next_transno, req_transno;
1083
1084         spin_lock_bh(&obd->obd_processing_task_lock);
1085         if (!list_empty(&obd->obd_req_replay_queue)) {
1086                 req = list_entry(obd->obd_req_replay_queue.next,
1087                                  struct ptlrpc_request, rq_list);
1088                 req_transno = req->rq_reqmsg->transno;
1089         } else {
1090                 req_transno = 0;
1091         }
1092
1093         max = obd->obd_max_recoverable_clients;
1094         connected = obd->obd_connected_clients;
1095         completed = max - atomic_read(&obd->obd_req_replay_clients);
1096         queue_len = obd->obd_requests_queued_for_recovery;
1097         next_transno = obd->obd_next_recovery_transno;
1098
1099         CDEBUG(D_HA,"max: %d, connected: %d, completed: %d, queue_len: %d, "
1100                "req_transno: "LPU64", next_transno: "LPU64"\n",
1101                max, connected, completed, queue_len, req_transno, next_transno);
1102         if (obd->obd_abort_recovery) {
1103                 CDEBUG(D_HA, "waking for aborted recovery\n");
1104                 wake_up = 1;
1105         } else if (atomic_read(&obd->obd_req_replay_clients) == 0) {
1106                 CDEBUG(D_HA, "waking for completed recovery\n");
1107                 wake_up = 1;
1108         } else if (req_transno == next_transno) {
1109                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1110                 wake_up = 1;
1111         } else if (queue_len + completed == max) {
1112                 LASSERT(req->rq_reqmsg->transno >= next_transno);
1113                 CDEBUG(D_ERROR,
1114                        "waking for skipped transno (skip: "LPD64
1115                        ", ql: %d, comp: %d, conn: %d, next: "LPD64")\n",
1116                        next_transno, queue_len, completed, max, req_transno);
1117                 obd->obd_next_recovery_transno = req_transno;
1118                 wake_up = 1;
1119         }
1120         spin_unlock_bh(&obd->obd_processing_task_lock);
1121         
1122         return wake_up;
1123 }
1124
1125 static struct ptlrpc_request *
1126 target_next_replay_req(struct obd_device *obd)
1127 {
1128         struct l_wait_info lwi = { 0 };
1129         struct ptlrpc_request *req;
1130
1131         CDEBUG(D_HA, "Waiting for transno "LPD64"\n",
1132                obd->obd_next_recovery_transno);
1133         l_wait_event(obd->obd_next_transno_waitq,
1134                      check_for_next_transno(obd), &lwi);
1135         
1136         spin_lock_bh(&obd->obd_processing_task_lock);
1137         if (obd->obd_abort_recovery) {
1138                 req = NULL;
1139         } else if (!list_empty(&obd->obd_req_replay_queue)) {
1140                 req = list_entry(obd->obd_req_replay_queue.next,
1141                                  struct ptlrpc_request, rq_list);
1142                 list_del_init(&req->rq_list);
1143                 obd->obd_requests_queued_for_recovery--;
1144         } else {
1145                 req = NULL;
1146         }
1147         spin_unlock_bh(&obd->obd_processing_task_lock);
1148         return req;
1149 }
1150
1151 static int check_for_next_lock(struct obd_device *obd)
1152 {
1153         struct ptlrpc_request *req = NULL;
1154         int wake_up = 0;
1155
1156         spin_lock_bh(&obd->obd_processing_task_lock);
1157         if (!list_empty(&obd->obd_lock_replay_queue)) {
1158                 req = list_entry(obd->obd_lock_replay_queue.next,
1159                                  struct ptlrpc_request, rq_list);
1160                 CDEBUG(D_HA, "waking for next lock\n");
1161                 wake_up = 1;
1162         } else if (atomic_read(&obd->obd_lock_replay_clients) == 0) {
1163                 CDEBUG(D_HA, "waking for completed lock replay\n");
1164                 wake_up = 1;
1165         } else if (obd->obd_abort_recovery) {
1166                 CDEBUG(D_HA, "waking for aborted recovery\n");
1167                 wake_up = 1;
1168         }
1169         spin_unlock_bh(&obd->obd_processing_task_lock);
1170         
1171         return wake_up;
1172 }
1173
1174 static struct ptlrpc_request *
1175 target_next_replay_lock(struct obd_device *obd)
1176 {
1177         struct l_wait_info lwi = { 0 };
1178         struct ptlrpc_request *req;
1179
1180         CDEBUG(D_HA, "Waiting for lock\n");
1181         l_wait_event(obd->obd_next_transno_waitq,
1182                      check_for_next_lock(obd), &lwi);
1183         
1184         spin_lock_bh(&obd->obd_processing_task_lock);
1185         if (obd->obd_abort_recovery) {
1186                 req = NULL;
1187         } else if (!list_empty(&obd->obd_lock_replay_queue)) {
1188                 req = list_entry(obd->obd_lock_replay_queue.next,
1189                                  struct ptlrpc_request, rq_list);
1190                 list_del_init(&req->rq_list);
1191         } else {
1192                 req = NULL;
1193         }
1194         spin_unlock_bh(&obd->obd_processing_task_lock);
1195         return req;
1196 }
1197
1198 static struct ptlrpc_request *
1199 target_next_final_ping(struct obd_device *obd)
1200 {
1201         struct ptlrpc_request *req;
1202
1203         spin_lock_bh(&obd->obd_processing_task_lock);
1204         if (!list_empty(&obd->obd_final_req_queue)) {
1205                 req = list_entry(obd->obd_final_req_queue.next,
1206                                  struct ptlrpc_request, rq_list);
1207                 list_del_init(&req->rq_list);
1208         } else {
1209                 req = NULL;
1210         }
1211         spin_unlock_bh(&obd->obd_processing_task_lock);
1212         return req;
1213 }
1214
1215 static int req_replay_done(struct obd_export *exp)
1216 {
1217         if (exp->exp_req_replay_needed)
1218                 return 0;
1219         return 1;
1220 }
1221
1222 static int lock_replay_done(struct obd_export *exp)
1223 {
1224         if (exp->exp_lock_replay_needed)
1225                 return 0;
1226         return 1;
1227 }
1228
1229 static int target_recovery_thread(void *arg)
1230 {
1231         struct obd_device *obd = arg;
1232         struct ptlrpc_request *req;
1233         struct target_recovery_data *trd = &obd->obd_recovery_data;
1234         char peer_str[PTL_NALFMT_SIZE];
1235         unsigned long flags;
1236         ENTRY;
1237
1238         kportal_daemonize("tgt-recov");
1239
1240         SIGNAL_MASK_LOCK(current, flags);
1241         sigfillset(&current->blocked);
1242         RECALC_SIGPENDING;
1243         SIGNAL_MASK_UNLOCK(current, flags);
1244
1245         CERROR("%s: started recovery thread pid %d\n", obd->obd_name, 
1246                current->pid);
1247         trd->trd_processing_task = current->pid;
1248
1249         obd->obd_recovering = 1;
1250         complete(&trd->trd_starting);
1251
1252         /* The first stage: replay requests */
1253         CWARN("1: request replay stage - %d clients\n",
1254               atomic_read(&obd->obd_req_replay_clients));
1255         while ((req = target_next_replay_req(obd))) {
1256                 LASSERT(trd->trd_processing_task == current->pid);
1257                 DEBUG_REQ(D_HA, req, "processing t"LPD64" from %s: ", 
1258                           req->rq_reqmsg->transno, 
1259                           ptlrpc_peernid2str(&req->rq_peer, peer_str));
1260                 (void)trd->trd_recovery_handler(req);
1261                 obd->obd_replayed_requests++;
1262                 reset_recovery_timer(obd);
1263                 /* bug 1580: decide how to properly sync() in recovery*/
1264                 //mds_fsync_super(mds->mds_sb);
1265                 ptlrpc_free_clone(req);
1266                 spin_lock_bh(&obd->obd_processing_task_lock);
1267                 obd->obd_next_recovery_transno++;
1268                 spin_unlock_bh(&obd->obd_processing_task_lock);
1269         }
1270
1271         spin_lock_bh(&obd->obd_processing_task_lock);
1272         target_cancel_recovery_timer(obd);
1273         spin_unlock_bh(&obd->obd_processing_task_lock);
1274
1275         /* If some clients haven't replayed requests in time, evict them */
1276         if (obd->obd_abort_recovery) {
1277                 int stale;
1278                 CERROR("req replay timed out, aborting ...\n");
1279                 obd->obd_abort_recovery = 0;
1280                 stale = class_disconnect_stale_exports(obd, req_replay_done, 0);
1281                 atomic_sub(stale, &obd->obd_lock_replay_clients);
1282                 abort_req_replay_queue(obd);
1283         }
1284
1285         /* The second stage: replay locks */
1286         CWARN("2: lock replay stage - %d clients\n",
1287               atomic_read(&obd->obd_lock_replay_clients));
1288         while ((req = target_next_replay_lock(obd))) {
1289                 LASSERT(trd->trd_processing_task == current->pid);
1290                 DEBUG_REQ(D_HA, req, "processing lock from %s: ", 
1291                           ptlrpc_peernid2str(&req->rq_peer, peer_str));
1292                 (void)trd->trd_recovery_handler(req);
1293                 reset_recovery_timer(obd);
1294                 ptlrpc_free_clone(req);
1295                 obd->obd_replayed_locks++;
1296         }
1297         
1298         spin_lock_bh(&obd->obd_processing_task_lock);
1299         target_cancel_recovery_timer(obd);
1300         spin_unlock_bh(&obd->obd_processing_task_lock);
1301
1302         /* If some clients haven't replayed requests in time, evict them */
1303         if (obd->obd_abort_recovery) {
1304                 int stale;
1305                 CERROR("lock replay timed out, aborting ...\n");
1306                 obd->obd_abort_recovery = 0;
1307                 stale = class_disconnect_stale_exports(obd, lock_replay_done, 0);
1308                 abort_lock_replay_queue(obd);
1309         }
1310
1311         /* We drop recoverying flag to forward all new requests
1312          * to regular mds_handle() since now */
1313         spin_lock_bh(&obd->obd_processing_task_lock);
1314         obd->obd_recovering = 0;
1315         spin_unlock_bh(&obd->obd_processing_task_lock);
1316
1317         /* The third stage: reply on final pings */
1318         CWARN("3: final stage - process recovery completion pings\n");
1319         while ((req = target_next_final_ping(obd))) {
1320                 LASSERT(trd->trd_processing_task == current->pid);
1321                 DEBUG_REQ(D_HA, req, "processing final ping from %s: ", 
1322                           ptlrpc_peernid2str(&req->rq_peer, peer_str));
1323                 (void)trd->trd_recovery_handler(req);
1324                 ptlrpc_free_clone(req);
1325         }
1326         
1327         CWARN("4: recovery completed - %d/%d reqs/locks replayed\n",
1328               obd->obd_replayed_requests, obd->obd_replayed_locks);
1329         target_finish_recovery(obd);
1330
1331         trd->trd_processing_task = 0;
1332         complete(&trd->trd_finishing);
1333         return 0;
1334 }
1335
1336 int target_start_recovery_thread(struct obd_device *obd, svc_handler_t handler)
1337 {
1338         int rc = 0;
1339         struct target_recovery_data *trd = &obd->obd_recovery_data;
1340
1341         memset(trd, 0, sizeof(*trd));
1342         init_completion(&trd->trd_starting);
1343         init_completion(&trd->trd_finishing);
1344         trd->trd_recovery_handler = handler;
1345
1346         if (kernel_thread(target_recovery_thread, obd, 0) == 0) 
1347                 wait_for_completion(&trd->trd_starting);
1348         else
1349                 rc = -ECHILD;
1350
1351         return rc;
1352 }
1353
1354 void target_stop_recovery_thread(struct obd_device *obd)
1355 {
1356         spin_lock_bh(&obd->obd_processing_task_lock);
1357         if (obd->obd_recovery_data.trd_processing_task > 0) {
1358                 struct target_recovery_data *trd = &obd->obd_recovery_data;
1359                 CERROR("%s: aborting recovery\n", obd->obd_name);
1360                 obd->obd_abort_recovery = 1;
1361                 wake_up(&obd->obd_next_transno_waitq);
1362                 spin_unlock_bh(&obd->obd_processing_task_lock);
1363                 wait_for_completion(&trd->trd_finishing);
1364         } else {
1365                 spin_unlock_bh(&obd->obd_processing_task_lock);
1366         }
1367 }
1368 #endif
1369
1370 int target_process_req_flags(struct obd_device *obd, struct ptlrpc_request *req)
1371 {
1372         struct obd_export *exp = req->rq_export;
1373         LASSERT(exp != NULL);
1374         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1375                 /* client declares he's ready to replay locks */
1376                 spin_lock_bh(&obd->obd_processing_task_lock);
1377                 if (exp->exp_req_replay_needed) {
1378                         LASSERT(atomic_read(&obd->obd_req_replay_clients) > 0);
1379                         exp->exp_req_replay_needed = 0;
1380                         atomic_dec(&obd->obd_req_replay_clients);
1381                         if (atomic_read(&obd->obd_req_replay_clients) == 0) {
1382                                 CDEBUG(D_HA, "all clients have replayed reqs\n");
1383                                 wake_up(&obd->obd_next_transno_waitq);
1384                         }
1385                 }
1386                 spin_unlock_bh(&obd->obd_processing_task_lock);
1387         }
1388         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1389                 /* client declares he's ready to complete recovery 
1390                  * so, we put the request on th final queue */
1391                 spin_lock_bh(&obd->obd_processing_task_lock);
1392                 if (exp->exp_lock_replay_needed) {
1393                         LASSERT(atomic_read(&obd->obd_lock_replay_clients) > 0);
1394                         exp->exp_lock_replay_needed = 0;
1395                         atomic_dec(&obd->obd_lock_replay_clients);
1396                         if (atomic_read(&obd->obd_lock_replay_clients) == 0) {
1397                                 CDEBUG(D_HA, "all clients have replayed locks\n");
1398                                 wake_up(&obd->obd_next_transno_waitq);
1399                         }
1400                 }
1401                 spin_unlock_bh(&obd->obd_processing_task_lock);
1402         }
1403
1404         return 0;
1405 }
1406
1407 int target_queue_recovery_request(struct ptlrpc_request *req,
1408                                   struct obd_device *obd)
1409 {
1410         struct list_head *tmp;
1411         int inserted = 0;
1412         __u64 transno = req->rq_reqmsg->transno;
1413
1414         if (obd->obd_recovery_data.trd_processing_task == current->pid) {
1415                 /* Processing the queue right now, don't re-add. */
1416                 return 1;
1417         }
1418
1419         target_process_req_flags(obd, req);
1420
1421         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1422                 /* client declares he's ready to complete recovery 
1423                  * so, we put the request on th final queue */
1424                 req = ptlrpc_clone_req(req);
1425                 if (req == NULL)
1426                         return -ENOMEM;
1427                 DEBUG_REQ(D_HA, req, "queue final req");
1428                 spin_lock_bh(&obd->obd_processing_task_lock);
1429                 list_add_tail(&req->rq_list, &obd->obd_final_req_queue);
1430                 spin_unlock_bh(&obd->obd_processing_task_lock);
1431                 return 0;
1432         }
1433         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1434                 /* client declares he's ready to replay locks */
1435                 req = ptlrpc_clone_req(req);
1436                 if (req == NULL)
1437                         return -ENOMEM;
1438                 DEBUG_REQ(D_HA, req, "queue lock replay req");
1439                 spin_lock_bh(&obd->obd_processing_task_lock);
1440                 list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
1441                 spin_unlock_bh(&obd->obd_processing_task_lock);
1442                 wake_up(&obd->obd_next_transno_waitq);
1443                 return 0;
1444         }
1445
1446
1447         /* CAVEAT EMPTOR: The incoming request message has been swabbed
1448          * (i.e. buflens etc are in my own byte order), but type-dependent
1449          * buffers (eg mds_body, ost_body etc) have NOT been swabbed. */
1450
1451         if (!transno) {
1452                 INIT_LIST_HEAD(&req->rq_list);
1453                 DEBUG_REQ(D_HA, req, "not queueing");
1454                 return 1;
1455         }
1456
1457
1458         /* If we're processing the queue, we want don't want to queue this
1459          * message.
1460          *
1461          * Also, if this request has a transno less than the one we're waiting
1462          * for, we should process it now.  It could (and currently always will)
1463          * be an open request for a descriptor that was opened some time ago.
1464          *
1465          * Also, a resent, replayed request that has already been
1466          * handled will pass through here and be processed immediately.
1467          */
1468         spin_lock_bh(&obd->obd_processing_task_lock);
1469         if (transno < obd->obd_next_recovery_transno) {
1470                 /* Processing the queue right now, don't re-add. */
1471                 LASSERT(list_empty(&req->rq_list));
1472                 spin_unlock_bh(&obd->obd_processing_task_lock);
1473                 return 1;
1474         }
1475         spin_unlock_bh(&obd->obd_processing_task_lock);
1476
1477         /* A resent, replayed request that is still on the queue; just drop it.
1478            The queued request will handle this. */
1479         if ((lustre_msg_get_flags(req->rq_reqmsg) & (MSG_RESENT | MSG_REPLAY))
1480             == (MSG_RESENT | MSG_REPLAY)) {
1481                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
1482                 return 0;
1483         }
1484
1485         req = ptlrpc_clone_req(req);
1486         if (req == NULL)
1487                 return -ENOMEM;
1488
1489         spin_lock_bh(&obd->obd_processing_task_lock);
1490
1491         /* XXX O(n^2) */
1492         list_for_each(tmp, &obd->obd_req_replay_queue) {
1493                 struct ptlrpc_request *reqiter =
1494                         list_entry(tmp, struct ptlrpc_request, rq_list);
1495
1496                 if (reqiter->rq_reqmsg->transno > transno) {
1497                         list_add_tail(&req->rq_list, &reqiter->rq_list);
1498                         inserted = 1;
1499                         break;
1500                 }
1501         }
1502
1503         if (!inserted)
1504                 list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
1505
1506         obd->obd_requests_queued_for_recovery++;
1507         wake_up(&obd->obd_next_transno_waitq);
1508         spin_unlock_bh(&obd->obd_processing_task_lock);
1509         return 0;
1510 }
1511
1512 struct obd_device * target_req2obd(struct ptlrpc_request *req)
1513 {
1514         return req->rq_export->exp_obd;
1515 }
1516
1517 int
1518 target_send_reply_msg (struct ptlrpc_request *req, int rc, int fail_id)
1519 {
1520         if (OBD_FAIL_CHECK(fail_id | OBD_FAIL_ONCE)) {
1521                 obd_fail_loc |= OBD_FAIL_ONCE | OBD_FAILED;
1522                 DEBUG_REQ(D_ERROR, req, "dropping reply");
1523                 /* NB this does _not_ send with ACK disabled, to simulate
1524                  * sending OK, but timing out for the ACK */
1525                 if (req->rq_reply_state != NULL) {
1526                         if (!req->rq_reply_state->rs_difficult) {
1527                                 lustre_free_reply_state (req->rq_reply_state);
1528                                 req->rq_reply_state = NULL;
1529                         } else {
1530                                 struct ptlrpc_service *svc =
1531                                         req->rq_rqbd->rqbd_srv_ni->sni_service;
1532                                 atomic_inc(&svc->srv_outstanding_replies);
1533                         }
1534                 }
1535                 return (-ECOMM);
1536         }
1537
1538         if (rc) {
1539                 req->rq_status = rc;
1540                 return (ptlrpc_error(req));
1541         } else {
1542                 DEBUG_REQ(D_NET, req, "sending reply");
1543         }
1544         
1545         return (ptlrpc_send_reply(req, 1));
1546 }
1547
1548 void 
1549 target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
1550 {
1551         int                        netrc;
1552         unsigned long              flags;
1553         struct ptlrpc_reply_state *rs;
1554         struct obd_device         *obd;
1555         struct obd_export         *exp;
1556         struct ptlrpc_srv_ni      *sni;
1557         struct ptlrpc_service     *svc;
1558
1559         sni = req->rq_rqbd->rqbd_srv_ni;
1560         svc = sni->sni_service;
1561         
1562         rs = req->rq_reply_state;
1563         if (rs == NULL || !rs->rs_difficult) {
1564                 /* The easy case; no notifiers and reply_out_callback()
1565                  * cleans up (i.e. we can't look inside rs after a
1566                  * successful send) */
1567                 netrc = target_send_reply_msg (req, rc, fail_id);
1568
1569                 LASSERT (netrc == 0 || req->rq_reply_state == NULL);
1570                 return;
1571         }
1572
1573         /* must be an export if locks saved */
1574         LASSERT (req->rq_export != NULL);
1575         /* req/reply consistent */
1576         LASSERT (rs->rs_srv_ni == sni);
1577
1578         /* "fresh" reply */
1579         LASSERT (!rs->rs_scheduled);
1580         LASSERT (!rs->rs_scheduled_ever);
1581         LASSERT (!rs->rs_handled);
1582         LASSERT (!rs->rs_on_net);
1583         LASSERT (rs->rs_export == NULL);
1584         LASSERT (list_empty(&rs->rs_obd_list));
1585         LASSERT (list_empty(&rs->rs_exp_list));
1586
1587         exp = class_export_get (req->rq_export);
1588         obd = exp->exp_obd;
1589
1590         /* disable reply scheduling onto srv_reply_queue while I'm setting up */
1591         rs->rs_scheduled = 1;
1592         rs->rs_on_net    = 1;
1593         rs->rs_xid       = req->rq_xid;
1594         rs->rs_transno   = req->rq_transno;
1595         rs->rs_export    = exp;
1596         
1597         spin_lock_irqsave (&obd->obd_uncommitted_replies_lock, flags);
1598
1599         if (rs->rs_transno > obd->obd_last_committed) {
1600                 /* not committed already */ 
1601                 list_add_tail (&rs->rs_obd_list, 
1602                                &obd->obd_uncommitted_replies);
1603         }
1604
1605         spin_unlock (&obd->obd_uncommitted_replies_lock);
1606         spin_lock (&exp->exp_lock);
1607
1608         list_add_tail (&rs->rs_exp_list, &exp->exp_outstanding_replies);
1609
1610         spin_unlock_irqrestore (&exp->exp_lock, flags);
1611
1612         netrc = target_send_reply_msg (req, rc, fail_id);
1613
1614         spin_lock_irqsave (&svc->srv_lock, flags);
1615
1616         svc->srv_n_difficult_replies++;
1617
1618         if (netrc != 0) /* error sending: reply is off the net */
1619                 rs->rs_on_net = 0;
1620
1621         if (!rs->rs_on_net ||                   /* some notifier */
1622             list_empty(&rs->rs_exp_list) ||     /* completed already */
1623             list_empty(&rs->rs_obd_list)) {
1624                 list_add_tail (&rs->rs_list, &svc->srv_reply_queue);
1625                 wake_up (&svc->srv_waitq);
1626         } else {
1627                 list_add (&rs->rs_list, &sni->sni_active_replies);
1628                 rs->rs_scheduled = 0;           /* allow notifier to schedule */
1629         }
1630
1631         spin_unlock_irqrestore (&svc->srv_lock, flags);
1632 }
1633
1634 int target_handle_ping(struct ptlrpc_request *req)
1635 {
1636         return lustre_pack_reply(req, 0, NULL, NULL);
1637 }