Whamcloud - gitweb
land b_hd_sec onto HEAD:
[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 = inter_module_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                 inter_module_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 = inter_module_get("mgmtcli_deregister_for_events");
356                 dereg_f(cli->cl_mgmtcli_obd, obddev);
357                 inter_module_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, 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         struct list_head *tmp, *n;
902         int rc;
903
904         CWARN("%s: sending delayed replies to recovered clients\n",
905               obd->obd_name);
906
907         ldlm_reprocess_all_ns(obd->obd_namespace);
908
909         /* when recovery finished, cleanup orphans on mds and ost */
910         if (OBT(obd) && OBP(obd, postrecov)) {
911                 rc = OBP(obd, postrecov)(obd);
912                 if (rc >= 0)
913                         CWARN("%s: all clients recovered, %d MDS "
914                               "orphans deleted\n", obd->obd_name, rc);
915                 else
916                         CERROR("postrecov failed %d\n", rc);
917         }
918
919
920         list_for_each_safe(tmp, n, &obd->obd_delayed_reply_queue) {
921                 struct ptlrpc_request *req;
922                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
923                 list_del(&req->rq_list);
924                 DEBUG_REQ(D_ERROR, req, "delayed:");
925                 ptlrpc_reply(req);
926                 target_release_saved_req(req);
927         }
928         obd->obd_recovery_end = LTIME_S(CURRENT_TIME);
929         return;
930 }
931
932 static void abort_recovery_queue(struct obd_device *obd)
933 {
934         struct ptlrpc_request *req;
935         struct list_head *tmp, *n;
936         int rc;
937
938         list_for_each_safe(tmp, n, &obd->obd_recovery_queue) {
939                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
940                 list_del(&req->rq_list);
941                 DEBUG_REQ(D_ERROR, req, "aborted:");
942                 req->rq_status = -ENOTCONN;
943                 req->rq_type = PTL_RPC_MSG_ERR;
944                 rc = lustre_pack_reply(req, 0, NULL, NULL);
945                 if (rc == 0) {
946                         ptlrpc_reply(req);
947                 } else {
948                         DEBUG_REQ(D_ERROR, req,
949                                   "packing failed for abort-reply; skipping");
950                 }
951                 target_release_saved_req(req);
952         }
953 }
954
955 /* Called from a cleanup function if the device is being cleaned up
956    forcefully.  The exports should all have been disconnected already,
957    the only thing left to do is
958      - clear the recovery flags
959      - cancel the timer
960      - free queued requests and replies, but don't send replies
961    Because the obd_stopping flag is set, no new requests should be received.
962
963 */
964 void target_cleanup_recovery(struct obd_device *obd)
965 {
966         struct list_head *tmp, *n;
967         struct ptlrpc_request *req;
968
969         spin_lock_bh(&obd->obd_processing_task_lock);
970         if (!obd->obd_recovering) {
971                 spin_unlock_bh(&obd->obd_processing_task_lock);
972                 EXIT;
973                 return;
974         }
975         obd->obd_recovering = obd->obd_abort_recovery = 0;
976         target_cancel_recovery_timer(obd);
977         spin_unlock_bh(&obd->obd_processing_task_lock);
978
979         list_for_each_safe(tmp, n, &obd->obd_delayed_reply_queue) {
980                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
981                 list_del(&req->rq_list);
982                 LASSERT (req->rq_reply_state);
983                 lustre_free_reply_state(req->rq_reply_state);
984                 target_release_saved_req(req);
985         }
986         list_for_each_safe(tmp, n, &obd->obd_recovery_queue) {
987                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
988                 list_del(&req->rq_list);
989                 LASSERT (req->rq_reply_state == 0);
990                 target_release_saved_req(req);
991         }
992 }
993
994 static void target_abort_recovery(void *data)
995 {
996         struct obd_device *obd = data;
997
998         LASSERT(!obd->obd_recovering);
999
1000         class_disconnect_stale_exports(obd, 0);
1001
1002         CERROR("%s: recovery period over; disconnecting unfinished clients.\n",
1003                obd->obd_name);
1004
1005         abort_recovery_queue(obd);
1006         target_finish_recovery(obd);
1007         ptlrpc_run_recovery_over_upcall(obd);
1008 }
1009
1010 static void target_recovery_expired(unsigned long castmeharder)
1011 {
1012         struct obd_device *obd = (struct obd_device *)castmeharder;
1013         CERROR("recovery timed out, aborting\n");
1014         spin_lock_bh(&obd->obd_processing_task_lock);
1015         if (obd->obd_recovering)
1016                 obd->obd_abort_recovery = 1;
1017
1018         wake_up(&obd->obd_next_transno_waitq);
1019         spin_unlock_bh(&obd->obd_processing_task_lock);
1020 }
1021
1022
1023 /* obd_processing_task_lock should be held */
1024 void target_cancel_recovery_timer(struct obd_device *obd)
1025 {
1026         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1027         del_timer(&obd->obd_recovery_timer);
1028 }
1029
1030 #ifdef __KERNEL__
1031 static void reset_recovery_timer(struct obd_device *obd)
1032 {
1033         spin_lock_bh(&obd->obd_processing_task_lock);
1034         if (!obd->obd_recovering) {
1035                 spin_unlock_bh(&obd->obd_processing_task_lock);
1036                 return;
1037         }                
1038         CDEBUG(D_HA, "timer will expire in %u seconds\n",
1039                OBD_RECOVERY_TIMEOUT / HZ);
1040         mod_timer(&obd->obd_recovery_timer, jiffies + OBD_RECOVERY_TIMEOUT);
1041         spin_unlock_bh(&obd->obd_processing_task_lock);
1042 }
1043 #endif
1044
1045 /* Only start it the first time called */
1046 void target_start_recovery_timer(struct obd_device *obd)
1047 {
1048         spin_lock_bh(&obd->obd_processing_task_lock);
1049         if (!obd->obd_recovering || timer_pending(&obd->obd_recovery_timer)) {
1050                 spin_unlock_bh(&obd->obd_processing_task_lock);
1051                 return;
1052         }
1053         CWARN("%s: starting recovery timer (%us)\n", obd->obd_name,
1054                OBD_RECOVERY_TIMEOUT / HZ);
1055         obd->obd_recovery_timer.function = target_recovery_expired;
1056         obd->obd_recovery_timer.data = (unsigned long)obd;
1057         mod_timer(&obd->obd_recovery_timer, jiffies + OBD_RECOVERY_TIMEOUT);
1058         spin_unlock_bh(&obd->obd_processing_task_lock);
1059 }
1060
1061 #ifdef __KERNEL__
1062 static int check_for_next_transno(struct obd_device *obd)
1063 {
1064         struct ptlrpc_request *req = NULL;
1065         int wake_up = 0, connected, completed, queue_len, max;
1066         __u64 next_transno, req_transno;
1067
1068         spin_lock_bh(&obd->obd_processing_task_lock);
1069         if (!list_empty(&obd->obd_recovery_queue)) {
1070                 req = list_entry(obd->obd_recovery_queue.next,
1071                                  struct ptlrpc_request, rq_list);
1072                 req_transno = req->rq_reqmsg->transno;
1073         } else {
1074                 req_transno = 0;
1075         }
1076
1077         max = obd->obd_max_recoverable_clients;
1078         connected = obd->obd_connected_clients;
1079         completed = max - obd->obd_recoverable_clients;
1080         queue_len = obd->obd_requests_queued_for_recovery;
1081         next_transno = obd->obd_next_recovery_transno;
1082
1083         CDEBUG(D_HA,"max: %d, connected: %d, completed: %d, queue_len: %d, "
1084                "req_transno: "LPU64", next_transno: "LPU64"\n",
1085                max, connected, completed, queue_len, req_transno, next_transno);
1086         if (obd->obd_abort_recovery) {
1087                 CDEBUG(D_HA, "waking for aborted recovery\n");
1088                 wake_up = 1;
1089         } else if (max == completed) {
1090                 CDEBUG(D_HA, "waking for completed recovery\n");
1091                 wake_up = 1;
1092         } else if (req_transno == next_transno) {
1093                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1094                 wake_up = 1;
1095         } else if (queue_len + completed == max) {
1096                 LASSERT(req->rq_reqmsg->transno >= next_transno);
1097                 CDEBUG(D_ERROR,
1098                        "waking for skipped transno (skip: "LPD64
1099                        ", ql: %d, comp: %d, conn: %d, next: "LPD64")\n",
1100                        next_transno, queue_len, completed, max, req_transno);
1101                 obd->obd_next_recovery_transno = req_transno;
1102                 wake_up = 1;
1103         }
1104         spin_unlock_bh(&obd->obd_processing_task_lock);
1105         
1106         return wake_up;
1107 }
1108
1109 static struct ptlrpc_request *
1110 target_next_replay_req(struct obd_device *obd)
1111 {
1112         struct l_wait_info lwi = { 0 };
1113         struct ptlrpc_request *req;
1114
1115         CDEBUG(D_HA, "Waiting for transno "LPD64"\n",
1116                obd->obd_next_recovery_transno);
1117         l_wait_event(obd->obd_next_transno_waitq,
1118                      check_for_next_transno(obd), &lwi);
1119         
1120         spin_lock_bh(&obd->obd_processing_task_lock);
1121         if (obd->obd_abort_recovery) {
1122                 req = NULL;
1123         } else if (!list_empty(&obd->obd_recovery_queue)) {
1124                 req = list_entry(obd->obd_recovery_queue.next,
1125                                  struct ptlrpc_request, rq_list);
1126                 list_del_init(&req->rq_list);
1127                 obd->obd_requests_queued_for_recovery--;
1128         } else {
1129                 req = NULL;
1130         }
1131         spin_unlock_bh(&obd->obd_processing_task_lock);
1132         return req;
1133 }
1134
1135 static int target_recovery_thread(void *arg)
1136 {
1137         struct obd_device *obd = arg;
1138         struct ptlrpc_request *req;
1139         struct target_recovery_data *trd = &obd->obd_recovery_data;
1140         unsigned long flags;
1141         ENTRY;
1142
1143         kportal_daemonize("tgt-recov");
1144
1145         SIGNAL_MASK_LOCK(current, flags);
1146         sigfillset(&current->blocked);
1147         RECALC_SIGPENDING;
1148         SIGNAL_MASK_UNLOCK(current, flags);
1149
1150         CERROR("%s: started recovery thread pid %d\n", obd->obd_name, 
1151                current->pid);
1152         trd->trd_processing_task = current->pid;
1153
1154         obd->obd_recovering = 1;
1155         complete(&trd->trd_starting);
1156
1157         while (obd->obd_recovering) {
1158                 LASSERT(trd->trd_processing_task == current->pid);
1159                 req = target_next_replay_req(obd);
1160                 if (req != NULL) {
1161                         char peer_str[PTL_NALFMT_SIZE];
1162                         DEBUG_REQ(D_HA, req, "processing t"LPD64" from %s: ", 
1163                                   req->rq_reqmsg->transno, 
1164                                   ptlrpc_peernid2str(&req->rq_peer, peer_str));
1165                         (void)trd->trd_recovery_handler(req);
1166                         obd->obd_replayed_requests++;
1167                         reset_recovery_timer(obd);
1168                         /* bug 1580: decide how to properly sync() in recovery*/
1169                         //mds_fsync_super(mds->mds_sb);
1170                         ptlrpc_free_clone(req);
1171                         spin_lock_bh(&obd->obd_processing_task_lock);
1172                         obd->obd_next_recovery_transno++;
1173                         spin_unlock_bh(&obd->obd_processing_task_lock);
1174                 } else {
1175                         /* recovery is over */
1176                         spin_lock_bh(&obd->obd_processing_task_lock);
1177                         obd->obd_recovering = 0;
1178                         target_cancel_recovery_timer(obd);
1179                         if (obd->obd_abort_recovery) {
1180                                 obd->obd_abort_recovery = 0;
1181                                 spin_unlock_bh(&obd->obd_processing_task_lock);
1182                                 target_abort_recovery(obd); 
1183                         } else {
1184                                 LASSERT(obd->obd_recoverable_clients == 0);
1185                                 spin_unlock_bh(&obd->obd_processing_task_lock);
1186                                 target_finish_recovery(obd);
1187                         }
1188                 }
1189         }
1190
1191         trd->trd_processing_task = 0;
1192         complete(&trd->trd_finishing);
1193         return 0;
1194 }
1195
1196 int target_start_recovery_thread(struct obd_device *obd, svc_handler_t handler)
1197 {
1198         int rc = 0;
1199         struct target_recovery_data *trd = &obd->obd_recovery_data;
1200
1201         memset(trd, 0, sizeof(*trd));
1202         init_completion(&trd->trd_starting);
1203         init_completion(&trd->trd_finishing);
1204         trd->trd_recovery_handler = handler;
1205
1206         if (kernel_thread(target_recovery_thread, obd, 0) == 0) 
1207                 wait_for_completion(&trd->trd_starting);
1208         else
1209                 rc = -ECHILD;
1210
1211         return rc;
1212 }
1213
1214 void target_stop_recovery_thread(struct obd_device *obd)
1215 {
1216         spin_lock_bh(&obd->obd_processing_task_lock);
1217         if (obd->obd_recovery_data.trd_processing_task > 0) {
1218                 struct target_recovery_data *trd = &obd->obd_recovery_data;
1219                 CERROR("%s: aborting recovery\n", obd->obd_name);
1220                 obd->obd_abort_recovery = 1;
1221                 wake_up(&obd->obd_next_transno_waitq);
1222                 spin_unlock_bh(&obd->obd_processing_task_lock);
1223                 wait_for_completion(&trd->trd_finishing);
1224         } else {
1225                 spin_unlock_bh(&obd->obd_processing_task_lock);
1226         }
1227 }
1228 #endif
1229
1230 int target_queue_recovery_request(struct ptlrpc_request *req,
1231                                   struct obd_device *obd)
1232 {
1233         struct list_head *tmp;
1234         int inserted = 0;
1235         __u64 transno = req->rq_reqmsg->transno;
1236
1237         /* CAVEAT EMPTOR: The incoming request message has been swabbed
1238          * (i.e. buflens etc are in my own byte order), but type-dependent
1239          * buffers (eg mds_body, ost_body etc) have NOT been swabbed. */
1240
1241         if (!transno) {
1242                 INIT_LIST_HEAD(&req->rq_list);
1243                 DEBUG_REQ(D_HA, req, "not queueing");
1244                 return 1;
1245         }
1246
1247
1248         /* If we're processing the queue, we want don't want to queue this
1249          * message.
1250          *
1251          * Also, if this request has a transno less than the one we're waiting
1252          * for, we should process it now.  It could (and currently always will)
1253          * be an open request for a descriptor that was opened some time ago.
1254          *
1255          * Also, a resent, replayed request that has already been
1256          * handled will pass through here and be processed immediately.
1257          */
1258         spin_lock_bh(&obd->obd_processing_task_lock);
1259         if (obd->obd_recovery_data.trd_processing_task == current->pid ||
1260             transno < obd->obd_next_recovery_transno) {
1261                 /* Processing the queue right now, don't re-add. */
1262                 LASSERT(list_empty(&req->rq_list));
1263                 spin_unlock_bh(&obd->obd_processing_task_lock);
1264                 return 1;
1265         }
1266         spin_unlock_bh(&obd->obd_processing_task_lock);
1267
1268         /* A resent, replayed request that is still on the queue; just drop it.
1269            The queued request will handle this. */
1270         if ((lustre_msg_get_flags(req->rq_reqmsg) & (MSG_RESENT | MSG_REPLAY))
1271             == (MSG_RESENT | MSG_REPLAY)) {
1272                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
1273                 return 0;
1274         }
1275
1276         req = ptlrpc_clone_req(req);
1277         if (req == NULL)
1278                 return -ENOMEM;
1279
1280         spin_lock_bh(&obd->obd_processing_task_lock);
1281
1282         /* XXX O(n^2) */
1283         list_for_each(tmp, &obd->obd_recovery_queue) {
1284                 struct ptlrpc_request *reqiter =
1285                         list_entry(tmp, struct ptlrpc_request, rq_list);
1286
1287                 if (reqiter->rq_reqmsg->transno > transno) {
1288                         list_add_tail(&req->rq_list, &reqiter->rq_list);
1289                         inserted = 1;
1290                         break;
1291                 }
1292         }
1293
1294         if (!inserted)
1295                 list_add_tail(&req->rq_list, &obd->obd_recovery_queue);
1296
1297         obd->obd_requests_queued_for_recovery++;
1298         wake_up(&obd->obd_next_transno_waitq);
1299         spin_unlock_bh(&obd->obd_processing_task_lock);
1300         return 0;
1301 }
1302
1303 struct obd_device * target_req2obd(struct ptlrpc_request *req)
1304 {
1305         return req->rq_export->exp_obd;
1306 }
1307
1308 int target_queue_final_reply(struct ptlrpc_request *req, int rc)
1309 {
1310         struct obd_device *obd = target_req2obd(req);
1311
1312         LASSERT ((rc == 0) == (req->rq_reply_state != NULL));
1313
1314         if (rc) {
1315                 /* Just like ptlrpc_error, but without the sending. */
1316                 rc = lustre_pack_reply(req, 0, NULL, NULL);
1317                 LASSERT(rc == 0); /* XXX handle this */
1318                 req->rq_type = PTL_RPC_MSG_ERR;
1319         }
1320
1321         LASSERT (!req->rq_reply_state->rs_difficult);
1322         LASSERT(list_empty(&req->rq_list));
1323         
1324         req = ptlrpc_clone_req(req);
1325
1326         spin_lock_bh(&obd->obd_processing_task_lock);
1327
1328         list_add(&req->rq_list, &obd->obd_delayed_reply_queue);
1329
1330         /* only count the first "replay over" request from each
1331            export */
1332         if (req->rq_export->exp_replay_needed) {
1333                 --obd->obd_recoverable_clients;
1334                 req->rq_export->exp_replay_needed = 0;
1335                 CWARN("%s: %d recoverable clients remain\n",
1336                       obd->obd_name, obd->obd_recoverable_clients);
1337         }
1338         wake_up(&obd->obd_next_transno_waitq);
1339         spin_unlock_bh(&obd->obd_processing_task_lock);
1340         return 1;
1341 }
1342
1343 int
1344 target_send_reply_msg (struct ptlrpc_request *req, int rc, int fail_id)
1345 {
1346         if (OBD_FAIL_CHECK(fail_id | OBD_FAIL_ONCE)) {
1347                 obd_fail_loc |= OBD_FAIL_ONCE | OBD_FAILED;
1348                 DEBUG_REQ(D_ERROR, req, "dropping reply");
1349                 /* NB this does _not_ send with ACK disabled, to simulate
1350                  * sending OK, but timing out for the ACK */
1351                 if (req->rq_reply_state != NULL) {
1352                         if (!req->rq_reply_state->rs_difficult) {
1353                                 lustre_free_reply_state (req->rq_reply_state);
1354                                 req->rq_reply_state = NULL;
1355                         } else {
1356                                 struct ptlrpc_service *svc =
1357                                         req->rq_rqbd->rqbd_srv_ni->sni_service;
1358                                 atomic_inc(&svc->srv_outstanding_replies);
1359                         }
1360                 }
1361                 return (-ECOMM);
1362         }
1363
1364         if (rc) {
1365                 req->rq_status = rc;
1366                 return (ptlrpc_error(req));
1367         } else {
1368                 DEBUG_REQ(D_NET, req, "sending reply");
1369         }
1370         
1371         return (ptlrpc_send_reply(req, 1));
1372 }
1373
1374 void 
1375 target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
1376 {
1377         int                        netrc;
1378         unsigned long              flags;
1379         struct ptlrpc_reply_state *rs;
1380         struct obd_device         *obd;
1381         struct obd_export         *exp;
1382         struct ptlrpc_srv_ni      *sni;
1383         struct ptlrpc_service     *svc;
1384
1385         sni = req->rq_rqbd->rqbd_srv_ni;
1386         svc = sni->sni_service;
1387         
1388         rs = req->rq_reply_state;
1389         if (rs == NULL || !rs->rs_difficult) {
1390                 /* The easy case; no notifiers and reply_out_callback()
1391                  * cleans up (i.e. we can't look inside rs after a
1392                  * successful send) */
1393                 netrc = target_send_reply_msg (req, rc, fail_id);
1394
1395                 LASSERT (netrc == 0 || req->rq_reply_state == NULL);
1396                 return;
1397         }
1398
1399         /* must be an export if locks saved */
1400         LASSERT (req->rq_export != NULL);
1401         /* req/reply consistent */
1402         LASSERT (rs->rs_srv_ni == sni);
1403
1404         /* "fresh" reply */
1405         LASSERT (!rs->rs_scheduled);
1406         LASSERT (!rs->rs_scheduled_ever);
1407         LASSERT (!rs->rs_handled);
1408         LASSERT (!rs->rs_on_net);
1409         LASSERT (rs->rs_export == NULL);
1410         LASSERT (list_empty(&rs->rs_obd_list));
1411         LASSERT (list_empty(&rs->rs_exp_list));
1412
1413         exp = class_export_get (req->rq_export);
1414         obd = exp->exp_obd;
1415
1416         /* disable reply scheduling onto srv_reply_queue while I'm setting up */
1417         rs->rs_scheduled = 1;
1418         rs->rs_on_net    = 1;
1419         rs->rs_xid       = req->rq_xid;
1420         rs->rs_transno   = req->rq_transno;
1421         rs->rs_export    = exp;
1422         
1423         spin_lock_irqsave (&obd->obd_uncommitted_replies_lock, flags);
1424
1425         if (rs->rs_transno > obd->obd_last_committed) {
1426                 /* not committed already */ 
1427                 list_add_tail (&rs->rs_obd_list, 
1428                                &obd->obd_uncommitted_replies);
1429         }
1430
1431         spin_unlock (&obd->obd_uncommitted_replies_lock);
1432         spin_lock (&exp->exp_lock);
1433
1434         list_add_tail (&rs->rs_exp_list, &exp->exp_outstanding_replies);
1435
1436         spin_unlock_irqrestore (&exp->exp_lock, flags);
1437
1438         netrc = target_send_reply_msg (req, rc, fail_id);
1439
1440         spin_lock_irqsave (&svc->srv_lock, flags);
1441
1442         svc->srv_n_difficult_replies++;
1443
1444         if (netrc != 0) /* error sending: reply is off the net */
1445                 rs->rs_on_net = 0;
1446
1447         if (!rs->rs_on_net ||                   /* some notifier */
1448             list_empty(&rs->rs_exp_list) ||     /* completed already */
1449             list_empty(&rs->rs_obd_list)) {
1450                 list_add_tail (&rs->rs_list, &svc->srv_reply_queue);
1451                 wake_up (&svc->srv_waitq);
1452         } else {
1453                 list_add (&rs->rs_list, &sni->sni_active_replies);
1454                 rs->rs_scheduled = 0;           /* allow notifier to schedule */
1455         }
1456
1457         spin_unlock_irqrestore (&svc->srv_lock, flags);
1458 }
1459
1460 int target_handle_ping(struct ptlrpc_request *req)
1461 {
1462         return lustre_pack_reply(req, 0, NULL, NULL);
1463 }