Whamcloud - gitweb
land b_hd_sec on HEAD. various security fixes.
[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         ENTRY;
185
186         /* In a more perfect world, we would hang a ptlrpc_client off of
187          * obd_type and just use the values from there. */
188         if (!strcmp(name, LUSTRE_OSC_NAME)) {
189                 rq_portal = OST_REQUEST_PORTAL;
190                 rp_portal = OSC_REPLY_PORTAL;
191                 connect_op = OST_CONNECT;
192         } else if (!strcmp(name, LUSTRE_MDC_NAME)) {
193                 rq_portal = MDS_REQUEST_PORTAL;
194                 rp_portal = MDC_REPLY_PORTAL;
195                 connect_op = MDS_CONNECT;
196         } else if (!strcmp(name, LUSTRE_MGMTCLI_NAME)) {
197                 rq_portal = MGMT_REQUEST_PORTAL;
198                 rp_portal = MGMT_REPLY_PORTAL;
199                 connect_op = MGMT_CONNECT;
200         } else {
201                 CERROR("unknown client OBD type \"%s\", can't setup\n",
202                        name);
203                 RETURN(-EINVAL);
204         }
205
206
207         if (LUSTRE_CFG_BUFLEN(lcfg, 1) < 1) {
208                 CERROR("requires a TARGET UUID\n");
209                 RETURN(-EINVAL);
210         }
211
212         if (LUSTRE_CFG_BUFLEN(lcfg, 1) > 37) {
213                 CERROR("client UUID must be less than 38 characters\n");
214                 RETURN(-EINVAL);
215         }
216
217         if (LUSTRE_CFG_BUFLEN(lcfg, 2) < 1) {
218                 CERROR("setup requires a SERVER UUID\n");
219                 RETURN(-EINVAL);
220         }
221
222         if (LUSTRE_CFG_BUFLEN(lcfg, 2) > 37) {
223                 CERROR("target UUID must be less than 38 characters\n");
224                 RETURN(-EINVAL);
225         }
226
227         sema_init(&cli->cl_sem, 1);
228         cli->cl_conn_count = 0;
229         memcpy(server_uuid.uuid,  lustre_cfg_buf(lcfg, 2),
230                min_t(unsigned int, LUSTRE_CFG_BUFLEN(lcfg, 2), 
231                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 #if 0
255         } else if (num_physpages >> (20 - PAGE_SHIFT) <= 512) { /* <= 512 MB */
256                 cli->cl_max_pages_per_rpc = PTLRPC_MAX_BRW_PAGES / 2;
257                 cli->cl_max_rpcs_in_flight = OSC_MAX_RIF_DEFAULT / 2;
258 #endif
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 #if 0
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 #endif
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, __u32 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->flavor == flavor)
552                         return -EPERM;
553         }
554         return 0;
555 }
556
557 int target_check_deny_sec(struct obd_device *target, struct ptlrpc_request *req)
558 {
559         __u32 flavor;
560         int rc = 0;
561
562         flavor = req->rq_req_secflvr;
563
564         if (!strcmp(target->obd_type->typ_name, LUSTRE_MDS_NAME)) {
565                 spin_lock(&target->u.mds.mds_denylist_lock);
566                 rc = check_deny_list(&target->u.mds.mds_denylist, flavor);
567                 spin_unlock(&target->u.mds.mds_denylist_lock);
568         } else if (!strcmp(target->obd_type->typ_name, "obdfilter")) {
569                 spin_lock(&target->u.filter.fo_denylist_lock);
570                 rc = check_deny_list(&target->u.filter.fo_denylist, flavor);
571                 spin_unlock(&target->u.filter.fo_denylist_lock);
572         }
573
574         return rc;
575 }
576
577 int target_handle_connect(struct ptlrpc_request *req)
578 {
579         unsigned long connect_flags = 0, *cfp;
580         struct obd_device *target;
581         struct obd_export *export = NULL;
582         struct obd_import *revimp;
583         struct lustre_handle conn;
584         struct obd_uuid tgtuuid;
585         struct obd_uuid cluuid;
586         struct obd_uuid remote_uuid;
587         struct list_head *p;
588         struct obd_connect_data *conn_data;
589         int conn_data_size = sizeof(*conn_data);
590         char *str, *tmp;
591         int rc = 0;
592         unsigned long flags;
593         int initial_conn = 0;
594         char peer_str[PTL_NALFMT_SIZE];
595         const int offset = 1;
596         ENTRY;
597
598         OBD_RACE(OBD_FAIL_TGT_CONN_RACE); 
599
600         LASSERT_REQSWAB (req, offset + 0);
601         str = lustre_msg_string(req->rq_reqmsg, offset + 0,
602                                 sizeof(tgtuuid) - 1);
603         if (str == NULL) {
604                 CERROR("bad target UUID for connect\n");
605                 GOTO(out, rc = -EINVAL);
606         }
607
608         obd_str2uuid (&tgtuuid, str);
609         target = class_uuid2obd(&tgtuuid);
610         if (!target)
611                 target = class_name2obd(str);
612         
613         if (!target || target->obd_stopping || !target->obd_set_up) {
614                 CERROR("UUID '%s' is not available for connect from %s\n",
615                        str, req->rq_peerstr);
616                 GOTO(out, rc = -ENODEV);
617         }
618
619         /* check the secure deny list of mds/ost */
620         rc = target_check_deny_sec(target, req);
621         if (rc != 0)
622                 GOTO(out, rc);
623
624         LASSERT_REQSWAB (req, offset + 1);
625         str = lustre_msg_string(req->rq_reqmsg, offset + 1, sizeof(cluuid) - 1);
626         if (str == NULL) {
627                 CERROR("bad client UUID for connect\n");
628                 GOTO(out, rc = -EINVAL);
629         }
630
631         obd_str2uuid (&cluuid, str);
632
633         /* XXX extract a nettype and format accordingly */
634         switch (sizeof(ptl_nid_t)) {
635                 /* NB the casts only avoid compiler warnings */
636         case 8:
637                 snprintf((char *)remote_uuid.uuid, sizeof(remote_uuid),
638                          "NET_"LPX64"_UUID", (__u64)req->rq_peer.peer_id.nid);
639                 break;
640         case 4:
641                 snprintf((char *)remote_uuid.uuid, sizeof(remote_uuid),
642                          "NET_%x_UUID", (__u32)req->rq_peer.peer_id.nid);
643                 break;
644         default:
645                 LBUG();
646         }
647
648         tmp = lustre_msg_buf(req->rq_reqmsg, offset + 2, sizeof(conn));
649         if (tmp == NULL)
650                 GOTO(out, rc = -EPROTO);
651
652         memcpy(&conn, tmp, sizeof conn);
653
654         cfp = lustre_msg_buf(req->rq_reqmsg, offset + 3, sizeof(unsigned long));
655         LASSERT(cfp != NULL);
656         connect_flags = *cfp;
657
658         conn_data = lustre_swab_reqbuf(req, offset + 4, sizeof(*conn_data),
659                                        lustre_swab_connect);
660         if (!conn_data)
661                 GOTO(out, rc = -EPROTO);
662
663         rc = lustre_pack_reply(req, 1, &conn_data_size, NULL);
664         if (rc)
665                 GOTO(out, rc);
666         
667         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_INITIAL)
668                 initial_conn = 1;
669         
670         /* lctl gets a backstage, all-access pass. */
671         if (obd_uuid_equals(&cluuid, &target->obd_uuid))
672                 goto dont_check_exports;
673
674         spin_lock(&target->obd_dev_lock);
675         list_for_each(p, &target->obd_exports) {
676                 export = list_entry(p, struct obd_export, exp_obd_chain);
677                 if (obd_uuid_equals(&cluuid, &export->exp_client_uuid)) {
678                         spin_unlock(&target->obd_dev_lock);
679                         LASSERT(export->exp_obd == target);
680
681                         rc = target_handle_reconnect(&conn, export, &cluuid,
682                                                      initial_conn);
683                         break;
684                 }
685                 export = NULL;
686         }
687         /* If we found an export, we already unlocked. */
688         if (!export) {
689                 spin_unlock(&target->obd_dev_lock);
690         } else if (req->rq_export == NULL && 
691                    atomic_read(&export->exp_rpc_count) > 0) {
692                 CWARN("%s: refuse connection from %s/%s to 0x%p/%d\n",
693                       target->obd_name, cluuid.uuid,
694                       ptlrpc_peernid2str(&req->rq_peer, peer_str),
695                       export, atomic_read(&export->exp_refcount));
696                 GOTO(out, rc = -EBUSY);
697         } else if (req->rq_export != NULL &&
698                    atomic_read(&export->exp_rpc_count) > 1) {
699                 CWARN("%s: refuse reconnection from %s@%s to 0x%p/%d\n",
700                       target->obd_name, cluuid.uuid,
701                       ptlrpc_peernid2str(&req->rq_peer, peer_str),
702                       export, atomic_read(&export->exp_rpc_count));
703                 GOTO(out, rc = -EBUSY);
704         } else if (req->rq_reqmsg->conn_cnt == 1 && !initial_conn) {
705                 CERROR("%s reconnected with 1 conn_cnt; cookies not random?\n",
706                        cluuid.uuid);
707                 GOTO(out, rc = -EALREADY);
708         }
709
710         /* Tell the client if we're in recovery. */
711         /* If this is the first client, start the recovery timer */
712         CWARN("%s: connection from %s@%s/%lu %st"LPU64"\n", target->obd_name,
713               cluuid.uuid, ptlrpc_peernid2str(&req->rq_peer, peer_str), *cfp,
714               target->obd_recovering ? "recovering/" : "", conn_data->transno);
715
716         if (target->obd_recovering) {
717                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
718                 target_start_recovery_timer(target);
719         }
720
721 #if 0
722         /* Tell the client if we support replayable requests */
723         if (target->obd_replayable)
724                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
725 #endif
726
727         if (export == NULL) {
728                 if (target->obd_recovering) {
729                         CERROR("%s denying connection for new client %s@%s: "
730                                "%d clients in recovery for %lds\n", target->obd_name, 
731                                cluuid.uuid,
732                                ptlrpc_peernid2str(&req->rq_peer, peer_str),
733                                target->obd_recoverable_clients,
734                                (target->obd_recovery_timer.expires-jiffies)/HZ);
735                         rc = -EBUSY;
736                 } else {
737  dont_check_exports:
738                         rc = obd_connect(&conn, target, &cluuid, conn_data,
739                                          connect_flags);
740                 }
741         }
742
743         /* Return only the parts of obd_connect_data that we understand, so the
744          * client knows that we don't understand the rest. */
745         conn_data->ocd_connect_flags &= OBD_CONNECT_SUPPORTED;
746         memcpy(lustre_msg_buf(req->rq_repmsg, 0, sizeof(*conn_data)), conn_data,
747                sizeof(*conn_data));
748
749         /* Tell the client if we support replayable requests */
750         if (target->obd_replayable)
751                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
752
753         /* If all else goes well, this is our RPC return code. */
754         req->rq_status = 0;
755
756         if (rc && rc != EALREADY)
757                 GOTO(out, rc);
758
759         req->rq_repmsg->handle = conn;
760
761         /* If the client and the server are the same node, we will already
762          * have an export that really points to the client's DLM export,
763          * because we have a shared handles table.
764          *
765          * XXX this will go away when shaver stops sending the "connect" handle
766          * in the real "remote handle" field of the request --phik 24 Apr 2003
767          */
768         if (req->rq_export != NULL)
769                 class_export_put(req->rq_export);
770
771         /* ownership of this export ref transfers to the request */
772         export = req->rq_export = class_conn2export(&conn);
773         LASSERT(export != NULL);
774
775         spin_lock_irqsave(&export->exp_lock, flags);
776         if (initial_conn) {
777                 req->rq_repmsg->conn_cnt = export->exp_conn_cnt + 1;
778         } else if (export->exp_conn_cnt >= req->rq_reqmsg->conn_cnt) {
779                 CERROR("%s@%s: already connected at a higher conn_cnt: %d > %d\n",
780                        cluuid.uuid, ptlrpc_peernid2str(&req->rq_peer, peer_str),
781                        export->exp_conn_cnt, 
782                        req->rq_reqmsg->conn_cnt);
783                 spin_unlock_irqrestore(&export->exp_lock, flags);
784                 GOTO(out, rc = -EALREADY);
785         } 
786         export->exp_conn_cnt = req->rq_reqmsg->conn_cnt;
787         spin_unlock_irqrestore(&export->exp_lock, flags);
788
789         /* request from liblustre? */
790         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT)
791                 export->exp_libclient = 1;
792
793         if (!(lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_ASYNC) &&
794             ptlrpc_peer_is_local(&req->rq_peer)) {
795                 CWARN("%s: exp %p set sync\n", target->obd_name, export);
796                 export->exp_sync = 1;
797         } else {
798                 CDEBUG(D_HA, "%s: exp %p set async\n",target->obd_name,export);
799                 export->exp_sync = 0;
800         }
801
802         if (export->exp_connection != NULL)
803                 ptlrpc_put_connection(export->exp_connection);
804         export->exp_connection = ptlrpc_get_connection(&req->rq_peer,
805                                                        &remote_uuid);
806
807         if (rc == EALREADY) {
808                 /* We indicate the reconnection in a flag, not an error code. */
809                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECONNECT);
810                 GOTO(out, rc = 0);
811         }
812
813         spin_lock_bh(&target->obd_processing_task_lock);
814         if (target->obd_recovering && export->exp_connected == 0) {
815                 __u64 t = conn_data->transno;
816                 export->exp_connected = 1;
817                 if ((lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_TRANSNO)
818                                 && t < target->obd_next_recovery_transno)
819                         target->obd_next_recovery_transno = t;
820                 target->obd_connected_clients++;
821                 if (target->obd_connected_clients == target->obd_max_recoverable_clients)
822                         wake_up(&target->obd_next_transno_waitq);
823         }
824         spin_unlock_bh(&target->obd_processing_task_lock);
825
826         memcpy(&conn, lustre_msg_buf(req->rq_reqmsg, offset + 2, sizeof(conn)),
827                sizeof(conn));
828
829         if (export->exp_imp_reverse != NULL) {
830                 /* same logic as client_obd_cleanup */
831                 class_import_get(export->exp_imp_reverse);
832                 class_destroy_import(export->exp_imp_reverse);
833                 ptlrpcs_import_drop_sec(export->exp_imp_reverse);
834                 class_import_put(export->exp_imp_reverse);
835         }
836
837         /* for the rest part, we return -ENOTCONN in case of errors
838          * in order to let client initialize connection again.
839          */
840         revimp = export->exp_imp_reverse = class_new_import();
841         if (!revimp) {
842                 CERROR("fail to alloc new reverse import.\n");
843                 GOTO(out, rc = -ENOTCONN);
844         }
845
846         revimp->imp_connection = ptlrpc_connection_addref(export->exp_connection);
847         revimp->imp_client = &export->exp_obd->obd_ldlm_client;
848         revimp->imp_remote_handle = conn;
849         revimp->imp_obd = target;
850         revimp->imp_dlm_fake = 1;
851         revimp->imp_state = LUSTRE_IMP_FULL;
852
853         rc = ptlrpcs_import_get_sec(revimp);
854         if (rc) {
855                 CERROR("reverse import can not get sec: %d\n", rc);
856                 class_destroy_import(revimp);
857                 export->exp_imp_reverse = NULL;
858                 GOTO(out, rc = -ENOTCONN);
859         }
860
861         class_import_put(revimp);
862
863         rc = obd_connect_post(export, initial_conn, connect_flags);
864 out:
865         if (rc)
866                 req->rq_status = rc;
867         RETURN(rc);
868 }
869
870 int target_handle_disconnect(struct ptlrpc_request *req)
871 {
872         struct obd_export *exp;
873         int rc;
874         ENTRY;
875
876         rc = lustre_pack_reply(req, 0, NULL, NULL);
877         if (rc)
878                 RETURN(rc);
879
880         /* keep the rq_export around so we can send the reply */
881         exp = class_export_get(req->rq_export);
882         req->rq_status = obd_disconnect(exp, 0);
883         RETURN(0);
884 }
885
886 void target_destroy_export(struct obd_export *exp)
887 {
888         /* exports created from last_rcvd data, and "fake"
889            exports created by lctl don't have an import */
890         if (exp->exp_imp_reverse != NULL) {
891                 ptlrpcs_import_drop_sec(exp->exp_imp_reverse);
892                 class_destroy_import(exp->exp_imp_reverse);
893         }
894
895         /* We cancel locks at disconnect time, but this will catch any locks
896          * granted in a race with recovery-induced disconnect. */
897         if (exp->exp_obd->obd_namespace != NULL)
898                 ldlm_cancel_locks_for_export(exp);
899 }
900
901 /*
902  * Recovery functions
903  */
904
905 struct ptlrpc_request *
906 ptlrpc_clone_req( struct ptlrpc_request *orig_req) 
907 {
908         struct ptlrpc_request *copy_req;
909         struct lustre_msg *copy_reqmsg;
910
911         OBD_ALLOC(copy_req, sizeof *copy_req);
912         if (!copy_req)
913                 return NULL;
914         OBD_ALLOC(copy_reqmsg, orig_req->rq_reqlen);
915         if (!copy_reqmsg){
916                 OBD_FREE(copy_req, sizeof *copy_req);
917                 return NULL;
918         }
919
920         memcpy(copy_req, orig_req, sizeof *copy_req);
921         memcpy(copy_reqmsg, orig_req->rq_reqmsg, orig_req->rq_reqlen);
922         /* the copied req takes over the reply state and security data */
923         orig_req->rq_reply_state = NULL;
924         orig_req->rq_svcsec_data = NULL;
925
926         copy_req->rq_reqmsg = copy_reqmsg;
927         class_export_get(copy_req->rq_export);
928         INIT_LIST_HEAD(&copy_req->rq_list);
929
930         return copy_req;
931 }
932
933 void ptlrpc_free_clone( struct ptlrpc_request *req) 
934 {
935         if (req->rq_svcsec)
936                 svcsec_cleanup_req(req);
937
938         class_export_put(req->rq_export);
939         list_del(&req->rq_list);
940         OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
941         OBD_FREE(req, sizeof *req);
942 }
943
944 static void target_release_saved_req(struct ptlrpc_request *req)
945 {
946         if (req->rq_svcsec)
947                 svcsec_cleanup_req(req);
948
949         class_export_put(req->rq_export);
950         OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
951         OBD_FREE(req, sizeof *req);
952 }
953
954 static void target_finish_recovery(struct obd_device *obd)
955 {
956         int rc;
957
958         ldlm_reprocess_all_ns(obd->obd_namespace);
959
960         /* when recovery finished, cleanup orphans on mds and ost */
961         if (OBT(obd) && OBP(obd, postrecov)) {
962                 rc = OBP(obd, postrecov)(obd);
963                 if (rc >= 0)
964                         CWARN("%s: all clients recovered, %d MDS "
965                               "orphans deleted\n", obd->obd_name, rc);
966                 else
967                         CERROR("postrecov failed %d\n", rc);
968         }
969
970         obd->obd_recovery_end = LTIME_S(CURRENT_TIME);
971         return;
972 }
973
974 static void abort_req_replay_queue(struct obd_device *obd)
975 {
976         struct ptlrpc_request *req;
977         struct list_head *tmp, *n;
978         int rc;
979
980         list_for_each_safe(tmp, n, &obd->obd_req_replay_queue) {
981                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
982                 list_del(&req->rq_list);
983                 DEBUG_REQ(D_ERROR, req, "aborted:");
984                 req->rq_status = -ENOTCONN;
985                 req->rq_type = PTL_RPC_MSG_ERR;
986                 rc = lustre_pack_reply(req, 0, NULL, NULL);
987                 if (rc == 0) {
988                         ptlrpc_reply(req);
989                 } else {
990                         DEBUG_REQ(D_ERROR, req,
991                                   "packing failed for abort-reply; skipping");
992                 }
993                 target_release_saved_req(req);
994         }
995 }
996
997 static void abort_lock_replay_queue(struct obd_device *obd)
998 {
999         struct ptlrpc_request *req;
1000         struct list_head *tmp, *n;
1001         int rc;
1002
1003         list_for_each_safe(tmp, n, &obd->obd_lock_replay_queue) {
1004                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
1005                 list_del(&req->rq_list);
1006                 DEBUG_REQ(D_ERROR, req, "aborted:");
1007                 req->rq_status = -ENOTCONN;
1008                 req->rq_type = PTL_RPC_MSG_ERR;
1009                 rc = lustre_pack_reply(req, 0, NULL, NULL);
1010                 if (rc == 0) {
1011                         ptlrpc_reply(req);
1012                 } else {
1013                         DEBUG_REQ(D_ERROR, req,
1014                                   "packing failed for abort-reply; skipping");
1015                 }
1016                 target_release_saved_req(req);
1017         }
1018 }
1019
1020 /* Called from a cleanup function if the device is being cleaned up
1021    forcefully.  The exports should all have been disconnected already,
1022    the only thing left to do is
1023      - clear the recovery flags
1024      - cancel the timer
1025      - free queued requests and replies, but don't send replies
1026    Because the obd_stopping flag is set, no new requests should be received.
1027
1028 */
1029 void target_cleanup_recovery(struct obd_device *obd)
1030 {
1031         struct list_head *tmp, *n;
1032         struct ptlrpc_request *req;
1033
1034         spin_lock_bh(&obd->obd_processing_task_lock);
1035         if (!obd->obd_recovering) {
1036                 spin_unlock_bh(&obd->obd_processing_task_lock);
1037                 EXIT;
1038                 return;
1039         }
1040         obd->obd_recovering = obd->obd_abort_recovery = 0;
1041         target_cancel_recovery_timer(obd);
1042         spin_unlock_bh(&obd->obd_processing_task_lock);
1043
1044         list_for_each_safe(tmp, n, &obd->obd_req_replay_queue) {
1045                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
1046                 list_del(&req->rq_list);
1047                 LASSERT (req->rq_reply_state == 0);
1048                 target_release_saved_req(req);
1049         }
1050         list_for_each_safe(tmp, n, &obd->obd_lock_replay_queue) {
1051                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
1052                 list_del(&req->rq_list);
1053                 LASSERT (req->rq_reply_state == 0);
1054                 target_release_saved_req(req);
1055         }
1056         list_for_each_safe(tmp, n, &obd->obd_final_req_queue) {
1057                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
1058                 list_del(&req->rq_list);
1059                 LASSERT (req->rq_reply_state == 0);
1060                 target_release_saved_req(req);
1061         }
1062 }
1063
1064 #if 0
1065 static void target_abort_recovery(void *data)
1066 {
1067         struct obd_device *obd = data;
1068
1069         LASSERT(!obd->obd_recovering);
1070
1071         class_disconnect_stale_exports(obd, 0);
1072
1073         CERROR("%s: recovery period over; disconnecting unfinished clients.\n",
1074                obd->obd_name);
1075
1076         abort_recovery_queue(obd);
1077         target_finish_recovery(obd);
1078         ptlrpc_run_recovery_over_upcall(obd);
1079 }
1080 #endif
1081
1082 static void target_recovery_expired(unsigned long castmeharder)
1083 {
1084         struct obd_device *obd = (struct obd_device *)castmeharder;
1085         spin_lock_bh(&obd->obd_processing_task_lock);
1086         if (obd->obd_recovering)
1087                 obd->obd_abort_recovery = 1;
1088
1089         wake_up(&obd->obd_next_transno_waitq);
1090         spin_unlock_bh(&obd->obd_processing_task_lock);
1091 }
1092
1093
1094 /* obd_processing_task_lock should be held */
1095 void target_cancel_recovery_timer(struct obd_device *obd)
1096 {
1097         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1098         del_timer(&obd->obd_recovery_timer);
1099 }
1100
1101 #ifdef __KERNEL__
1102 static void reset_recovery_timer(struct obd_device *obd)
1103 {
1104         spin_lock_bh(&obd->obd_processing_task_lock);
1105         if (!obd->obd_recovering) {
1106                 spin_unlock_bh(&obd->obd_processing_task_lock);
1107                 return;
1108         }                
1109         CDEBUG(D_HA, "timer will expire in %u seconds\n",
1110                OBD_RECOVERY_TIMEOUT / HZ);
1111         mod_timer(&obd->obd_recovery_timer, jiffies + OBD_RECOVERY_TIMEOUT);
1112         spin_unlock_bh(&obd->obd_processing_task_lock);
1113 }
1114 #endif
1115
1116 /* Only start it the first time called */
1117 void target_start_recovery_timer(struct obd_device *obd)
1118 {
1119         spin_lock_bh(&obd->obd_processing_task_lock);
1120         if (!obd->obd_recovering || timer_pending(&obd->obd_recovery_timer)) {
1121                 spin_unlock_bh(&obd->obd_processing_task_lock);
1122                 return;
1123         }
1124         CWARN("%s: starting recovery timer (%us)\n", obd->obd_name,
1125                OBD_RECOVERY_TIMEOUT / HZ);
1126         obd->obd_recovery_timer.function = target_recovery_expired;
1127         obd->obd_recovery_timer.data = (unsigned long)obd;
1128         mod_timer(&obd->obd_recovery_timer, jiffies + OBD_RECOVERY_TIMEOUT);
1129         spin_unlock_bh(&obd->obd_processing_task_lock);
1130 }
1131
1132 #ifdef __KERNEL__
1133 static int check_for_next_transno(struct obd_device *obd)
1134 {
1135         struct ptlrpc_request *req = NULL;
1136         int wake_up = 0, connected, completed, queue_len, max;
1137         __u64 next_transno, req_transno;
1138
1139         spin_lock_bh(&obd->obd_processing_task_lock);
1140         if (!list_empty(&obd->obd_req_replay_queue)) {
1141                 req = list_entry(obd->obd_req_replay_queue.next,
1142                                  struct ptlrpc_request, rq_list);
1143                 req_transno = req->rq_reqmsg->transno;
1144         } else {
1145                 req_transno = 0;
1146         }
1147
1148         max = obd->obd_max_recoverable_clients;
1149         connected = obd->obd_connected_clients;
1150         completed = max - obd->obd_recoverable_clients;
1151         queue_len = obd->obd_requests_queued_for_recovery;
1152         next_transno = obd->obd_next_recovery_transno;
1153
1154         CDEBUG(D_HA,"max: %d, connected: %d, completed: %d, queue_len: %d, "
1155                "req_transno: "LPU64", next_transno: "LPU64"\n",
1156                max, connected, completed, queue_len, req_transno, next_transno);
1157         if (obd->obd_abort_recovery) {
1158                 CDEBUG(D_HA, "waking for aborted recovery\n");
1159                 wake_up = 1;
1160         } else if (atomic_read(&obd->obd_req_replay_clients) == 0) {
1161                 CDEBUG(D_HA, "waking for completed recovery\n");
1162                 wake_up = 1;
1163         } else if (req_transno == next_transno) {
1164                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1165                 wake_up = 1;
1166         } else if (queue_len + completed == max) {
1167                 LASSERT(req->rq_reqmsg->transno >= next_transno);
1168                 CDEBUG(req_transno > obd->obd_last_committed ? D_ERROR : D_HA,
1169                        "waking for skipped transno (skip: "LPD64
1170                        ", ql: %d, comp: %d, conn: %d, next: "LPD64")\n",
1171                        next_transno, queue_len, completed, max, req_transno);
1172                 obd->obd_next_recovery_transno = req_transno;
1173                 wake_up = 1;
1174         } else if (queue_len == atomic_read(&obd->obd_req_replay_clients)) {
1175                 /* some clients haven't connected in time, but we need
1176                  * their requests to continue recovery. so, we abort ... */
1177                 CDEBUG(D_ERROR, "abort due to missed clients: queue: %d max: %d\n",
1178                        queue_len, max);
1179                 obd->obd_abort_recovery = 1;
1180                 wake_up = 1;
1181         }
1182         spin_unlock_bh(&obd->obd_processing_task_lock);
1183         
1184         return wake_up;
1185 }
1186
1187 static struct ptlrpc_request *
1188 target_next_replay_req(struct obd_device *obd)
1189 {
1190         struct l_wait_info lwi = { 0 };
1191         struct ptlrpc_request *req;
1192
1193         CDEBUG(D_HA, "Waiting for transno "LPD64"\n",
1194                obd->obd_next_recovery_transno);
1195         l_wait_event(obd->obd_next_transno_waitq,
1196                      check_for_next_transno(obd), &lwi);
1197         
1198         spin_lock_bh(&obd->obd_processing_task_lock);
1199         if (obd->obd_abort_recovery) {
1200                 req = NULL;
1201         } else if (!list_empty(&obd->obd_req_replay_queue)) {
1202                 req = list_entry(obd->obd_req_replay_queue.next,
1203                                  struct ptlrpc_request, rq_list);
1204                 list_del_init(&req->rq_list);
1205                 obd->obd_requests_queued_for_recovery--;
1206         } else {
1207                 req = NULL;
1208         }
1209         spin_unlock_bh(&obd->obd_processing_task_lock);
1210         return req;
1211 }
1212
1213 static int check_for_next_lock(struct obd_device *obd)
1214 {
1215         struct ptlrpc_request *req = NULL;
1216         int wake_up = 0;
1217
1218         spin_lock_bh(&obd->obd_processing_task_lock);
1219         if (!list_empty(&obd->obd_lock_replay_queue)) {
1220                 req = list_entry(obd->obd_lock_replay_queue.next,
1221                                  struct ptlrpc_request, rq_list);
1222                 CDEBUG(D_HA, "waking for next lock\n");
1223                 wake_up = 1;
1224         } else if (atomic_read(&obd->obd_lock_replay_clients) == 0) {
1225                 CDEBUG(D_HA, "waking for completed lock replay\n");
1226                 wake_up = 1;
1227         } else if (obd->obd_abort_recovery) {
1228                 CDEBUG(D_HA, "waking for aborted recovery\n");
1229                 wake_up = 1;
1230         }
1231         spin_unlock_bh(&obd->obd_processing_task_lock);
1232         
1233         return wake_up;
1234 }
1235
1236 static struct ptlrpc_request *
1237 target_next_replay_lock(struct obd_device *obd)
1238 {
1239         struct l_wait_info lwi = { 0 };
1240         struct ptlrpc_request *req;
1241
1242         CDEBUG(D_HA, "Waiting for lock\n");
1243         l_wait_event(obd->obd_next_transno_waitq,
1244                      check_for_next_lock(obd), &lwi);
1245         
1246         spin_lock_bh(&obd->obd_processing_task_lock);
1247         if (obd->obd_abort_recovery) {
1248                 req = NULL;
1249         } else if (!list_empty(&obd->obd_lock_replay_queue)) {
1250                 req = list_entry(obd->obd_lock_replay_queue.next,
1251                                  struct ptlrpc_request, rq_list);
1252                 list_del_init(&req->rq_list);
1253         } else {
1254                 req = NULL;
1255         }
1256         spin_unlock_bh(&obd->obd_processing_task_lock);
1257         return req;
1258 }
1259
1260 static struct ptlrpc_request *
1261 target_next_final_ping(struct obd_device *obd)
1262 {
1263         struct ptlrpc_request *req;
1264
1265         spin_lock_bh(&obd->obd_processing_task_lock);
1266         if (!list_empty(&obd->obd_final_req_queue)) {
1267                 req = list_entry(obd->obd_final_req_queue.next,
1268                                  struct ptlrpc_request, rq_list);
1269                 list_del_init(&req->rq_list);
1270         } else {
1271                 req = NULL;
1272         }
1273         spin_unlock_bh(&obd->obd_processing_task_lock);
1274         return req;
1275 }
1276
1277 static int req_replay_done(struct obd_export *exp)
1278 {
1279         if (exp->exp_req_replay_needed)
1280                 return 0;
1281         return 1;
1282 }
1283
1284 static int lock_replay_done(struct obd_export *exp)
1285 {
1286         if (exp->exp_lock_replay_needed)
1287                 return 0;
1288         return 1;
1289 }
1290
1291 static int connect_done(struct obd_export *exp)
1292 {
1293         if (exp->exp_connected)
1294                 return 1;
1295         return 0;
1296 }
1297
1298 static int check_for_clients(struct obd_device *obd)
1299 {
1300         if (obd->obd_abort_recovery)
1301                 return 1;
1302         LASSERT(obd->obd_connected_clients <= obd->obd_max_recoverable_clients);
1303         if (obd->obd_connected_clients == obd->obd_max_recoverable_clients)
1304                 return 1;
1305         return 0;
1306 }
1307
1308 static int target_recovery_thread(void *arg)
1309 {
1310         struct obd_device *obd = arg;
1311         struct ptlrpc_request *req;
1312         struct target_recovery_data *trd = &obd->obd_recovery_data;
1313         char peer_str[PTL_NALFMT_SIZE];
1314         struct l_wait_info lwi = { 0 };
1315         unsigned long flags;
1316         ENTRY;
1317
1318         kportal_daemonize("tgt-recov");
1319
1320         SIGNAL_MASK_LOCK(current, flags);
1321         sigfillset(&current->blocked);
1322         RECALC_SIGPENDING;
1323         SIGNAL_MASK_UNLOCK(current, flags);
1324
1325         CERROR("%s: started recovery thread pid %d\n", obd->obd_name, 
1326                current->pid);
1327         trd->trd_processing_task = current->pid;
1328
1329         obd->obd_recovering = 1;
1330         complete(&trd->trd_starting);
1331
1332         /* first of all, we have to know the first transno to replay */
1333         obd->obd_abort_recovery = 0;
1334         l_wait_event(obd->obd_next_transno_waitq,
1335                      check_for_clients(obd), &lwi);
1336         
1337         spin_lock_bh(&obd->obd_processing_task_lock);
1338         target_cancel_recovery_timer(obd);
1339         spin_unlock_bh(&obd->obd_processing_task_lock);
1340
1341         /* If some clients haven't connected in time, evict them */
1342         if (obd->obd_abort_recovery) {
1343                 int stale;
1344                 CERROR("some clients haven't connect in time (%d/%d),"
1345                        "evict them ...\n", obd->obd_connected_clients,
1346                        obd->obd_max_recoverable_clients);
1347                 obd->obd_abort_recovery = 0;
1348                 stale = class_disconnect_stale_exports(obd, connect_done, 0);
1349                 atomic_sub(stale, &obd->obd_req_replay_clients);
1350                 atomic_sub(stale, &obd->obd_lock_replay_clients);
1351         }
1352
1353         /* next stage: replay requests */
1354         CWARN("1: request replay stage - %d clients from t"LPU64"\n",
1355               atomic_read(&obd->obd_req_replay_clients),
1356               obd->obd_next_recovery_transno);
1357         while ((req = target_next_replay_req(obd))) {
1358                 LASSERT(trd->trd_processing_task == current->pid);
1359                 DEBUG_REQ(D_HA, req, "processing t"LPD64" from %s: ", 
1360                           req->rq_reqmsg->transno, 
1361                           ptlrpc_peernid2str(&req->rq_peer, peer_str));
1362                 (void)trd->trd_recovery_handler(req);
1363                 obd->obd_replayed_requests++;
1364                 reset_recovery_timer(obd);
1365                 /* bug 1580: decide how to properly sync() in recovery*/
1366                 //mds_fsync_super(mds->mds_sb);
1367                 ptlrpc_free_clone(req);
1368                 spin_lock_bh(&obd->obd_processing_task_lock);
1369                 obd->obd_next_recovery_transno++;
1370                 spin_unlock_bh(&obd->obd_processing_task_lock);
1371         }
1372
1373         spin_lock_bh(&obd->obd_processing_task_lock);
1374         target_cancel_recovery_timer(obd);
1375         spin_unlock_bh(&obd->obd_processing_task_lock);
1376
1377         /* If some clients haven't replayed requests in time, evict them */
1378         if (obd->obd_abort_recovery) {
1379                 int stale;
1380                 CERROR("req replay timed out, aborting ...\n");
1381                 obd->obd_abort_recovery = 0;
1382                 stale = class_disconnect_stale_exports(obd, req_replay_done, 0);
1383                 atomic_sub(stale, &obd->obd_lock_replay_clients);
1384                 abort_req_replay_queue(obd);
1385         }
1386
1387         /* The second stage: replay locks */
1388         CWARN("2: lock replay stage - %d clients\n",
1389               atomic_read(&obd->obd_lock_replay_clients));
1390         while ((req = target_next_replay_lock(obd))) {
1391                 LASSERT(trd->trd_processing_task == current->pid);
1392                 DEBUG_REQ(D_HA, req, "processing lock from %s: ", 
1393                           ptlrpc_peernid2str(&req->rq_peer, peer_str));
1394                 (void)trd->trd_recovery_handler(req);
1395                 reset_recovery_timer(obd);
1396                 ptlrpc_free_clone(req);
1397                 obd->obd_replayed_locks++;
1398         }
1399         
1400         spin_lock_bh(&obd->obd_processing_task_lock);
1401         target_cancel_recovery_timer(obd);
1402         spin_unlock_bh(&obd->obd_processing_task_lock);
1403
1404         /* If some clients haven't replayed requests in time, evict them */
1405         if (obd->obd_abort_recovery) {
1406                 int stale;
1407                 CERROR("lock replay timed out, aborting ...\n");
1408                 obd->obd_abort_recovery = 0;
1409                 stale = class_disconnect_stale_exports(obd, lock_replay_done, 0);
1410                 abort_lock_replay_queue(obd);
1411         }
1412
1413         /* We drop recoverying flag to forward all new requests
1414          * to regular mds_handle() since now */
1415         spin_lock_bh(&obd->obd_processing_task_lock);
1416         obd->obd_recovering = 0;
1417         spin_unlock_bh(&obd->obd_processing_task_lock);
1418
1419         /* The third stage: reply on final pings */
1420         CWARN("3: final stage - process recovery completion pings\n");
1421         while ((req = target_next_final_ping(obd))) {
1422                 LASSERT(trd->trd_processing_task == current->pid);
1423                 DEBUG_REQ(D_HA, req, "processing final ping from %s: ", 
1424                           ptlrpc_peernid2str(&req->rq_peer, peer_str));
1425                 (void)trd->trd_recovery_handler(req);
1426                 ptlrpc_free_clone(req);
1427         }
1428         
1429         CWARN("4: recovery completed - %d/%d reqs/locks replayed\n",
1430               obd->obd_replayed_requests, obd->obd_replayed_locks);
1431         target_finish_recovery(obd);
1432
1433         trd->trd_processing_task = 0;
1434         complete(&trd->trd_finishing);
1435         return 0;
1436 }
1437
1438 int target_start_recovery_thread(struct obd_device *obd, svc_handler_t handler)
1439 {
1440         int rc = 0;
1441         struct target_recovery_data *trd = &obd->obd_recovery_data;
1442
1443         memset(trd, 0, sizeof(*trd));
1444         init_completion(&trd->trd_starting);
1445         init_completion(&trd->trd_finishing);
1446         trd->trd_recovery_handler = handler;
1447
1448         if (kernel_thread(target_recovery_thread, obd, 0) > 0) {
1449                 wait_for_completion(&trd->trd_starting);
1450                 LASSERT(obd->obd_recovering != 0);
1451         } else
1452                 rc = -ECHILD;
1453
1454         return rc;
1455 }
1456
1457 void target_stop_recovery_thread(struct obd_device *obd)
1458 {
1459         spin_lock_bh(&obd->obd_processing_task_lock);
1460         if (obd->obd_recovery_data.trd_processing_task > 0) {
1461                 struct target_recovery_data *trd = &obd->obd_recovery_data;
1462                 CERROR("%s: aborting recovery\n", obd->obd_name);
1463                 obd->obd_abort_recovery = 1;
1464                 wake_up(&obd->obd_next_transno_waitq);
1465                 spin_unlock_bh(&obd->obd_processing_task_lock);
1466                 wait_for_completion(&trd->trd_finishing);
1467         } else {
1468                 spin_unlock_bh(&obd->obd_processing_task_lock);
1469         }
1470 }
1471 #endif
1472
1473 int target_process_req_flags(struct obd_device *obd, struct ptlrpc_request *req)
1474 {
1475         struct obd_export *exp = req->rq_export;
1476         LASSERT(exp != NULL);
1477         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1478                 /* client declares he's ready to replay locks */
1479                 spin_lock_bh(&obd->obd_processing_task_lock);
1480                 if (exp->exp_req_replay_needed) {
1481                         LASSERT(atomic_read(&obd->obd_req_replay_clients) > 0);
1482                         exp->exp_req_replay_needed = 0;
1483                         atomic_dec(&obd->obd_req_replay_clients);
1484                         obd->obd_recoverable_clients--;
1485                         if (atomic_read(&obd->obd_req_replay_clients) == 0)
1486                                 CDEBUG(D_HA, "all clients have replayed reqs\n");
1487                         wake_up(&obd->obd_next_transno_waitq);
1488                 }
1489                 spin_unlock_bh(&obd->obd_processing_task_lock);
1490         }
1491         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1492                 /* client declares he's ready to complete recovery 
1493                  * so, we put the request on th final queue */
1494                 spin_lock_bh(&obd->obd_processing_task_lock);
1495                 if (exp->exp_lock_replay_needed) {
1496                         LASSERT(atomic_read(&obd->obd_lock_replay_clients) > 0);
1497                         exp->exp_lock_replay_needed = 0;
1498                         atomic_dec(&obd->obd_lock_replay_clients);
1499                         if (atomic_read(&obd->obd_lock_replay_clients) == 0)
1500                                 CDEBUG(D_HA, "all clients have replayed locks\n");
1501                         wake_up(&obd->obd_next_transno_waitq);
1502                 }
1503                 spin_unlock_bh(&obd->obd_processing_task_lock);
1504         }
1505
1506         return 0;
1507 }
1508
1509 int target_queue_recovery_request(struct ptlrpc_request *req,
1510                                   struct obd_device *obd)
1511 {
1512         struct list_head *tmp;
1513         int inserted = 0;
1514         __u64 transno = req->rq_reqmsg->transno;
1515
1516         if (obd->obd_recovery_data.trd_processing_task == current->pid) {
1517                 /* Processing the queue right now, don't re-add. */
1518                 return 1;
1519         }
1520
1521         target_process_req_flags(obd, req);
1522
1523         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1524                 /* client declares he's ready to complete recovery 
1525                  * so, we put the request on th final queue */
1526                 req = ptlrpc_clone_req(req);
1527                 if (req == NULL)
1528                         return -ENOMEM;
1529                 DEBUG_REQ(D_HA, req, "queue final req");
1530                 spin_lock_bh(&obd->obd_processing_task_lock);
1531                 list_add_tail(&req->rq_list, &obd->obd_final_req_queue);
1532                 spin_unlock_bh(&obd->obd_processing_task_lock);
1533                 return 0;
1534         }
1535         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1536                 /* client declares he's ready to replay locks */
1537                 req = ptlrpc_clone_req(req);
1538                 if (req == NULL)
1539                         return -ENOMEM;
1540                 DEBUG_REQ(D_HA, req, "queue lock replay req");
1541                 spin_lock_bh(&obd->obd_processing_task_lock);
1542                 list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
1543                 spin_unlock_bh(&obd->obd_processing_task_lock);
1544                 wake_up(&obd->obd_next_transno_waitq);
1545                 return 0;
1546         }
1547
1548
1549         /* CAVEAT EMPTOR: The incoming request message has been swabbed
1550          * (i.e. buflens etc are in my own byte order), but type-dependent
1551          * buffers (eg mds_body, ost_body etc) have NOT been swabbed. */
1552
1553         if (!transno) {
1554                 INIT_LIST_HEAD(&req->rq_list);
1555                 DEBUG_REQ(D_HA, req, "not queueing");
1556                 return 1;
1557         }
1558
1559
1560         /* If we're processing the queue, we want don't want to queue this
1561          * message.
1562          *
1563          * Also, if this request has a transno less than the one we're waiting
1564          * for, we should process it now.  It could (and currently always will)
1565          * be an open request for a descriptor that was opened some time ago.
1566          *
1567          * Also, a resent, replayed request that has already been
1568          * handled will pass through here and be processed immediately.
1569          */
1570         spin_lock_bh(&obd->obd_processing_task_lock);
1571         if (transno < obd->obd_next_recovery_transno && check_for_clients(obd)) {
1572                 /* Processing the queue right now, don't re-add. */
1573                 LASSERT(list_empty(&req->rq_list));
1574                 spin_unlock_bh(&obd->obd_processing_task_lock);
1575                 return 1;
1576         }
1577         spin_unlock_bh(&obd->obd_processing_task_lock);
1578
1579         /* A resent, replayed request that is still on the queue; just drop it.
1580            The queued request will handle this. */
1581         if ((lustre_msg_get_flags(req->rq_reqmsg) & (MSG_RESENT | MSG_REPLAY))
1582             == (MSG_RESENT | MSG_REPLAY)) {
1583                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
1584                 return 0;
1585         }
1586
1587         req = ptlrpc_clone_req(req);
1588         if (req == NULL)
1589                 return -ENOMEM;
1590
1591         spin_lock_bh(&obd->obd_processing_task_lock);
1592
1593         /* XXX O(n^2) */
1594         list_for_each(tmp, &obd->obd_req_replay_queue) {
1595                 struct ptlrpc_request *reqiter =
1596                         list_entry(tmp, struct ptlrpc_request, rq_list);
1597
1598                 if (reqiter->rq_reqmsg->transno > transno) {
1599                         list_add_tail(&req->rq_list, &reqiter->rq_list);
1600                         inserted = 1;
1601                         break;
1602                 }
1603         }
1604
1605         if (!inserted)
1606                 list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
1607
1608         obd->obd_requests_queued_for_recovery++;
1609         wake_up(&obd->obd_next_transno_waitq);
1610         spin_unlock_bh(&obd->obd_processing_task_lock);
1611         return 0;
1612 }
1613
1614 struct obd_device * target_req2obd(struct ptlrpc_request *req)
1615 {
1616         return req->rq_export->exp_obd;
1617 }
1618
1619 int
1620 target_send_reply_msg (struct ptlrpc_request *req, int rc, int fail_id)
1621 {
1622         if (OBD_FAIL_CHECK(fail_id | OBD_FAIL_ONCE)) {
1623                 obd_fail_loc |= OBD_FAIL_ONCE | OBD_FAILED;
1624                 DEBUG_REQ(D_ERROR, req, "dropping reply");
1625                 /* NB this does _not_ send with ACK disabled, to simulate
1626                  * sending OK, but timing out for the ACK */
1627                 if (req->rq_reply_state != NULL) {
1628                         if (!req->rq_reply_state->rs_difficult) {
1629                                 lustre_free_reply_state (req->rq_reply_state);
1630                                 req->rq_reply_state = NULL;
1631                         } else {
1632                                 struct ptlrpc_service *svc =
1633                                         req->rq_rqbd->rqbd_srv_ni->sni_service;
1634                                 atomic_inc(&svc->srv_outstanding_replies);
1635                         }
1636                 }
1637                 return (-ECOMM);
1638         }
1639
1640         if (rc) {
1641                 req->rq_status = rc;
1642                 return (ptlrpc_error(req));
1643         } else {
1644                 DEBUG_REQ(D_NET, req, "sending reply");
1645         }
1646         
1647         return (ptlrpc_send_reply(req, 1));
1648 }
1649
1650 void 
1651 target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
1652 {
1653         int                        netrc;
1654         unsigned long              flags;
1655         struct ptlrpc_reply_state *rs;
1656         struct obd_device         *obd;
1657         struct obd_export         *exp;
1658         struct ptlrpc_srv_ni      *sni;
1659         struct ptlrpc_service     *svc;
1660
1661         sni = req->rq_rqbd->rqbd_srv_ni;
1662         svc = sni->sni_service;
1663         
1664         rs = req->rq_reply_state;
1665         if (rs == NULL || !rs->rs_difficult) {
1666                 /* The easy case; no notifiers and reply_out_callback()
1667                  * cleans up (i.e. we can't look inside rs after a
1668                  * successful send) */
1669                 netrc = target_send_reply_msg (req, rc, fail_id);
1670
1671                 LASSERT (netrc == 0 || req->rq_reply_state == NULL);
1672                 return;
1673         }
1674
1675         /* must be an export if locks saved */
1676         LASSERT (req->rq_export != NULL);
1677         /* req/reply consistent */
1678         LASSERT (rs->rs_srv_ni == sni);
1679
1680         /* "fresh" reply */
1681         LASSERT (!rs->rs_scheduled);
1682         LASSERT (!rs->rs_scheduled_ever);
1683         LASSERT (!rs->rs_handled);
1684         LASSERT (!rs->rs_on_net);
1685         LASSERT (rs->rs_export == NULL);
1686         LASSERT (list_empty(&rs->rs_obd_list));
1687         LASSERT (list_empty(&rs->rs_exp_list));
1688
1689         exp = class_export_get (req->rq_export);
1690         obd = exp->exp_obd;
1691
1692         /* disable reply scheduling onto srv_reply_queue while I'm setting up */
1693         rs->rs_scheduled = 1;
1694         rs->rs_on_net    = 1;
1695         rs->rs_xid       = req->rq_xid;
1696         rs->rs_transno   = req->rq_transno;
1697         rs->rs_export    = exp;
1698         
1699         spin_lock_irqsave (&obd->obd_uncommitted_replies_lock, flags);
1700
1701         if (rs->rs_transno > obd->obd_last_committed) {
1702                 /* not committed already */ 
1703                 list_add_tail (&rs->rs_obd_list, 
1704                                &obd->obd_uncommitted_replies);
1705         }
1706
1707         spin_unlock (&obd->obd_uncommitted_replies_lock);
1708         spin_lock (&exp->exp_lock);
1709
1710         list_add_tail (&rs->rs_exp_list, &exp->exp_outstanding_replies);
1711
1712         spin_unlock_irqrestore (&exp->exp_lock, flags);
1713
1714         netrc = target_send_reply_msg (req, rc, fail_id);
1715
1716         spin_lock_irqsave (&svc->srv_lock, flags);
1717
1718         svc->srv_n_difficult_replies++;
1719
1720         if (netrc != 0) /* error sending: reply is off the net */
1721                 rs->rs_on_net = 0;
1722
1723         if (!rs->rs_on_net ||                   /* some notifier */
1724             list_empty(&rs->rs_exp_list) ||     /* completed already */
1725             list_empty(&rs->rs_obd_list)) {
1726                 list_add_tail (&rs->rs_list, &svc->srv_reply_queue);
1727                 wake_up (&svc->srv_waitq);
1728         } else {
1729                 list_add (&rs->rs_list, &sni->sni_active_replies);
1730                 rs->rs_scheduled = 0;           /* allow notifier to schedule */
1731         }
1732
1733         spin_unlock_irqrestore (&svc->srv_lock, flags);
1734 }
1735
1736 int target_handle_ping(struct ptlrpc_request *req)
1737 {
1738         return lustre_pack_reply(req, 0, NULL, NULL);
1739 }