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