Whamcloud - gitweb
d86e89268fc840a06a024ade1d1c736b500402c8
[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
39 int client_obd_setup(struct obd_device *obddev, obd_count len, void *buf)
40 {
41         struct ptlrpc_connection *conn;
42         struct lustre_cfg* lcfg = buf;
43         struct client_obd *cli = &obddev->u.cli;
44         struct obd_import *imp;
45         struct obd_uuid server_uuid;
46         int rq_portal, rp_portal, connect_op;
47         char *name = obddev->obd_type->typ_name;
48         char *mgmt_name = NULL;
49         int rc;
50         struct obd_device *mgmt_obd;
51         mgmtcli_register_for_events_t register_f;
52         ENTRY;
53
54         /* In a more perfect world, we would hang a ptlrpc_client off of
55          * obd_type and just use the values from there. */
56         if (!strcmp(name, LUSTRE_OSC_NAME)) {
57                 rq_portal = OST_REQUEST_PORTAL;
58                 rp_portal = OSC_REPLY_PORTAL;
59                 connect_op = OST_CONNECT;
60         } else if (!strcmp(name, LUSTRE_MDC_NAME)) {
61                 rq_portal = MDS_REQUEST_PORTAL;
62                 rp_portal = MDC_REPLY_PORTAL;
63                 connect_op = MDS_CONNECT;
64         } else if (!strcmp(name, LUSTRE_MGMTCLI_NAME)) {
65                 rq_portal = MGMT_REQUEST_PORTAL;
66                 rp_portal = MGMT_REPLY_PORTAL;
67                 connect_op = MGMT_CONNECT;
68         } else {
69                 CERROR("unknown client OBD type \"%s\", can't setup\n",
70                        name);
71                 RETURN(-EINVAL);
72         }
73
74         if (lcfg->lcfg_inllen1 < 1) {
75                 CERROR("requires a TARGET UUID\n");
76                 RETURN(-EINVAL);
77         }
78
79         if (lcfg->lcfg_inllen1 > 37) {
80                 CERROR("client UUID must be less than 38 characters\n");
81                 RETURN(-EINVAL);
82         }
83
84         if (lcfg->lcfg_inllen2 < 1) {
85                 CERROR("setup requires a SERVER UUID\n");
86                 RETURN(-EINVAL);
87         }
88
89         if (lcfg->lcfg_inllen2 > 37) {
90                 CERROR("target UUID must be less than 38 characters\n");
91                 RETURN(-EINVAL);
92         }
93
94         sema_init(&cli->cl_sem, 1);
95         cli->cl_conn_count = 0;
96         memcpy(server_uuid.uuid, lcfg->lcfg_inlbuf2,
97                min_t(unsigned int, lcfg->lcfg_inllen2, sizeof(server_uuid)));
98
99         cli->cl_dirty = 0;
100         cli->cl_avail_grant = 0;
101         cli->cl_dirty_max = OSC_MAX_DIRTY_DEFAULT * 1024 * 1024;
102         INIT_LIST_HEAD(&cli->cl_cache_waiters);
103         INIT_LIST_HEAD(&cli->cl_loi_ready_list);
104         INIT_LIST_HEAD(&cli->cl_loi_write_list);
105         INIT_LIST_HEAD(&cli->cl_loi_read_list);
106         spin_lock_init(&cli->cl_loi_list_lock);
107         cli->cl_brw_in_flight = 0;
108         spin_lock_init(&cli->cl_read_rpc_hist.oh_lock);
109         spin_lock_init(&cli->cl_write_rpc_hist.oh_lock);
110         spin_lock_init(&cli->cl_read_page_hist.oh_lock);
111         spin_lock_init(&cli->cl_write_page_hist.oh_lock);
112         cli->cl_max_pages_per_rpc = PTLRPC_MAX_BRW_PAGES;
113         cli->cl_max_rpcs_in_flight = OSC_MAX_RIF_DEFAULT;
114
115         rc = ldlm_get_ref();
116         if (rc) {
117                 CERROR("ldlm_get_ref failed: %d\n", rc);
118                 GOTO(err, rc);
119         }
120
121         conn = ptlrpc_uuid_to_connection(&server_uuid);
122         if (conn == NULL)
123                 GOTO(err_ldlm, rc = -ENOENT);
124
125         ptlrpc_init_client(rq_portal, rp_portal, name,
126                            &obddev->obd_ldlm_client);
127
128         imp = class_new_import();
129         if (imp == NULL) {
130                 ptlrpc_put_connection(conn);
131                 GOTO(err_ldlm, rc = -ENOENT);
132         }
133         imp->imp_connection = conn;
134         imp->imp_client = &obddev->obd_ldlm_client;
135         imp->imp_obd = obddev;
136         imp->imp_connect_op = connect_op;
137         imp->imp_generation = 0;
138         imp->imp_initial_recov = 1;
139         INIT_LIST_HEAD(&imp->imp_pinger_chain);
140         memcpy(imp->imp_target_uuid.uuid, lcfg->lcfg_inlbuf1,
141               lcfg->lcfg_inllen1);
142         class_import_put(imp);
143
144         cli->cl_import = imp;
145         cli->cl_max_mds_easize = sizeof(struct lov_mds_md);
146         cli->cl_max_mds_cookiesize = sizeof(struct llog_cookie);
147         cli->cl_sandev = to_kdev_t(0);
148
149         if (lcfg->lcfg_inllen3 != 0) {
150                 if (!strcmp(lcfg->lcfg_inlbuf3, "inactive")) {
151                         CDEBUG(D_HA, "marking %s %s->%s as inactive\n",
152                                name, obddev->obd_name,
153                                imp->imp_target_uuid.uuid);
154                         imp->imp_invalid = 1;
155
156                         if (lcfg->lcfg_inllen4 != 0)
157                                 mgmt_name = lcfg->lcfg_inlbuf4;
158                 } else {
159                         mgmt_name = lcfg->lcfg_inlbuf3;
160                 }
161         }
162
163         if (mgmt_name != NULL) {
164                 /* Register with management client if we need to. */
165                 CDEBUG(D_HA, "%s registering with %s for events about %s\n",
166                        obddev->obd_name, mgmt_name, server_uuid.uuid);
167
168                 mgmt_obd = class_name2obd(mgmt_name);
169                 if (!mgmt_obd) {
170                         CERROR("can't find mgmtcli %s to register\n",
171                                mgmt_name);
172                         GOTO(err_import, rc = -ENOSYS);
173                 }
174
175                 register_f = inter_module_get("mgmtcli_register_for_events");
176                 if (!register_f) {
177                         CERROR("can't i_m_g mgmtcli_register_for_events\n");
178                         GOTO(err_import, rc = -ENOSYS);
179                 }
180
181                 rc = register_f(mgmt_obd, obddev, &imp->imp_target_uuid);
182                 inter_module_put("mgmtcli_register_for_events");
183
184                 if (!rc)
185                         cli->cl_mgmtcli_obd = mgmt_obd;
186         }
187
188         RETURN(rc);
189
190 err_import:
191         class_destroy_import(imp);
192 err_ldlm:
193         ldlm_put_ref(0);
194 err:
195         RETURN(rc);
196
197 }
198
199 int client_obd_cleanup(struct obd_device *obddev, int flags)
200 {
201         struct client_obd *cli = &obddev->u.cli;
202
203         if (!cli->cl_import)
204                 RETURN(-EINVAL);
205         if (cli->cl_mgmtcli_obd) {
206                 mgmtcli_deregister_for_events_t dereg_f;
207
208                 dereg_f = inter_module_get("mgmtcli_deregister_for_events");
209                 dereg_f(cli->cl_mgmtcli_obd, obddev);
210                 inter_module_put("mgmtcli_deregister_for_events");
211         }
212         class_destroy_import(cli->cl_import);
213         cli->cl_import = NULL;
214
215         ldlm_put_ref(flags & OBD_OPT_FORCE);
216
217         RETURN(0);
218 }
219
220 int client_connect_import(struct lustre_handle *dlm_handle,
221                           struct obd_device *obd,
222                           struct obd_uuid *cluuid)
223 {
224         struct client_obd *cli = &obd->u.cli;
225         struct obd_import *imp = cli->cl_import;
226         struct obd_export *exp;
227         int rc;
228         ENTRY;
229
230         down(&cli->cl_sem);
231         rc = class_connect(dlm_handle, obd, cluuid);
232         if (rc)
233                 GOTO(out_sem, rc);
234
235         cli->cl_conn_count++;
236         if (cli->cl_conn_count > 1)
237                 GOTO(out_sem, rc);
238         exp = class_conn2export(dlm_handle);
239
240         if (obd->obd_namespace != NULL)
241                 CERROR("already have namespace!\n");
242         obd->obd_namespace = ldlm_namespace_new(obd->obd_name,
243                                                 LDLM_NAMESPACE_CLIENT);
244         if (obd->obd_namespace == NULL)
245                 GOTO(out_disco, rc = -ENOMEM);
246
247         imp->imp_dlm_handle = *dlm_handle;
248         rc = ptlrpc_init_import(imp);
249         if (rc != 0) 
250                 GOTO(out_ldlm, rc);
251
252         exp->exp_connection = ptlrpc_connection_addref(imp->imp_connection);
253         rc = ptlrpc_connect_import(imp, NULL);
254         if (rc != 0) {
255                 LASSERT (imp->imp_state == LUSTRE_IMP_DISCON);
256                 GOTO(out_ldlm, rc);
257         }
258
259         ptlrpc_pinger_add_import(imp);
260         EXIT;
261
262         if (rc) {
263 out_ldlm:
264                 ldlm_namespace_free(obd->obd_namespace, 0);
265                 obd->obd_namespace = NULL;
266 out_disco:
267                 cli->cl_conn_count--;
268                 class_disconnect(exp, 0);
269         } else {
270                 class_export_put(exp);
271         }
272 out_sem:
273         up(&cli->cl_sem);
274         return rc;
275 }
276
277 int client_disconnect_export(struct obd_export *exp, int failover)
278 {
279         struct obd_device *obd = class_exp2obd(exp);
280         struct client_obd *cli = &obd->u.cli;
281         struct obd_import *imp = cli->cl_import;
282         int rc = 0, err;
283         ENTRY;
284
285         if (!obd) {
286                 CERROR("invalid export for disconnect: exp %p cookie "LPX64"\n",
287                        exp, exp ? exp->exp_handle.h_cookie : -1);
288                 RETURN(-EINVAL);
289         }
290
291         down(&cli->cl_sem);
292         if (!cli->cl_conn_count) {
293                 CERROR("disconnecting disconnected device (%s)\n",
294                        obd->obd_name);
295                 GOTO(out_sem, rc = -EINVAL);
296         }
297
298         cli->cl_conn_count--;
299         if (cli->cl_conn_count)
300                 GOTO(out_no_disconnect, rc = 0);
301
302         /* Some non-replayable imports (MDS's OSCs) are pinged, so just
303          * delete it regardless.  (It's safe to delete an import that was
304          * never added.) */
305         (void)ptlrpc_pinger_del_import(imp);
306
307         if (obd->obd_namespace != NULL) {
308                 /* obd_no_recov == local only */
309                 ldlm_cli_cancel_unused(obd->obd_namespace, NULL,
310                                        obd->obd_no_recov, NULL);
311                 ldlm_namespace_free(obd->obd_namespace, obd->obd_no_recov);
312                 obd->obd_namespace = NULL;
313         }
314
315         /* Yeah, obd_no_recov also (mainly) means "forced shutdown". */
316         if (obd->obd_no_recov)
317                 ptlrpc_invalidate_import(imp, 0);
318         else
319                 rc = ptlrpc_disconnect_import(imp);
320
321         EXIT;
322  out_no_disconnect:
323         err = class_disconnect(exp, 0);
324         if (!rc && err)
325                 rc = err;
326  out_sem:
327         up(&cli->cl_sem);
328         RETURN(rc);
329 }
330
331 /* --------------------------------------------------------------------------
332  * from old lib/target.c
333  * -------------------------------------------------------------------------- */
334
335 int target_handle_reconnect(struct lustre_handle *conn, struct obd_export *exp,
336                             struct obd_uuid *cluuid, int initial_conn)
337 {
338         if (exp->exp_connection && !initial_conn) {
339                 struct lustre_handle *hdl;
340                 hdl = &exp->exp_imp_reverse->imp_remote_handle;
341                 /* Might be a re-connect after a partition. */
342                 if (!memcmp(&conn->cookie, &hdl->cookie, sizeof conn->cookie)) {
343                         CERROR("%s reconnecting\n", cluuid->uuid);
344                         conn->cookie = exp->exp_handle.h_cookie;
345                         RETURN(EALREADY);
346                 } else {
347                         CERROR("%s reconnecting from %s, "
348                                "handle mismatch (ours "LPX64", theirs "
349                                LPX64")\n", cluuid->uuid,
350                                exp->exp_connection->c_remote_uuid.uuid,
351                                hdl->cookie, conn->cookie);
352                         memset(conn, 0, sizeof *conn);
353                         RETURN(-EALREADY);
354                 }
355         }
356
357         conn->cookie = exp->exp_handle.h_cookie;
358         CDEBUG(D_INFO, "existing export for UUID '%s' at %p\n",
359                cluuid->uuid, exp);
360         CDEBUG(D_IOCTL,"connect: cookie "LPX64"\n", conn->cookie);
361         RETURN(0);
362 }
363
364 int target_handle_connect(struct ptlrpc_request *req)
365 {
366         struct obd_device *target;
367         struct obd_export *export = NULL;
368         struct obd_import *revimp;
369         struct lustre_handle conn;
370         struct obd_uuid tgtuuid;
371         struct obd_uuid cluuid;
372         struct obd_uuid remote_uuid;
373         struct list_head *p;
374         char *str, *tmp;
375         int rc = 0;
376         unsigned long flags;
377         int initial_conn = 0;
378         char peer_str[PTL_NALFMT_SIZE];
379         ENTRY;
380
381         OBD_RACE(OBD_FAIL_TGT_CONN_RACE); 
382
383         LASSERT_REQSWAB (req, 0);
384         str = lustre_msg_string(req->rq_reqmsg, 0, sizeof(tgtuuid) - 1);
385         if (str == NULL) {
386                 CERROR("bad target UUID for connect\n");
387                 GOTO(out, rc = -EINVAL);
388         }
389
390         obd_str2uuid (&tgtuuid, str);
391         target = class_uuid2obd(&tgtuuid);
392         if (!target) {
393                 target = class_name2obd(str);
394         }
395         
396         if (!target || target->obd_stopping || !target->obd_set_up) {
397                 CERROR("UUID '%s' is not available for connect\n", str);
398
399                 GOTO(out, rc = -ENODEV);
400         }
401
402         LASSERT_REQSWAB (req, 1);
403         str = lustre_msg_string(req->rq_reqmsg, 1, sizeof(cluuid) - 1);
404         if (str == NULL) {
405                 CERROR("bad client UUID for connect\n");
406                 GOTO(out, rc = -EINVAL);
407         }
408
409         obd_str2uuid (&cluuid, str);
410
411         /* XXX extract a nettype and format accordingly */
412         switch (sizeof(ptl_nid_t)) {
413                 /* NB the casts only avoid compiler warnings */
414         case 8:
415                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
416                          "NET_"LPX64"_UUID", (__u64)req->rq_peer.peer_nid);
417                 break;
418         case 4:
419                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
420                          "NET_%x_UUID", (__u32)req->rq_peer.peer_nid);
421                 break;
422         default:
423                 LBUG();
424         }
425
426         tmp = lustre_msg_buf(req->rq_reqmsg, 2, sizeof conn);
427         if (tmp == NULL)
428                 GOTO(out, rc = -EPROTO);
429
430         memcpy(&conn, tmp, sizeof conn);
431
432         rc = lustre_pack_reply(req, 0, NULL, NULL);
433         if (rc)
434                 GOTO(out, rc);
435         
436         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_INITIAL)
437                 initial_conn = 1;
438         
439         /* lctl gets a backstage, all-access pass. */
440         if (obd_uuid_equals(&cluuid, &target->obd_uuid))
441                 goto dont_check_exports;
442
443         spin_lock(&target->obd_dev_lock);
444         list_for_each(p, &target->obd_exports) {
445                 export = list_entry(p, struct obd_export, exp_obd_chain);
446                 if (obd_uuid_equals(&cluuid, &export->exp_client_uuid)) {
447                         spin_unlock(&target->obd_dev_lock);
448                         LASSERT(export->exp_obd == target);
449
450                         rc = target_handle_reconnect(&conn, export, &cluuid,
451                                                      initial_conn);
452                         break;
453                 }
454                 export = NULL;
455         }
456         /* If we found an export, we already unlocked. */
457         if (!export) {
458                 spin_unlock(&target->obd_dev_lock);
459         } else if (req->rq_export == NULL && 
460                    atomic_read(&export->exp_rpc_count) > 0) {
461                 CWARN("%s: refuse connection from %s/%s to 0x%p/%d\n",
462                       target->obd_name, cluuid.uuid,
463                       ptlrpc_peernid2str(&req->rq_peer, peer_str),
464                       export, atomic_read(&export->exp_refcount));
465                 GOTO(out, rc = -EBUSY);
466         } else if (req->rq_export != NULL &&
467                    atomic_read(&export->exp_rpc_count) > 1) {
468                 CWARN("%s: refuse reconnection from %s@%s to 0x%p/%d\n",
469                       target->obd_name, cluuid.uuid,
470                       ptlrpc_peernid2str(&req->rq_peer, peer_str),
471                       export, atomic_read(&export->exp_rpc_count));
472                 GOTO(out, rc = -EBUSY);
473         }
474         else if (req->rq_reqmsg->conn_cnt == 1 && !initial_conn) {
475                 CERROR("%s reconnected with 1 conn_cnt; cookies not random?\n",
476                        cluuid.uuid);
477                 GOTO(out, rc = -EALREADY);
478         }
479
480         /* Tell the client if we're in recovery. */
481         /* If this is the first client, start the recovery timer */
482         CWARN("%s: connection from %s@%s %s\n", target->obd_name, cluuid.uuid,
483               ptlrpc_peernid2str(&req->rq_peer, peer_str),
484               target->obd_recovering ? "(recovering)" : "");
485         if (target->obd_recovering) {
486                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
487                 target_start_recovery_timer(target);
488         }
489 #if 0
490         /* Tell the client if we support replayable requests */
491         if (target->obd_replayable)
492                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
493 #endif
494         if (export == NULL) {
495                 if (target->obd_recovering) {
496                         CERROR("denying connection for new client %s@%s: "
497                                "%d clients in recovery for %lds\n", cluuid.uuid,
498                                ptlrpc_peernid2str(&req->rq_peer, peer_str),
499                                target->obd_recoverable_clients,
500                                (target->obd_recovery_timer.expires-jiffies)/HZ);
501                         rc = -EBUSY;
502                 } else {
503  dont_check_exports:
504                         rc = obd_connect(&conn, target, &cluuid);
505                 }
506         }
507         /* Tell the client if we support replayable requests */
508         if (target->obd_replayable)
509                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
510
511         /* If all else goes well, this is our RPC return code. */
512         req->rq_status = 0;
513
514         if (rc && rc != EALREADY)
515                 GOTO(out, rc);
516
517         req->rq_repmsg->handle = conn;
518
519         /* If the client and the server are the same node, we will already
520          * have an export that really points to the client's DLM export,
521          * because we have a shared handles table.
522          *
523          * XXX this will go away when shaver stops sending the "connect" handle
524          * in the real "remote handle" field of the request --phik 24 Apr 2003
525          */
526         if (req->rq_export != NULL)
527                 class_export_put(req->rq_export);
528
529         /* ownership of this export ref transfers to the request */
530         export = req->rq_export = class_conn2export(&conn);
531         LASSERT(export != NULL);
532
533         spin_lock_irqsave(&export->exp_lock, flags);
534         if (initial_conn) {
535                 req->rq_repmsg->conn_cnt = export->exp_conn_cnt + 1;
536         } else if (export->exp_conn_cnt >= req->rq_reqmsg->conn_cnt) {
537                 CERROR("%s@%s: already connected at a higher conn_cnt: %d > %d\n",
538                        cluuid.uuid, ptlrpc_peernid2str(&req->rq_peer, peer_str),
539                        export->exp_conn_cnt, 
540                        req->rq_reqmsg->conn_cnt);
541                 spin_unlock_irqrestore(&export->exp_lock, flags);
542                 GOTO(out, rc = -EALREADY);
543         } 
544         export->exp_conn_cnt = req->rq_reqmsg->conn_cnt;
545         spin_unlock_irqrestore(&export->exp_lock, flags);
546
547         /* request from liblustre? */
548         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT)
549                 export->exp_libclient = 1;
550
551         if (export->exp_connection != NULL)
552                 ptlrpc_put_connection(export->exp_connection);
553         export->exp_connection = ptlrpc_get_connection(&req->rq_peer,
554                                                        &remote_uuid);
555
556         if (rc == EALREADY) {
557                 /* We indicate the reconnection in a flag, not an error code. */
558                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECONNECT);
559                 GOTO(out, rc = 0);
560         }
561
562         if (target->obd_recovering) {
563                 target->obd_connected_clients++;
564         }
565
566         memcpy(&conn, lustre_msg_buf(req->rq_reqmsg, 2, sizeof conn),
567                sizeof conn);
568
569         if (export->exp_imp_reverse != NULL)
570                 class_destroy_import(export->exp_imp_reverse);
571         revimp = export->exp_imp_reverse = class_new_import();
572         revimp->imp_connection = ptlrpc_connection_addref(export->exp_connection);
573         revimp->imp_client = &export->exp_obd->obd_ldlm_client;
574         revimp->imp_remote_handle = conn;
575         revimp->imp_obd = target;
576         revimp->imp_dlm_fake = 1;
577         revimp->imp_state = LUSTRE_IMP_FULL;
578         class_import_put(revimp);
579 out:
580         if (rc)
581                 req->rq_status = rc;
582         RETURN(rc);
583 }
584
585 int target_handle_disconnect(struct ptlrpc_request *req)
586 {
587         struct obd_export *exp;
588         int rc;
589         ENTRY;
590
591         rc = lustre_pack_reply(req, 0, NULL, NULL);
592         if (rc)
593                 RETURN(rc);
594
595         /* keep the rq_export around so we can send the reply */
596         exp = class_export_get(req->rq_export);
597         req->rq_status = obd_disconnect(exp, 0);
598         RETURN(0);
599 }
600
601 void target_destroy_export(struct obd_export *exp)
602 {
603         /* exports created from last_rcvd data, and "fake"
604            exports created by lctl don't have an import */
605         if (exp->exp_imp_reverse != NULL)
606                 class_destroy_import(exp->exp_imp_reverse);
607
608         /* We cancel locks at disconnect time, but this will catch any locks
609          * granted in a race with recovery-induced disconnect. */
610         if (exp->exp_obd->obd_namespace != NULL)
611                 ldlm_cancel_locks_for_export(exp);
612 }
613
614 /*
615  * Recovery functions
616  */
617
618 struct ptlrpc_request *
619 ptlrpc_clone_req( struct ptlrpc_request *orig_req) 
620 {
621         struct ptlrpc_request *copy_req;
622         struct lustre_msg *copy_reqmsg;
623
624         OBD_ALLOC(copy_req, sizeof *copy_req);
625         if (!copy_req)
626                 return NULL;
627         OBD_ALLOC(copy_reqmsg, orig_req->rq_reqlen);
628         if (!copy_reqmsg){
629                 OBD_FREE(copy_req, sizeof *copy_req);
630                 return NULL;
631         }
632
633         memcpy(copy_req, orig_req, sizeof *copy_req);
634         memcpy(copy_reqmsg, orig_req->rq_reqmsg, orig_req->rq_reqlen);
635         /* the copied req takes over the reply state */
636         orig_req->rq_reply_state = NULL;
637
638         copy_req->rq_reqmsg = copy_reqmsg;
639         class_export_get(copy_req->rq_export);
640         INIT_LIST_HEAD(&copy_req->rq_list);
641
642         return copy_req;
643 }
644 void ptlrpc_free_clone( struct ptlrpc_request *req) 
645 {
646         class_export_put(req->rq_export);
647         list_del(&req->rq_list);
648         OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
649         OBD_FREE(req, sizeof *req);
650 }
651
652 static void abort_delayed_replies(struct obd_device *obd)
653 {
654         struct ptlrpc_request *req;
655         struct list_head *tmp, *n;
656         list_for_each_safe(tmp, n, &obd->obd_delayed_reply_queue) {
657                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
658                 DEBUG_REQ(D_ERROR, req, "aborted:");
659                 req->rq_status = -ENOTCONN;
660                 req->rq_type = PTL_RPC_MSG_ERR;
661                 ptlrpc_reply(req);
662                 class_export_put(req->rq_export);
663                 list_del(&req->rq_list);
664                 OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
665                 OBD_FREE(req, sizeof *req);
666         }
667 }
668
669 static void abort_recovery_queue(struct obd_device *obd)
670 {
671         struct ptlrpc_request *req;
672         struct list_head *tmp, *n;
673         int rc;
674
675         list_for_each_safe(tmp, n, &obd->obd_recovery_queue) {
676                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
677                 DEBUG_REQ(D_ERROR, req, "aborted:");
678                 req->rq_status = -ENOTCONN;
679                 req->rq_type = PTL_RPC_MSG_ERR;
680                 rc = lustre_pack_reply(req, 0, NULL, NULL);
681                 if (rc == 0) {
682                         ptlrpc_reply(req);
683                 } else {
684                         DEBUG_REQ(D_ERROR, req,
685                                   "packing failed for abort-reply; skipping");
686                 }
687                 list_del(&req->rq_list);
688                 class_export_put(req->rq_export);
689                 OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
690                 OBD_FREE(req, sizeof *req);
691         }
692 }
693
694 static void target_abort_recovery(void *data)
695 {
696         struct obd_device *obd = data;
697         int rc;
698
699         CERROR("disconnecting clients and aborting recovery\n");
700         LASSERT(!obd->obd_recovering);
701
702         class_disconnect_exports(obd, 0);
703
704         /* when recovery was aborted, cleanup orphans on mds and ost */
705         if (OBT(obd) && OBP(obd, postrecov)) {
706                 rc = OBP(obd, postrecov)(obd);
707                 if (rc >= 0)
708                         CWARN("Cleanup %d orphans after recovery was aborted\n",
709                               rc);
710                 else
711                         CERROR("postrecov failed %d\n", rc);
712         }
713
714         abort_delayed_replies(obd);
715         abort_recovery_queue(obd);
716         ptlrpc_run_recovery_over_upcall(obd);
717 }
718
719 static void target_recovery_expired(unsigned long castmeharder)
720 {
721         struct obd_device *obd = (struct obd_device *)castmeharder;
722         CERROR("recovery timed out, aborting\n");
723         spin_lock_bh(&obd->obd_processing_task_lock);
724         obd->obd_abort_recovery = 1;
725         wake_up(&obd->obd_next_transno_waitq);
726         spin_unlock_bh(&obd->obd_processing_task_lock);
727 }
728
729
730 /* obd_processing_task_lock should be held */
731 void target_cancel_recovery_timer(struct obd_device *obd)
732 {
733         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
734         del_timer(&obd->obd_recovery_timer);
735 }
736
737 static void reset_recovery_timer(struct obd_device *obd)
738 {
739         spin_lock_bh(&obd->obd_processing_task_lock);
740         if (!obd->obd_recovering) {
741                 spin_unlock_bh(&obd->obd_processing_task_lock);
742                 return;
743         }                
744         CDEBUG(D_HA, "timer will expire in %u seconds\n",
745                OBD_RECOVERY_TIMEOUT / HZ);
746         mod_timer(&obd->obd_recovery_timer, jiffies + OBD_RECOVERY_TIMEOUT);
747         spin_unlock_bh(&obd->obd_processing_task_lock);
748 }
749
750
751 /* Only start it the first time called */
752 void target_start_recovery_timer(struct obd_device *obd)
753 {
754         spin_lock_bh(&obd->obd_processing_task_lock);
755         if (!obd->obd_recovering || timer_pending(&obd->obd_recovery_timer)) {
756                 spin_unlock_bh(&obd->obd_processing_task_lock);
757                 return;
758         }
759         CWARN("%s: starting recovery timer (%us)\n", obd->obd_name,
760                OBD_RECOVERY_TIMEOUT / HZ);
761         obd->obd_recovery_timer.function = target_recovery_expired;
762         obd->obd_recovery_timer.data = (unsigned long)obd;
763         mod_timer(&obd->obd_recovery_timer, jiffies + OBD_RECOVERY_TIMEOUT);
764         spin_unlock_bh(&obd->obd_processing_task_lock);
765 }
766
767 static void target_finish_recovery(struct obd_device *obd)
768 {
769         struct list_head *tmp, *n;
770         int rc2;
771
772         ldlm_reprocess_all_ns(obd->obd_namespace);
773
774         CWARN("%s: all clients recovered, calling postrecov\n",
775               obd->obd_name);
776         /* when recovery finished, cleanup orphans on mds and ost */
777         if (OBT(obd) && OBP(obd, postrecov)) {
778                 rc2 = OBP(obd, postrecov)(obd);
779                 if (rc2 >= 0)
780                         CWARN("%s: all clients recovered, %d MDS "
781                               "orphans deleted\n", obd->obd_name, rc2);
782                 else
783                         CERROR("postrecov failed %d\n", rc2);
784         }
785
786         CWARN("%s: recovery over, sending delayed replies\n",
787               obd->obd_name);
788         list_for_each_safe(tmp, n, &obd->obd_delayed_reply_queue) {
789                 struct ptlrpc_request *req;
790                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
791                 DEBUG_REQ(D_ERROR, req, "delayed:");
792                 ptlrpc_reply(req);
793                 ptlrpc_free_clone(req);
794         }
795         ptlrpc_run_recovery_over_upcall(obd);
796 }
797
798 static int check_for_next_transno(struct obd_device *obd)
799 {
800         struct ptlrpc_request *req;
801         int wake_up = 0, connected, completed, queue_len, max;
802         __u64 next_transno, req_transno;
803
804         spin_lock_bh(&obd->obd_processing_task_lock);
805         if (!list_empty(&obd->obd_recovery_queue)) {
806                 req = list_entry(obd->obd_recovery_queue.next,
807                                  struct ptlrpc_request, rq_list);
808                 req_transno = req->rq_reqmsg->transno;
809         } else {
810                 req_transno = 0;
811         }
812
813         max = obd->obd_max_recoverable_clients;
814         connected = obd->obd_connected_clients;
815         completed = max - obd->obd_recoverable_clients;
816         queue_len = obd->obd_requests_queued_for_recovery;
817         next_transno = obd->obd_next_recovery_transno;
818
819         CDEBUG(D_HA,"max: %d, connected: %d, completed: %d, queue_len: %d, "
820                "req_transno: "LPU64", next_transno: "LPU64"\n",
821                max, connected, completed, queue_len, req_transno, next_transno);
822         if (obd->obd_abort_recovery) {
823                 CDEBUG(D_HA, "waking for aborted recovery\n");
824                 wake_up = 1;
825         } else if (max == completed) {
826                 CDEBUG(D_HA, "waking for completed recovery\n");
827                 wake_up = 1;
828         } else if (req_transno == next_transno) {
829                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
830                 wake_up = 1;
831         } else if (queue_len + completed == max) {
832                 LASSERT(req->rq_reqmsg->transno >= next_transno);
833                 CDEBUG(D_ERROR,
834                        "waking for skipped transno (skip: "LPD64
835                        ", ql: %d, comp: %d, conn: %d, next: "LPD64")\n",
836                        next_transno, queue_len, completed, max, req_transno);
837                 obd->obd_next_recovery_transno = req_transno;
838                 wake_up = 1;
839         }
840         spin_unlock_bh(&obd->obd_processing_task_lock);
841         
842         return wake_up;
843 }
844
845 static struct ptlrpc_request *
846 target_next_replay_req(struct obd_device *obd)
847 {
848         struct l_wait_info lwi = { 0 };
849         struct ptlrpc_request *req;
850
851         CDEBUG(D_HA, "Waiting for transno "LPD64"\n",
852                obd->obd_next_recovery_transno);
853         l_wait_event(obd->obd_next_transno_waitq,
854                      check_for_next_transno(obd), &lwi);
855         
856         spin_lock_bh(&obd->obd_processing_task_lock);
857         if (obd->obd_abort_recovery) {
858                 req = NULL;
859         } else if (!list_empty(&obd->obd_recovery_queue)) {
860                 req = list_entry(obd->obd_recovery_queue.next,
861                                  struct ptlrpc_request, rq_list);
862                 list_del_init(&req->rq_list);
863                 obd->obd_requests_queued_for_recovery--;
864         } else {
865                 req = NULL;
866         }
867         spin_unlock_bh(&obd->obd_processing_task_lock);
868         return req;
869 }
870
871
872 static int target_recovery_thread(void *arg)
873 {
874         struct obd_device *obd = arg;
875         struct ptlrpc_request *req;
876         struct target_recovery_data *trd = &obd->obd_recovery_data;
877         unsigned long flags;
878         ENTRY;
879
880         kportal_daemonize("tgt-recov");
881
882         SIGNAL_MASK_LOCK(current, flags);
883         sigfillset(&current->blocked);
884         RECALC_SIGPENDING;
885         SIGNAL_MASK_UNLOCK(current, flags);
886
887         CERROR("%s: started recovery thread pid %d\n", obd->obd_name, 
888                current->pid);
889         trd->trd_processing_task = current->pid;
890
891         obd->obd_recovering = 1;
892         complete(&trd->trd_starting);
893
894         while (obd->obd_recovering) {
895                 LASSERT(trd->trd_processing_task == current->pid);
896                 req = target_next_replay_req(obd);
897                 if (req != NULL) {
898                         char peer_str[PTL_NALFMT_SIZE];
899                         DEBUG_REQ(D_HA, req, "processing t"LPD64" from %s: ", 
900                                   req->rq_reqmsg->transno, 
901                                   ptlrpc_peernid2str(&req->rq_peer, peer_str));
902                         (void)trd->trd_recovery_handler(req);
903                         obd->obd_replayed_requests++;
904                         reset_recovery_timer(obd);
905                         /* bug 1580: decide how to properly sync() in recovery*/
906                         //mds_fsync_super(mds->mds_sb);
907                         ptlrpc_free_clone(req);
908                         spin_lock_bh(&obd->obd_processing_task_lock);
909                         obd->obd_next_recovery_transno++;
910                         spin_unlock_bh(&obd->obd_processing_task_lock);
911                 } else {
912                         /* recovery is over */
913                         spin_lock_bh(&obd->obd_processing_task_lock);
914                         obd->obd_recovering = 0;
915                         target_cancel_recovery_timer(obd);
916                         if (obd->obd_abort_recovery) {
917                                 obd->obd_abort_recovery = 0;
918                                 spin_unlock_bh(&obd->obd_processing_task_lock);
919                                 target_abort_recovery(obd); 
920                         } else {
921                                 LASSERT(obd->obd_recoverable_clients == 0);
922                                 spin_unlock_bh(&obd->obd_processing_task_lock);
923                                 target_finish_recovery(obd);
924                         }
925                 }
926         }
927
928         trd->trd_processing_task = 0;
929         complete(&trd->trd_finishing);
930         return 0;
931 }
932
933 int target_start_recovery_thread(struct obd_device *obd, svc_handler_t handler)
934 {
935         int rc = 0;
936         struct target_recovery_data *trd = &obd->obd_recovery_data;
937
938         memset(trd, 0, sizeof(*trd));
939         init_completion(&trd->trd_starting);
940         init_completion(&trd->trd_finishing);
941         trd->trd_recovery_handler = handler;
942
943         if (kernel_thread(target_recovery_thread, obd, 0) == 0) 
944                 wait_for_completion(&trd->trd_starting);
945         else
946                 rc = -ECHILD;
947
948         return rc;
949 }
950
951 void target_stop_recovery_thread(struct obd_device *obd)
952 {
953         spin_lock_bh(&obd->obd_processing_task_lock);
954         if (obd->obd_recovery_data.trd_processing_task > 0) {
955                 struct target_recovery_data *trd = &obd->obd_recovery_data;
956                 CERROR("%s: aborting recovery\n", obd->obd_name);
957                 obd->obd_abort_recovery = 1;
958                 wake_up(&obd->obd_next_transno_waitq);
959                 spin_unlock_bh(&obd->obd_processing_task_lock);
960                 wait_for_completion(&trd->trd_finishing);
961         } else {
962                 spin_unlock_bh(&obd->obd_processing_task_lock);
963         }
964 }
965
966 int target_queue_recovery_request(struct ptlrpc_request *req,
967                                   struct obd_device *obd)
968 {
969         struct list_head *tmp;
970         int inserted = 0;
971         __u64 transno = req->rq_reqmsg->transno;
972
973         /* CAVEAT EMPTOR: The incoming request message has been swabbed
974          * (i.e. buflens etc are in my own byte order), but type-dependent
975          * buffers (eg mds_body, ost_body etc) have NOT been swabbed. */
976
977         if (!transno) {
978                 INIT_LIST_HEAD(&req->rq_list);
979                 DEBUG_REQ(D_HA, req, "not queueing");
980                 return 1;
981         }
982
983
984         /* If we're processing the queue, we want don't want to queue this
985          * message.
986          *
987          * Also, if this request has a transno less than the one we're waiting
988          * for, we should process it now.  It could (and currently always will)
989          * be an open request for a descriptor that was opened some time ago.
990          *
991          * Also, a resent, replayed request that has already been
992          * handled will pass through here and be processed immediately.
993          */
994         spin_lock_bh(&obd->obd_processing_task_lock);
995         if (obd->obd_recovery_data.trd_processing_task == current->pid ||
996             transno < obd->obd_next_recovery_transno) {
997                 /* Processing the queue right now, don't re-add. */
998                 lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
999                 LASSERT(list_empty(&req->rq_list));
1000                 spin_unlock_bh(&obd->obd_processing_task_lock);
1001                 return 1;
1002         }
1003         spin_unlock_bh(&obd->obd_processing_task_lock);
1004
1005         /* A resent, replayed request that is still on the queue; just drop it.
1006            The queued request will handle this. */
1007         if ((lustre_msg_get_flags(req->rq_reqmsg) & (MSG_RESENT | MSG_REPLAY))
1008             == (MSG_RESENT | MSG_REPLAY)) {
1009                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
1010                 return 0;
1011         }
1012
1013         req = ptlrpc_clone_req(req);
1014         if (req == NULL)
1015                 return -ENOMEM;
1016
1017         spin_lock_bh(&obd->obd_processing_task_lock);
1018
1019         /* XXX O(n^2) */
1020         list_for_each(tmp, &obd->obd_recovery_queue) {
1021                 struct ptlrpc_request *reqiter =
1022                         list_entry(tmp, struct ptlrpc_request, rq_list);
1023
1024                 if (reqiter->rq_reqmsg->transno > transno) {
1025                         list_add_tail(&req->rq_list, &reqiter->rq_list);
1026                         inserted = 1;
1027                         break;
1028                 }
1029         }
1030
1031         if (!inserted) {
1032                 list_add_tail(&req->rq_list, &obd->obd_recovery_queue);
1033         }
1034
1035         obd->obd_requests_queued_for_recovery++;
1036         wake_up(&obd->obd_next_transno_waitq);
1037         spin_unlock_bh(&obd->obd_processing_task_lock);
1038
1039         return 0;
1040 }
1041
1042 struct obd_device * target_req2obd(struct ptlrpc_request *req)
1043 {
1044         return req->rq_export->exp_obd;
1045 }
1046
1047 int target_queue_final_reply(struct ptlrpc_request *req, int rc)
1048 {
1049         struct obd_device *obd = target_req2obd(req);
1050
1051         LASSERT ((rc == 0) == (req->rq_reply_state != NULL));
1052
1053         if (rc) {
1054                 /* Just like ptlrpc_error, but without the sending. */
1055                 rc = lustre_pack_reply(req, 0, NULL, NULL);
1056                 LASSERT(rc == 0); /* XXX handle this */
1057                 req->rq_type = PTL_RPC_MSG_ERR;
1058         }
1059
1060         LASSERT (!req->rq_reply_state->rs_difficult);
1061         LASSERT(list_empty(&req->rq_list));
1062         
1063         req = ptlrpc_clone_req(req);
1064
1065         spin_lock_bh(&obd->obd_processing_task_lock);
1066
1067         list_add(&req->rq_list, &obd->obd_delayed_reply_queue);
1068
1069         /* only count the first "replay over" request from each
1070            export */
1071         if (req->rq_export->exp_replay_needed) {
1072                 --obd->obd_recoverable_clients;
1073                 req->rq_export->exp_replay_needed = 0;
1074                 CWARN("%s: %d recoverable clients remain\n",
1075                       obd->obd_name, obd->obd_recoverable_clients);
1076         }
1077         wake_up(&obd->obd_next_transno_waitq);
1078         spin_unlock_bh(&obd->obd_processing_task_lock);
1079         return 1;
1080 }
1081
1082 int
1083 target_send_reply_msg (struct ptlrpc_request *req, int rc, int fail_id)
1084 {
1085         if (OBD_FAIL_CHECK(fail_id | OBD_FAIL_ONCE)) {
1086                 obd_fail_loc |= OBD_FAIL_ONCE | OBD_FAILED;
1087                 DEBUG_REQ(D_ERROR, req, "dropping reply");
1088                 /* NB this does _not_ send with ACK disabled, to simulate
1089                  * sending OK, but timing out for the ACK */
1090                 if (req->rq_reply_state != NULL) {
1091                         if (!req->rq_reply_state->rs_difficult) {
1092                                 lustre_free_reply_state (req->rq_reply_state);
1093                                 req->rq_reply_state = NULL;
1094                         } else {
1095                                 struct ptlrpc_service *svc =
1096                                         req->rq_rqbd->rqbd_srv_ni->sni_service;
1097                                 atomic_inc(&svc->srv_outstanding_replies);
1098                         }
1099                 }
1100                 return (-ECOMM);
1101         }
1102
1103         if (rc) {
1104                 DEBUG_REQ(D_ERROR, req, "processing error (%d)", rc);
1105                 if (req->rq_reply_state == NULL) {
1106                         rc = lustre_pack_reply (req, 0, NULL, NULL);
1107                         if (rc != 0) {
1108                                 CERROR ("can't allocate reply\n");
1109                                 return (rc);
1110                         }
1111                 }
1112                 req->rq_type = PTL_RPC_MSG_ERR;
1113         } else {
1114                 DEBUG_REQ(D_NET, req, "sending reply");
1115         }
1116         
1117         return (ptlrpc_send_reply(req, 1));
1118 }
1119
1120 void 
1121 target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
1122 {
1123         int                        netrc;
1124         unsigned long              flags;
1125         struct ptlrpc_reply_state *rs;
1126         struct obd_device         *obd;
1127         struct obd_export         *exp;
1128         struct ptlrpc_srv_ni      *sni;
1129         struct ptlrpc_service     *svc;
1130
1131         sni = req->rq_rqbd->rqbd_srv_ni;
1132         svc = sni->sni_service;
1133         
1134         rs = req->rq_reply_state;
1135         if (rs == NULL || !rs->rs_difficult) {
1136                 /* The easy case; no notifiers and reply_out_callback()
1137                  * cleans up (i.e. we can't look inside rs after a
1138                  * successful send) */
1139                 netrc = target_send_reply_msg (req, rc, fail_id);
1140
1141                 LASSERT (netrc == 0 || req->rq_reply_state == NULL);
1142                 return;
1143         }
1144
1145         /* must be an export if locks saved */
1146         LASSERT (req->rq_export != NULL);
1147         /* req/reply consistent */
1148         LASSERT (rs->rs_srv_ni == sni);
1149
1150         /* "fresh" reply */
1151         LASSERT (!rs->rs_scheduled);
1152         LASSERT (!rs->rs_scheduled_ever);
1153         LASSERT (!rs->rs_handled);
1154         LASSERT (!rs->rs_on_net);
1155         LASSERT (rs->rs_export == NULL);
1156         LASSERT (list_empty(&rs->rs_obd_list));
1157         LASSERT (list_empty(&rs->rs_exp_list));
1158
1159         exp = class_export_get (req->rq_export);
1160         obd = exp->exp_obd;
1161
1162         /* disable reply scheduling onto srv_reply_queue while I'm setting up */
1163         rs->rs_scheduled = 1;
1164         rs->rs_on_net    = 1;
1165         rs->rs_xid       = req->rq_xid;
1166         rs->rs_transno   = req->rq_transno;
1167         rs->rs_export    = exp;
1168         
1169         spin_lock_irqsave (&obd->obd_uncommitted_replies_lock, flags);
1170
1171         if (rs->rs_transno > obd->obd_last_committed) {
1172                 /* not committed already */ 
1173                 list_add_tail (&rs->rs_obd_list, 
1174                                &obd->obd_uncommitted_replies);
1175         }
1176
1177         spin_unlock (&obd->obd_uncommitted_replies_lock);
1178         spin_lock (&exp->exp_lock);
1179
1180         list_add_tail (&rs->rs_exp_list, &exp->exp_outstanding_replies);
1181
1182         spin_unlock_irqrestore (&exp->exp_lock, flags);
1183
1184         netrc = target_send_reply_msg (req, rc, fail_id);
1185
1186         spin_lock_irqsave (&svc->srv_lock, flags);
1187
1188         svc->srv_n_difficult_replies++;
1189
1190         if (netrc != 0) /* error sending: reply is off the net */
1191                 rs->rs_on_net = 0;
1192
1193         if (!rs->rs_on_net ||                   /* some notifier */
1194             list_empty(&rs->rs_exp_list) ||     /* completed already */
1195             list_empty(&rs->rs_obd_list)) {
1196                 list_add_tail (&rs->rs_list, &svc->srv_reply_queue);
1197                 wake_up (&svc->srv_waitq);
1198         } else {
1199                 list_add (&rs->rs_list, &sni->sni_active_replies);
1200                 rs->rs_scheduled = 0;           /* allow notifier to schedule */
1201         }
1202
1203         spin_unlock_irqrestore (&svc->srv_lock, flags);
1204 }
1205
1206 int target_handle_ping(struct ptlrpc_request *req)
1207 {
1208         return lustre_pack_reply(req, 0, NULL, NULL);
1209 }