Whamcloud - gitweb
- fixed a typo.
[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 the Lustre file system, http://www.lustre.org
7  *   Lustre is a trademark of Cluster File Systems, Inc.
8  *
9  *   You may have signed or agreed to another license before downloading
10  *   this software.  If so, you are bound by the terms and conditions
11  *   of that agreement, and the following does not apply to you.  See the
12  *   LICENSE file included with this distribution for more information.
13  *
14  *   If you did not agree to a different license, then this copy of Lustre
15  *   is open source software; you can redistribute it and/or modify it
16  *   under the terms of version 2 of the GNU General Public License as
17  *   published by the Free Software Foundation.
18  *
19  *   In either case, Lustre is distributed in the hope that it will be
20  *   useful, but WITHOUT ANY WARRANTY; without even the implied warranty
21  *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  *   license text for more details.
23  */
24
25 #ifndef EXPORT_SYMTAB
26 # define EXPORT_SYMTAB
27 #endif
28 #define DEBUG_SUBSYSTEM S_LDLM
29
30 #ifdef __KERNEL__
31 # include <libcfs/libcfs.h>
32 #else
33 # include <liblustre.h>
34 #endif
35 #include <obd.h>
36 #include <lustre_mds.h>
37 #include <lustre_dlm.h>
38 #include <lustre_net.h>
39 #include "ldlm_internal.h"
40
41 /* @priority: if non-zero, move the selected to the list head
42  * @create: if zero, only search in existed connections
43  */
44 static int import_set_conn(struct obd_import *imp, struct obd_uuid *uuid,
45                            int priority, int create)
46 {
47         struct ptlrpc_connection *ptlrpc_conn;
48         struct obd_import_conn *imp_conn = NULL, *item;
49         int rc = 0;
50         ENTRY;
51
52         if (!create && !priority) {
53                 CDEBUG(D_HA, "Nothing to do\n");
54                 RETURN(-EINVAL);
55         }
56
57         ptlrpc_conn = ptlrpc_uuid_to_connection(uuid);
58         if (!ptlrpc_conn) {
59                 CDEBUG(D_HA, "can't find connection %s\n", uuid->uuid);
60                 RETURN (-ENOENT);
61         }
62
63         if (create) {
64                 OBD_ALLOC(imp_conn, sizeof(*imp_conn));
65                 if (!imp_conn) {
66                         GOTO(out_put, rc = -ENOMEM);
67                 }
68         }
69
70         spin_lock(&imp->imp_lock);
71         list_for_each_entry(item, &imp->imp_conn_list, oic_item) {
72                 if (obd_uuid_equals(uuid, &item->oic_uuid)) {
73                         if (priority) {
74                                 list_del(&item->oic_item);
75                                 list_add(&item->oic_item, &imp->imp_conn_list);
76                                 item->oic_last_attempt = 0;
77                         }
78                         CDEBUG(D_HA, "imp %p@%s: found existing conn %s%s\n",
79                                imp, imp->imp_obd->obd_name, uuid->uuid,
80                                (priority ? ", moved to head" : ""));
81                         spin_unlock(&imp->imp_lock);
82                         GOTO(out_free, rc = 0);
83                 }
84         }
85         /* not found */
86         if (create) {
87                 imp_conn->oic_conn = ptlrpc_conn;
88                 imp_conn->oic_uuid = *uuid;
89                 item->oic_last_attempt = 0;
90                 if (priority)
91                         list_add(&imp_conn->oic_item, &imp->imp_conn_list);
92                 else
93                         list_add_tail(&imp_conn->oic_item, &imp->imp_conn_list);
94                 CDEBUG(D_HA, "imp %p@%s: add connection %s at %s\n",
95                        imp, imp->imp_obd->obd_name, uuid->uuid,
96                        (priority ? "head" : "tail"));
97         } else {
98                 spin_unlock(&imp->imp_lock);
99                 GOTO(out_free, rc = -ENOENT);
100
101         }
102
103         spin_unlock(&imp->imp_lock);
104         RETURN(0);
105 out_free:
106         if (imp_conn)
107                 OBD_FREE(imp_conn, sizeof(*imp_conn));
108 out_put:
109         ptlrpc_put_connection(ptlrpc_conn);
110         RETURN(rc);
111 }
112
113 int import_set_conn_priority(struct obd_import *imp, struct obd_uuid *uuid)
114 {
115         return import_set_conn(imp, uuid, 1, 0);
116 }
117
118 int client_import_add_conn(struct obd_import *imp, struct obd_uuid *uuid,
119                            int priority)
120 {
121         return import_set_conn(imp, uuid, priority, 1);
122 }
123
124 int client_import_del_conn(struct obd_import *imp, struct obd_uuid *uuid)
125 {
126         struct obd_import_conn *imp_conn;
127         struct obd_export *dlmexp;
128         int rc = -ENOENT;
129         ENTRY;
130
131         spin_lock(&imp->imp_lock);
132         if (list_empty(&imp->imp_conn_list)) {
133                 LASSERT(!imp->imp_connection);
134                 GOTO(out, rc);
135         }
136
137         list_for_each_entry(imp_conn, &imp->imp_conn_list, oic_item) {
138                 if (!obd_uuid_equals(uuid, &imp_conn->oic_uuid))
139                         continue;
140                 LASSERT(imp_conn->oic_conn);
141
142                 /* is current conn? */
143                 if (imp_conn == imp->imp_conn_current) {
144                         LASSERT(imp_conn->oic_conn == imp->imp_connection);
145
146                         if (imp->imp_state != LUSTRE_IMP_CLOSED &&
147                             imp->imp_state != LUSTRE_IMP_DISCON) {
148                                 CERROR("can't remove current connection\n");
149                                 GOTO(out, rc = -EBUSY);
150                         }
151
152                         ptlrpc_put_connection(imp->imp_connection);
153                         imp->imp_connection = NULL;
154
155                         dlmexp = class_conn2export(&imp->imp_dlm_handle);
156                         if (dlmexp && dlmexp->exp_connection) {
157                                 LASSERT(dlmexp->exp_connection ==
158                                         imp_conn->oic_conn);
159                                 ptlrpc_put_connection(dlmexp->exp_connection);
160                                 dlmexp->exp_connection = NULL;
161                         }
162                 }
163
164                 list_del(&imp_conn->oic_item);
165                 ptlrpc_put_connection(imp_conn->oic_conn);
166                 OBD_FREE(imp_conn, sizeof(*imp_conn));
167                 CDEBUG(D_HA, "imp %p@%s: remove connection %s\n",
168                        imp, imp->imp_obd->obd_name, uuid->uuid);
169                 rc = 0;
170                 break;
171         }
172 out:
173         spin_unlock(&imp->imp_lock);
174         if (rc == -ENOENT)
175                 CERROR("connection %s not found\n", uuid->uuid);
176         RETURN(rc);
177 }
178
179 /* configure an RPC client OBD device
180  *
181  * lcfg parameters:
182  * 1 - client UUID
183  * 2 - server UUID
184  * 3 - inactive-on-startup
185  */
186 int client_obd_setup(struct obd_device *obddev, obd_count len, void *buf)
187 {
188         struct lustre_cfg* lcfg = buf;
189         struct client_obd *cli = &obddev->u.cli;
190         struct obd_import *imp;
191         struct obd_uuid server_uuid;
192         int rq_portal, rp_portal, connect_op;
193         char *name = obddev->obd_type->typ_name;
194         int rc;
195         ENTRY;
196
197         /* In a more perfect world, we would hang a ptlrpc_client off of
198          * obd_type and just use the values from there. */
199         if (!strcmp(name, LUSTRE_OSC_NAME)) {
200 #ifdef __KERNEL__
201                 /* Can be removed in Lustre 1.8, for compatibility only */
202                 rq_portal = OST_IO_PORTAL;
203 #else
204                 rq_portal = OST_REQUEST_PORTAL;
205 #endif
206                 rp_portal = OSC_REPLY_PORTAL;
207                 connect_op = OST_CONNECT;
208         } else if (!strcmp(name, LUSTRE_MDC_NAME)) {
209                 rq_portal = MDS_REQUEST_PORTAL;
210                 rp_portal = MDC_REPLY_PORTAL;
211                 connect_op = MDS_CONNECT;
212         } else if (!strcmp(name, LUSTRE_MGC_NAME)) {
213                 rq_portal = MGS_REQUEST_PORTAL;
214                 rp_portal = MGC_REPLY_PORTAL;
215                 connect_op = MGS_CONNECT;
216         } else {
217                 CERROR("unknown client OBD type \"%s\", can't setup\n",
218                        name);
219                 RETURN(-EINVAL);
220         }
221
222         if (LUSTRE_CFG_BUFLEN(lcfg, 1) < 1) {
223                 CERROR("requires a TARGET UUID\n");
224                 RETURN(-EINVAL);
225         }
226
227         if (LUSTRE_CFG_BUFLEN(lcfg, 1) > 37) {
228                 CERROR("client UUID must be less than 38 characters\n");
229                 RETURN(-EINVAL);
230         }
231
232         if (LUSTRE_CFG_BUFLEN(lcfg, 2) < 1) {
233                 CERROR("setup requires a SERVER UUID\n");
234                 RETURN(-EINVAL);
235         }
236
237         if (LUSTRE_CFG_BUFLEN(lcfg, 2) > 37) {
238                 CERROR("target UUID must be less than 38 characters\n");
239                 RETURN(-EINVAL);
240         }
241
242         sema_init(&cli->cl_sem, 1);
243         sema_init(&cli->cl_mgc_sem, 1);
244         cli->cl_conn_count = 0;
245         memcpy(server_uuid.uuid, lustre_cfg_buf(lcfg, 2),
246                min_t(unsigned int, LUSTRE_CFG_BUFLEN(lcfg, 2),
247                      sizeof(server_uuid)));
248
249         cli->cl_dirty = 0;
250         cli->cl_avail_grant = 0;
251         /* FIXME: should limit this for the sum of all cl_dirty_max */
252         cli->cl_dirty_max = OSC_MAX_DIRTY_DEFAULT * 1024 * 1024;
253         if (cli->cl_dirty_max >> CFS_PAGE_SHIFT > num_physpages / 8)
254                 cli->cl_dirty_max = num_physpages << (CFS_PAGE_SHIFT - 3);
255         CFS_INIT_LIST_HEAD(&cli->cl_cache_waiters);
256         CFS_INIT_LIST_HEAD(&cli->cl_loi_ready_list);
257         CFS_INIT_LIST_HEAD(&cli->cl_loi_write_list);
258         CFS_INIT_LIST_HEAD(&cli->cl_loi_read_list);
259         client_obd_list_lock_init(&cli->cl_loi_list_lock);
260         cli->cl_r_in_flight = 0;
261         cli->cl_w_in_flight = 0;
262         spin_lock_init(&cli->cl_read_rpc_hist.oh_lock);
263         spin_lock_init(&cli->cl_write_rpc_hist.oh_lock);
264         spin_lock_init(&cli->cl_read_page_hist.oh_lock);
265         spin_lock_init(&cli->cl_write_page_hist.oh_lock);
266         spin_lock_init(&cli->cl_read_offset_hist.oh_lock);
267         spin_lock_init(&cli->cl_write_offset_hist.oh_lock);
268 #ifdef ENABLE_CHECKSUM
269         cli->cl_checksum = 1;
270 #endif
271         atomic_set(&cli->cl_resends, OSC_DEFAULT_RESENDS);
272
273         /* This value may be changed at connect time in
274            ptlrpc_connect_interpret. */
275         cli->cl_max_pages_per_rpc = min((int)PTLRPC_MAX_BRW_PAGES,
276                                         (int)(1024 * 1024 >> CFS_PAGE_SHIFT));
277
278         if (!strcmp(name, LUSTRE_MDC_NAME)) {
279                 cli->cl_max_rpcs_in_flight = MDC_MAX_RIF_DEFAULT;
280         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 128 /* MB */) {
281                 cli->cl_max_rpcs_in_flight = 2;
282         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 256 /* MB */) {
283                 cli->cl_max_rpcs_in_flight = 3;
284         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 512 /* MB */) {
285                 cli->cl_max_rpcs_in_flight = 4;
286         } else {
287                 cli->cl_max_rpcs_in_flight = OSC_MAX_RIF_DEFAULT;
288         }
289         rc = ldlm_get_ref();
290         if (rc) {
291                 CERROR("ldlm_get_ref failed: %d\n", rc);
292                 GOTO(err, rc);
293         }
294
295         ptlrpc_init_client(rq_portal, rp_portal, name,
296                            &obddev->obd_ldlm_client);
297
298         imp = class_new_import(obddev);
299         if (imp == NULL)
300                 GOTO(err_ldlm, rc = -ENOENT);
301         imp->imp_client = &obddev->obd_ldlm_client;
302         imp->imp_connect_op = connect_op;
303         imp->imp_initial_recov = 1;
304         imp->imp_initial_recov_bk = 0;
305         CFS_INIT_LIST_HEAD(&imp->imp_pinger_chain);
306         memcpy(cli->cl_target_uuid.uuid, lustre_cfg_buf(lcfg, 1),
307                LUSTRE_CFG_BUFLEN(lcfg, 1));
308         class_import_put(imp);
309
310         rc = client_import_add_conn(imp, &server_uuid, 1);
311         if (rc) {
312                 CERROR("can't add initial connection\n");
313                 GOTO(err_import, rc);
314         }
315
316         cli->cl_import = imp;
317         /* cli->cl_max_mds_{easize,cookiesize} updated by mdc_init_ea_size() */
318         cli->cl_max_mds_easize = sizeof(struct lov_mds_md);
319         cli->cl_max_mds_cookiesize = sizeof(struct llog_cookie);
320
321         if (LUSTRE_CFG_BUFLEN(lcfg, 3) > 0) {
322                 if (!strcmp(lustre_cfg_string(lcfg, 3), "inactive")) {
323                         CDEBUG(D_HA, "marking %s %s->%s as inactive\n",
324                                name, obddev->obd_name,
325                                cli->cl_target_uuid.uuid);
326                         
327                         spin_lock(&imp->imp_lock);
328                         imp->imp_invalid = 1;
329                         spin_unlock(&imp->imp_lock);
330                 }
331         }
332
333         cli->cl_qchk_stat = CL_NOT_QUOTACHECKED;
334
335         RETURN(rc);
336
337 err_import:
338         class_destroy_import(imp);
339 err_ldlm:
340         ldlm_put_ref(0);
341 err:
342         RETURN(rc);
343
344 }
345
346 int client_obd_cleanup(struct obd_device *obddev)
347 {
348         ENTRY;
349         ldlm_put_ref(obddev->obd_force);
350         RETURN(0);
351 }
352
353 /* ->o_connect() method for client side (OSC and MDC and MGC) */
354 int client_connect_import(struct lustre_handle *dlm_handle,
355                           struct obd_device *obd, struct obd_uuid *cluuid,
356                           struct obd_connect_data *data, void *localdata)
357 {
358         struct client_obd *cli = &obd->u.cli;
359         struct obd_import *imp = cli->cl_import;
360         struct obd_export *exp;
361         struct obd_connect_data *ocd;
362         struct ldlm_namespace *to_be_freed = NULL;
363         int rc;
364         ENTRY;
365
366         mutex_down(&cli->cl_sem);
367         rc = class_connect(dlm_handle, obd, cluuid);
368         if (rc)
369                 GOTO(out_sem, rc);
370
371         cli->cl_conn_count++;
372         if (cli->cl_conn_count > 1)
373                 GOTO(out_sem, rc);
374         exp = class_conn2export(dlm_handle);
375
376         if (obd->obd_namespace != NULL)
377                 CERROR("already have namespace!\n");
378         obd->obd_namespace = ldlm_namespace_new(obd->obd_name,
379                                                 LDLM_NAMESPACE_CLIENT,
380                                                 LDLM_NAMESPACE_GREEDY);
381         if (obd->obd_namespace == NULL)
382                 GOTO(out_disco, rc = -ENOMEM);
383
384         imp->imp_dlm_handle = *dlm_handle;
385         rc = ptlrpc_init_import(imp);
386         if (rc != 0)
387                 GOTO(out_ldlm, rc);
388
389         ocd = &imp->imp_connect_data;
390         if (data) {
391                 *ocd = *data;
392                 imp->imp_connect_flags_orig = data->ocd_connect_flags;
393         }
394
395         rc = ptlrpc_connect_import(imp, NULL);
396         if (rc != 0) {
397                 LASSERT (imp->imp_state == LUSTRE_IMP_DISCON);
398                 GOTO(out_ldlm, rc);
399         }
400         LASSERT(exp->exp_connection);
401
402         if (data) {
403                 LASSERT((ocd->ocd_connect_flags & data->ocd_connect_flags) ==
404                         ocd->ocd_connect_flags);
405                 data->ocd_connect_flags = ocd->ocd_connect_flags;
406         }
407
408         ptlrpc_pinger_add_import(imp);
409         EXIT;
410
411         if (rc) {
412 out_ldlm:
413                 ldlm_namespace_free_prior(obd->obd_namespace);
414                 to_be_freed = obd->obd_namespace;
415                 obd->obd_namespace = NULL;
416 out_disco:
417                 cli->cl_conn_count--;
418                 class_disconnect(exp);
419         } else {
420                 class_export_put(exp);
421         }
422 out_sem:
423         mutex_up(&cli->cl_sem);
424         if (to_be_freed)
425                 ldlm_namespace_free_post(to_be_freed, 0);
426         return rc;
427 }
428
429 int client_disconnect_export(struct obd_export *exp)
430 {
431         struct obd_device *obd = class_exp2obd(exp);
432         struct client_obd *cli;
433         struct obd_import *imp;
434         struct ldlm_namespace *to_be_freed = NULL;
435         int rc = 0, err;
436         ENTRY;
437
438         if (!obd) {
439                 CERROR("invalid export for disconnect: exp %p cookie "LPX64"\n",
440                        exp, exp ? exp->exp_handle.h_cookie : -1);
441                 RETURN(-EINVAL);
442         }
443
444         cli = &obd->u.cli;
445         imp = cli->cl_import;
446
447         mutex_down(&cli->cl_sem);
448         if (!cli->cl_conn_count) {
449                 CERROR("disconnecting disconnected device (%s)\n",
450                        obd->obd_name);
451                 GOTO(out_sem, rc = -EINVAL);
452         }
453
454         cli->cl_conn_count--;
455         if (cli->cl_conn_count)
456                 GOTO(out_no_disconnect, rc = 0);
457
458         /* Mark import deactivated now, so we don't try to reconnect if any
459          * of the cleanup RPCs fails (e.g. ldlm cancel, etc).  We don't
460          * fully deactivate the import, or that would drop all requests. */
461         spin_lock(&imp->imp_lock);
462         imp->imp_deactive = 1;
463         spin_unlock(&imp->imp_lock);
464
465         /* Some non-replayable imports (MDS's OSCs) are pinged, so just
466          * delete it regardless.  (It's safe to delete an import that was
467          * never added.) */
468         (void)ptlrpc_pinger_del_import(imp);
469
470         if (obd->obd_namespace != NULL) {
471                 /* obd_force == local only */
472                 ldlm_cli_cancel_unused(obd->obd_namespace, NULL,
473                                        obd->obd_force ? LDLM_FL_LOCAL_ONLY:0,
474                                        NULL);
475                 ldlm_namespace_free_prior(obd->obd_namespace);
476                 to_be_freed = obd->obd_namespace;
477                 obd->obd_namespace = NULL;
478         }
479
480         /* Yeah, obd_force means "forced shutdown". */
481         if (!obd->obd_force)
482                 rc = ptlrpc_disconnect_import(imp, 0);
483
484         ptlrpc_invalidate_import(imp);
485         ptlrpc_free_rq_pool(imp->imp_rq_pool);
486         class_destroy_import(imp);
487         cli->cl_import = NULL;
488
489         EXIT;
490  out_no_disconnect:
491         err = class_disconnect(exp);
492         if (!rc && err)
493                 rc = err;
494  out_sem:
495         mutex_up(&cli->cl_sem);
496         if (to_be_freed)
497                 ldlm_namespace_free_post(to_be_freed, obd->obd_no_recov);
498         RETURN(rc);
499 }
500
501 /* --------------------------------------------------------------------------
502  * from old lib/target.c
503  * -------------------------------------------------------------------------- */
504
505 int target_handle_reconnect(struct lustre_handle *conn, struct obd_export *exp,
506                             struct obd_uuid *cluuid)
507 {
508         ENTRY;
509         if (exp->exp_connection && exp->exp_imp_reverse) {
510                 struct lustre_handle *hdl;
511                 hdl = &exp->exp_imp_reverse->imp_remote_handle;
512                 /* Might be a re-connect after a partition. */
513                 if (!memcmp(&conn->cookie, &hdl->cookie, sizeof conn->cookie)) {
514                         CWARN("%s: %s reconnecting\n", exp->exp_obd->obd_name,
515                               cluuid->uuid);
516                         conn->cookie = exp->exp_handle.h_cookie;
517                         /* target_handle_connect() treats EALREADY and
518                          * -EALREADY differently.  EALREADY means we are
519                          * doing a valid reconnect from the same client. */
520                         RETURN(EALREADY);
521                 } else {
522                         CERROR("%s reconnecting from %s, "
523                                "handle mismatch (ours "LPX64", theirs "
524                                LPX64")\n", cluuid->uuid,
525                                exp->exp_connection->c_remote_uuid.uuid,
526                                hdl->cookie, conn->cookie);
527                         memset(conn, 0, sizeof *conn);
528                         /* target_handle_connect() treats EALREADY and
529                          * -EALREADY differently.  -EALREADY is an error
530                          * (same UUID, different handle). */
531                         RETURN(-EALREADY);
532                 }
533         }
534
535         conn->cookie = exp->exp_handle.h_cookie;
536         CDEBUG(D_HA, "connect export for UUID '%s' at %p, cookie "LPX64"\n",
537                cluuid->uuid, exp, conn->cookie);
538         RETURN(0);
539 }
540
541 void target_client_add_cb(struct obd_device *obd, __u64 transno, void *cb_data,
542                           int error)
543 {
544         struct obd_export *exp = cb_data;
545
546         CDEBUG(D_RPCTRACE, "%s: committing for initial connect of %s\n",
547                obd->obd_name, exp->exp_client_uuid.uuid);
548
549         spin_lock(&exp->exp_lock);
550         exp->exp_need_sync = 0;
551         spin_unlock(&exp->exp_lock);
552 }
553 EXPORT_SYMBOL(target_client_add_cb);
554
555 int target_handle_connect(struct ptlrpc_request *req, svc_handler_t handler)
556 {
557         struct obd_device *target, *targref = NULL;
558         struct obd_export *export = NULL;
559         struct obd_import *revimp;
560         struct lustre_handle conn;
561         struct obd_uuid tgtuuid;
562         struct obd_uuid cluuid;
563         struct obd_uuid remote_uuid;
564         char *str, *tmp;
565         int rc = 0, abort_recovery;
566         struct obd_connect_data *data;
567         int size[2] = { sizeof(struct ptlrpc_body), sizeof(*data) };
568         lnet_nid_t client_nid = 0;
569         ENTRY;
570
571         OBD_RACE(OBD_FAIL_TGT_CONN_RACE);
572
573         lustre_set_req_swabbed(req, REQ_REC_OFF);
574         str = lustre_msg_string(req->rq_reqmsg, REQ_REC_OFF, sizeof(tgtuuid)-1);
575         if (str == NULL) {
576                 DEBUG_REQ(D_ERROR, req, "bad target UUID for connect");
577                 GOTO(out, rc = -EINVAL);
578         }
579
580         obd_str2uuid (&tgtuuid, str);
581         target = class_uuid2obd(&tgtuuid);
582         /* COMPAT_146 */
583         /* old (pre 1.6) lustre_process_log tries to connect to mdsname
584            (eg. mdsA) instead of uuid. */
585         if (!target) {
586                 snprintf((char *)tgtuuid.uuid, sizeof(tgtuuid), "%s_UUID", str);
587                 target = class_uuid2obd(&tgtuuid);
588         }
589         if (!target)
590                 target = class_name2obd(str);
591         /* end COMPAT_146 */
592
593         if (!target || target->obd_stopping || !target->obd_set_up) {
594                 LCONSOLE_ERROR_MSG(0x137, "UUID '%s' is not available "
595                                    " for connect (%s)\n", str,
596                                    !target ? "no target" :
597                                    (target->obd_stopping ? "stopping" :
598                                    "not set up"));
599                 GOTO(out, rc = -ENODEV);
600         }
601
602         if (target->obd_no_conn) {
603                 LCONSOLE_WARN("%s: temporarily refusing client connection "
604                               "from %s\n", target->obd_name, 
605                               libcfs_nid2str(req->rq_peer.nid));
606                 GOTO(out, rc = -EAGAIN);
607         }
608
609         /* Make sure the target isn't cleaned up while we're here. Yes, 
610            there's still a race between the above check and our incref here. 
611            Really, class_uuid2obd should take the ref. */
612         targref = class_incref(target);
613
614         lustre_set_req_swabbed(req, REQ_REC_OFF + 1);
615         str = lustre_msg_string(req->rq_reqmsg, REQ_REC_OFF + 1,
616                                 sizeof(cluuid) - 1);
617         if (str == NULL) {
618                 DEBUG_REQ(D_ERROR, req, "bad client UUID for connect");
619                 GOTO(out, rc = -EINVAL);
620         }
621
622         obd_str2uuid (&cluuid, str);
623
624         /* XXX extract a nettype and format accordingly */
625         switch (sizeof(lnet_nid_t)) {
626                 /* NB the casts only avoid compiler warnings */
627         case 8:
628                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
629                          "NET_"LPX64"_UUID", (__u64)req->rq_peer.nid);
630                 break;
631         case 4:
632                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
633                          "NET_%x_UUID", (__u32)req->rq_peer.nid);
634                 break;
635         default:
636                 LBUG();
637         }
638
639         spin_lock_bh(&target->obd_processing_task_lock);
640         abort_recovery = target->obd_abort_recovery;
641         spin_unlock_bh(&target->obd_processing_task_lock);
642         if (abort_recovery)
643                 target_abort_recovery(target);
644
645         tmp = lustre_msg_buf(req->rq_reqmsg, REQ_REC_OFF + 2, sizeof conn);
646         if (tmp == NULL)
647                 GOTO(out, rc = -EPROTO);
648
649         memcpy(&conn, tmp, sizeof conn);
650
651         data = lustre_swab_reqbuf(req, REQ_REC_OFF + 3, sizeof(*data),
652                                   lustre_swab_connect);
653         rc = lustre_pack_reply(req, 2, size, NULL);
654         if (rc)
655                 GOTO(out, rc);
656
657         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
658                 if (!data) {
659                         DEBUG_REQ(D_WARNING, req, "Refusing old (unversioned) "
660                                   "libclient connection attempt");
661                         GOTO(out, rc = -EPROTO);
662                 } else if (data->ocd_version < LUSTRE_VERSION_CODE -
663                                                LUSTRE_VERSION_ALLOWED_OFFSET ||
664                            data->ocd_version > LUSTRE_VERSION_CODE +
665                                                LUSTRE_VERSION_ALLOWED_OFFSET) {
666                         DEBUG_REQ(D_WARNING, req, "Refusing %s (%d.%d.%d.%d) "
667                                   "libclient connection attempt",
668                                   data->ocd_version < LUSTRE_VERSION_CODE ?
669                                   "old" : "new",
670                                   OBD_OCD_VERSION_MAJOR(data->ocd_version),
671                                   OBD_OCD_VERSION_MINOR(data->ocd_version),
672                                   OBD_OCD_VERSION_PATCH(data->ocd_version),
673                                   OBD_OCD_VERSION_FIX(data->ocd_version));
674                         data = lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
675                                               offsetof(typeof(*data),
676                                                        ocd_version) +
677                                               sizeof(data->ocd_version));
678                         if (data) {
679                                 data->ocd_connect_flags = OBD_CONNECT_VERSION;
680                                 data->ocd_version = LUSTRE_VERSION_CODE;
681                         }
682                         GOTO(out, rc = -EPROTO);
683                 }
684         }
685
686         /* lctl gets a backstage, all-access pass. */
687         if (obd_uuid_equals(&cluuid, &target->obd_uuid))
688                 goto dont_check_exports;
689
690         spin_lock(&target->obd_dev_lock);
691         export = lustre_hash_get_object_by_key(target->obd_uuid_hash_body, &cluuid);
692
693         if (export != NULL && export->exp_connecting) { /* bug 9635, et. al. */
694                 CWARN("%s: exp %p already connecting\n",
695                       export->exp_obd->obd_name, export);
696                 class_export_put(export);
697                 export = NULL;
698                 rc = -EALREADY;
699         } else if (export != NULL && export->exp_connection != NULL &&
700                    req->rq_peer.nid != export->exp_connection->c_peer.nid) {
701                 /* make darn sure this is coming from the same peer
702                  * if the UUIDs matched */
703                   CWARN("%s: cookie %s seen on new NID %s when "
704                           "existing NID %s is already connected\n",
705                         target->obd_name, cluuid.uuid,
706                   libcfs_nid2str(req->rq_peer.nid),
707                   libcfs_nid2str(export->exp_connection->c_peer.nid));
708                   class_export_put(export);
709                   export = NULL;
710                   rc = -EALREADY;
711         } else if (export != NULL && export->exp_failed) { /* bug 11327 */
712                 CDEBUG(D_HA, "%s: exp %p evict in progress - new cookie needed "
713                       "for connect\n", export->exp_obd->obd_name, export);
714                 class_export_put(export);
715                 export = NULL;
716                 rc = -ENODEV;
717         } else if (export != NULL) {
718                 spin_lock(&export->exp_lock);
719                 export->exp_connecting = 1;
720                 spin_unlock(&export->exp_lock);
721                 class_export_put(export);
722                 spin_unlock(&target->obd_dev_lock);
723                 LASSERT(export->exp_obd == target);
724
725                 rc = target_handle_reconnect(&conn, export, &cluuid);
726         }
727
728         /* If we found an export, we already unlocked. */
729         if (!export) {
730                 spin_unlock(&target->obd_dev_lock);
731                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_CONNECT, 2 * obd_timeout);
732         } else if (req->rq_export == NULL &&
733                    atomic_read(&export->exp_rpc_count) > 0) {
734                 CWARN("%s: refuse connection from %s/%s to 0x%p; still busy "
735                       "with %d references\n", target->obd_name, cluuid.uuid,
736                       libcfs_nid2str(req->rq_peer.nid),
737                       export, atomic_read(&export->exp_refcount));
738                 GOTO(out, rc = -EBUSY);
739         } else if (req->rq_export != NULL &&
740                    atomic_read(&export->exp_rpc_count) > 1) {
741                 CWARN("%s: refuse reconnection from %s@%s to 0x%p; still busy "
742                       "with %d active RPCs\n", target->obd_name, cluuid.uuid,
743                       libcfs_nid2str(req->rq_peer.nid),
744                       export, atomic_read(&export->exp_rpc_count));
745                 GOTO(out, rc = -EBUSY);
746         } else if (lustre_msg_get_conn_cnt(req->rq_reqmsg) == 1) {
747                 CERROR("%s: NID %s (%s) reconnected with 1 conn_cnt; "
748                        "cookies not random?\n", target->obd_name,
749                        libcfs_nid2str(req->rq_peer.nid), cluuid.uuid);
750                 GOTO(out, rc = -EALREADY);
751         } else {
752                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_RECONNECT, 2 * obd_timeout);
753         }
754
755         if (rc < 0)
756                 GOTO(out, rc);
757
758         /* Tell the client if we're in recovery. */
759         if (target->obd_recovering) {
760                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
761                 /* If this is the first time a client connects,
762                    reset the recovery timer */
763                 if (rc == 0)
764                         target_start_recovery_timer(target, handler, req);
765         }
766
767         /* We want to handle EALREADY but *not* -EALREADY from
768          * target_handle_reconnect(), return reconnection state in a flag */
769         if (rc == EALREADY) {
770                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECONNECT);
771                 rc = 0;
772         } else {
773                 LASSERT(rc == 0);
774         }
775
776         /* Tell the client if we support replayable requests */
777         if (target->obd_replayable)
778                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
779         client_nid = req->rq_peer.nid;
780
781         if (export == NULL) {
782                 if (target->obd_recovering) {
783                         CERROR("%s: denying connection for new client %s (%s): "
784                                "%d clients in recovery for %lds\n",
785                                target->obd_name,
786                                libcfs_nid2str(req->rq_peer.nid), cluuid.uuid,
787                                target->obd_recoverable_clients,
788                                cfs_duration_sec(cfs_time_sub(cfs_timer_deadline(&target->obd_recovery_timer),
789                                                              cfs_time_current())));
790                         rc = -EBUSY;
791                 } else {
792  dont_check_exports:
793                         rc = obd_connect(&conn, target, &cluuid, data,
794                                          &client_nid);
795                 }
796         } else {
797                 rc = obd_reconnect(export, target, &cluuid, data);
798         }
799
800         if (rc)
801                 GOTO(out, rc);
802
803         /* Return only the parts of obd_connect_data that we understand, so the
804          * client knows that we don't understand the rest. */
805         if (data)
806                 memcpy(lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
807                                       sizeof(*data)),
808                        data, sizeof(*data));
809
810         /* If all else goes well, this is our RPC return code. */
811         req->rq_status = 0;
812
813         lustre_msg_set_handle(req->rq_repmsg, &conn);
814
815         /* ownership of this export ref transfers to the request AFTER we
816          * drop any previous reference the request had, but we don't want
817          * that to go to zero before we get our new export reference. */
818         export = class_conn2export(&conn);
819         if (!export) {
820                 DEBUG_REQ(D_ERROR, req, "Missing export!");
821                 GOTO(out, rc = -ENODEV);
822         }
823
824         /* If the client and the server are the same node, we will already
825          * have an export that really points to the client's DLM export,
826          * because we have a shared handles table.
827          *
828          * XXX this will go away when shaver stops sending the "connect" handle
829          * in the real "remote handle" field of the request --phik 24 Apr 2003
830          */
831         if (req->rq_export != NULL)
832                 class_export_put(req->rq_export);
833
834         req->rq_export = export;
835
836         spin_lock(&export->exp_lock);
837         if (export->exp_conn_cnt >= lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
838                 CERROR("%s: %s already connected at higher conn_cnt: %d > %d\n",
839                        cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
840                        export->exp_conn_cnt,
841                        lustre_msg_get_conn_cnt(req->rq_reqmsg));
842
843                 spin_unlock(&export->exp_lock);
844                 GOTO(out, rc = -EALREADY);
845         }
846         export->exp_conn_cnt = lustre_msg_get_conn_cnt(req->rq_reqmsg);
847
848         /* request from liblustre?  Don't evict it for not pinging. */
849         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
850                 export->exp_libclient = 1;
851                 spin_unlock(&export->exp_lock);
852
853                 spin_lock(&target->obd_dev_lock);
854                 list_del_init(&export->exp_obd_chain_timed);
855                 spin_unlock(&target->obd_dev_lock);
856         } else {
857                 spin_unlock(&export->exp_lock);
858         }
859
860         if (export->exp_connection != NULL)
861                 ptlrpc_put_connection(export->exp_connection);
862         export->exp_connection = ptlrpc_get_connection(req->rq_peer,
863                                                        req->rq_self,
864                                                        &remote_uuid);
865
866         spin_lock(&target->obd_dev_lock);
867         /* Export might be hashed already, e.g. if this is reconnect */
868         if (hlist_unhashed(&export->exp_nid_hash))
869                 lustre_hash_additem(export->exp_obd->obd_nid_hash_body,
870                                     &export->exp_connection->c_peer.nid,
871                                     &export->exp_nid_hash);
872         spin_unlock(&target->obd_dev_lock);
873
874         if (lustre_msg_get_op_flags(req->rq_repmsg) & MSG_CONNECT_RECONNECT) {
875                 revimp = class_import_get(export->exp_imp_reverse);
876                 GOTO(set_flags, rc = 0);
877         }
878
879         if (target->obd_recovering)
880                 target->obd_connected_clients++;
881
882         memcpy(&conn,
883                lustre_msg_buf(req->rq_reqmsg, REQ_REC_OFF + 2, sizeof conn),
884                sizeof conn);
885
886         if (export->exp_imp_reverse != NULL)
887                 class_destroy_import(export->exp_imp_reverse);
888         revimp = export->exp_imp_reverse = class_new_import(target);
889         revimp->imp_connection = ptlrpc_connection_addref(export->exp_connection);
890         revimp->imp_client = &export->exp_obd->obd_ldlm_client;
891         revimp->imp_remote_handle = conn;
892         revimp->imp_dlm_fake = 1;
893         revimp->imp_state = LUSTRE_IMP_FULL;
894 set_flags:
895         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_NEXT_VER) {
896                 /* Client wants v2 */
897                 revimp->imp_msg_magic = LUSTRE_MSG_MAGIC_V2;
898                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_NEXT_VER);
899                 if (export->exp_connect_flags & OBD_CONNECT_AT)
900                         revimp->imp_msg_flags |= MSG_AT_SUPPORT;
901         }
902
903         class_import_put(revimp);
904 out:
905         if (export) {
906                 spin_lock(&export->exp_lock);
907                 export->exp_connecting = 0;
908                 spin_unlock(&export->exp_lock);
909         }
910         if (targref)
911                 class_decref(targref);
912         if (rc)
913                 req->rq_status = rc;
914         RETURN(rc);
915 }
916
917 int target_handle_disconnect(struct ptlrpc_request *req)
918 {
919         int rc;
920         ENTRY;
921
922         rc = lustre_pack_reply(req, 1, NULL, NULL);
923         if (rc)
924                 RETURN(rc);
925
926         /* keep the rq_export around so we can send the reply */
927         req->rq_status = obd_disconnect(class_export_get(req->rq_export));
928         RETURN(0);
929 }
930
931 void target_destroy_export(struct obd_export *exp)
932 {
933         /* exports created from last_rcvd data, and "fake"
934            exports created by lctl don't have an import */
935         if (exp->exp_imp_reverse != NULL)
936                 class_destroy_import(exp->exp_imp_reverse);
937
938         /* We cancel locks at disconnect time, but this will catch any locks
939          * granted in a race with recovery-induced disconnect. */
940         if (exp->exp_obd->obd_namespace != NULL)
941                 ldlm_cancel_locks_for_export(exp);
942 }
943
944 /*
945  * Recovery functions
946  */
947
948
949 static void target_release_saved_req(struct ptlrpc_request *req)
950 {
951         ptlrpc_req_drop_rs(req);
952         class_export_put(req->rq_export);
953         OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
954         OBD_FREE(req, sizeof *req);
955 }
956
957 static void target_finish_recovery(struct obd_device *obd)
958 {
959         struct list_head *tmp, *n;
960
961         LCONSOLE_INFO("%s: sending delayed replies to recovered clients\n",
962                       obd->obd_name);
963
964         ldlm_reprocess_all_ns(obd->obd_namespace);
965
966         /* when recovery finished, cleanup orphans on mds and ost */
967         if (OBT(obd) && OBP(obd, postrecov)) {
968                 int rc = OBP(obd, postrecov)(obd);
969                 LCONSOLE_WARN("%s: recovery %s: rc %d\n", obd->obd_name,
970                               rc < 0 ? "failed" : "complete", rc);
971         }
972
973         list_for_each_safe(tmp, n, &obd->obd_delayed_reply_queue) {
974                 struct ptlrpc_request *req;
975                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
976                 list_del(&req->rq_list);
977                 DEBUG_REQ(D_HA, req, "delayed:");
978                 ptlrpc_reply(req);
979                 target_release_saved_req(req);
980         }
981         obd->obd_recovery_end = cfs_time_current_sec();
982 }
983
984 static void abort_recovery_queue(struct obd_device *obd)
985 {
986         struct ptlrpc_request *req;
987         struct list_head *tmp, *n;
988         int rc;
989
990         list_for_each_safe(tmp, n, &obd->obd_recovery_queue) {
991                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
992                 list_del(&req->rq_list);
993                 DEBUG_REQ(D_ERROR, req, "aborted:");
994                 req->rq_status = -ENOTCONN;
995                 req->rq_type = PTL_RPC_MSG_ERR;
996                 rc = lustre_pack_reply(req, 1, NULL, NULL);
997                 if (rc == 0)
998                         ptlrpc_reply(req);
999                 else
1000                         DEBUG_REQ(D_ERROR, req,
1001                                   "packing failed for abort-reply; skipping");
1002                 target_release_saved_req(req);
1003         }
1004 }
1005
1006 /* Called from a cleanup function if the device is being cleaned up
1007    forcefully.  The exports should all have been disconnected already,
1008    the only thing left to do is
1009      - clear the recovery flags
1010      - cancel the timer
1011      - free queued requests and replies, but don't send replies
1012    Because the obd_stopping flag is set, no new requests should be received.
1013
1014 */
1015 void target_cleanup_recovery(struct obd_device *obd)
1016 {
1017         struct list_head *tmp, *n;
1018         struct ptlrpc_request *req;
1019         ENTRY;
1020
1021         LASSERT(obd->obd_stopping);
1022
1023         spin_lock_bh(&obd->obd_processing_task_lock);
1024         if (!obd->obd_recovering) {
1025                 spin_unlock_bh(&obd->obd_processing_task_lock);
1026                 EXIT;
1027                 return;
1028         }
1029         obd->obd_recovering = obd->obd_abort_recovery = 0;
1030         target_cancel_recovery_timer(obd);
1031         spin_unlock_bh(&obd->obd_processing_task_lock);
1032
1033         list_for_each_safe(tmp, n, &obd->obd_delayed_reply_queue) {
1034                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
1035                 list_del(&req->rq_list);
1036                 target_release_saved_req(req);
1037         }
1038
1039         list_for_each_safe(tmp, n, &obd->obd_recovery_queue) {
1040                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
1041                 list_del(&req->rq_list);
1042                 target_release_saved_req(req);
1043         }
1044         EXIT;
1045 }
1046
1047 void target_abort_recovery(void *data)
1048 {
1049         struct obd_device *obd = data;
1050         ENTRY;
1051
1052         spin_lock_bh(&obd->obd_processing_task_lock);
1053         if (!obd->obd_recovering) {
1054                 spin_unlock_bh(&obd->obd_processing_task_lock);
1055                 EXIT;
1056                 return;
1057         }
1058         obd->obd_recovering = obd->obd_abort_recovery = 0;
1059         target_cancel_recovery_timer(obd);
1060         spin_unlock_bh(&obd->obd_processing_task_lock);
1061
1062         LCONSOLE_WARN("%s: recovery period over; %d clients never reconnected "
1063                       "after %lds (%d clients did)\n",
1064                       obd->obd_name, obd->obd_recoverable_clients,
1065                       cfs_time_current_sec()- obd->obd_recovery_start,
1066                       obd->obd_connected_clients);
1067         class_disconnect_stale_exports(obd);
1068         abort_recovery_queue(obd);
1069
1070         target_finish_recovery(obd);
1071         CDEBUG(D_HA, "%s: recovery complete\n", obd_uuid2str(&obd->obd_uuid));
1072         EXIT;
1073 }
1074
1075 static void target_recovery_expired(unsigned long castmeharder)
1076 {
1077         struct obd_device *obd = (struct obd_device *)castmeharder;
1078         CERROR("%s: recovery timed out, aborting\n", obd->obd_name);
1079         spin_lock_bh(&obd->obd_processing_task_lock);
1080         if (obd->obd_recovering)
1081                 obd->obd_abort_recovery = 1;
1082         cfs_waitq_signal(&obd->obd_next_transno_waitq);
1083         spin_unlock_bh(&obd->obd_processing_task_lock);
1084 }
1085
1086
1087 /* obd_processing_task_lock should be held */
1088 void target_cancel_recovery_timer(struct obd_device *obd)
1089 {
1090         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1091         cfs_timer_disarm(&obd->obd_recovery_timer);
1092 }
1093
1094 static void reset_recovery_timer(struct obd_device *obd, int mintime)
1095 {
1096         spin_lock_bh(&obd->obd_processing_task_lock);
1097         if (!obd->obd_recovering) {
1098                 spin_unlock_bh(&obd->obd_processing_task_lock);
1099                 return;
1100         }
1101         /* Track the client's largest expected replay time */
1102         obd->obd_recovery_timeout = max(mintime, obd->obd_recovery_timeout);
1103         obd->obd_recovery_end = cfs_time_current_sec() +
1104                 obd->obd_recovery_timeout;
1105         cfs_timer_arm(&obd->obd_recovery_timer, 
1106                       cfs_time_shift(obd->obd_recovery_timeout));
1107         spin_unlock_bh(&obd->obd_processing_task_lock);
1108         CDEBUG(D_HA, "%s: recovery timer will expire in %u seconds\n", 
1109                obd->obd_name, obd->obd_recovery_timeout);
1110 }
1111
1112
1113 /* Reset the timer with each new client connection */
1114 void target_start_recovery_timer(struct obd_device *obd, svc_handler_t handler,
1115                                  struct ptlrpc_request *req)
1116 {
1117         spin_lock_bh(&obd->obd_processing_task_lock);
1118         if (obd->obd_recovery_handler)
1119                 goto out;
1120         CWARN("%s: starting recovery timer\n", obd->obd_name);
1121         obd->obd_recovery_start = cfs_time_current_sec();
1122         /* minimum */
1123         obd->obd_recovery_timeout = OBD_RECOVERY_FACTOR * obd_timeout;
1124         obd->obd_recovery_handler = handler;
1125         cfs_timer_init(&obd->obd_recovery_timer, target_recovery_expired, obd);
1126 out:
1127         spin_unlock_bh(&obd->obd_processing_task_lock);
1128         reset_recovery_timer(obd, OBD_RECOVERY_FACTOR *
1129                              lustre_msg_get_timeout(req->rq_reqmsg));
1130 }
1131
1132 static int check_for_next_transno(struct obd_device *obd)
1133 {
1134         struct ptlrpc_request *req;
1135         int wake_up = 0, connected, completed, queue_len, max;
1136         __u64 next_transno, req_transno;
1137
1138         spin_lock_bh(&obd->obd_processing_task_lock);
1139         req = list_entry(obd->obd_recovery_queue.next,
1140                          struct ptlrpc_request, rq_list);
1141         max = obd->obd_max_recoverable_clients;
1142         req_transno = lustre_msg_get_transno(req->rq_reqmsg);
1143         connected = obd->obd_connected_clients;
1144         completed = max - obd->obd_recoverable_clients;
1145         queue_len = obd->obd_requests_queued_for_recovery;
1146         next_transno = obd->obd_next_recovery_transno;
1147
1148         CDEBUG(D_HA,"max: %d, connected: %d, completed: %d, queue_len: %d, "
1149                "req_transno: "LPU64", next_transno: "LPU64"\n",
1150                max, connected, completed, queue_len, req_transno, next_transno);
1151         if (obd->obd_abort_recovery) {
1152                 CDEBUG(D_HA, "waking for aborted recovery\n");
1153                 wake_up = 1;
1154         } else if (!obd->obd_recovering) {
1155                 CDEBUG(D_HA, "waking for completed recovery (?)\n");
1156                 wake_up = 1;
1157         } else if (req_transno == next_transno) {
1158                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1159                 wake_up = 1;
1160         } else if (queue_len + completed == max) {
1161                 CDEBUG(D_ERROR,
1162                        "waking for skipped transno (skip: "LPD64
1163                        ", ql: %d, comp: %d, conn: %d, next: "LPD64")\n",
1164                        next_transno, queue_len, completed, max, req_transno);
1165                 obd->obd_next_recovery_transno = req_transno;
1166                 wake_up = 1;
1167         }
1168         spin_unlock_bh(&obd->obd_processing_task_lock);
1169         LASSERT(lustre_msg_get_transno(req->rq_reqmsg) >= next_transno);
1170         return wake_up;
1171 }
1172
1173 static void process_recovery_queue(struct obd_device *obd)
1174 {
1175         struct ptlrpc_request *req;
1176         int abort_recovery = 0;
1177         struct l_wait_info lwi = { 0 };
1178         ENTRY;
1179
1180         for (;;) {
1181                 spin_lock_bh(&obd->obd_processing_task_lock);
1182                 LASSERT(obd->obd_processing_task == cfs_curproc_pid());
1183                 req = list_entry(obd->obd_recovery_queue.next,
1184                                  struct ptlrpc_request, rq_list);
1185
1186                 if (lustre_msg_get_transno(req->rq_reqmsg) !=
1187                     obd->obd_next_recovery_transno) {
1188                         spin_unlock_bh(&obd->obd_processing_task_lock);
1189                         CDEBUG(D_HA, "Waiting for transno "LPD64" (1st is "
1190                                LPD64", x"LPU64")\n",
1191                                obd->obd_next_recovery_transno,
1192                                lustre_msg_get_transno(req->rq_reqmsg),
1193                                req->rq_xid);
1194                         l_wait_event(obd->obd_next_transno_waitq,
1195                                      check_for_next_transno(obd), &lwi);
1196                         spin_lock_bh(&obd->obd_processing_task_lock);
1197                         abort_recovery = obd->obd_abort_recovery;
1198                         spin_unlock_bh(&obd->obd_processing_task_lock);
1199                         if (abort_recovery) {
1200                                 target_abort_recovery(obd);
1201                                 return;
1202                         }
1203                         continue;
1204                 }
1205                 list_del_init(&req->rq_list);
1206                 obd->obd_requests_queued_for_recovery--;
1207                 spin_unlock_bh(&obd->obd_processing_task_lock);
1208
1209                 DEBUG_REQ(D_HA, req, "processing: ");
1210                 (void)obd->obd_recovery_handler(req);
1211                 obd->obd_replayed_requests++;
1212                 reset_recovery_timer(obd, 2 * /* safety */
1213                         at_get(&req->rq_rqbd->rqbd_service->srv_at_estimate));
1214                 /* bug 1580: decide how to properly sync() in recovery */
1215                 //mds_fsync_super(obd->u.obt.obt_sb);
1216                 class_export_put(req->rq_export);
1217                 ptlrpc_req_drop_rs(req);
1218                 OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
1219                 OBD_FREE(req, sizeof *req);
1220                 spin_lock_bh(&obd->obd_processing_task_lock);
1221                 obd->obd_next_recovery_transno++;
1222                 if (list_empty(&obd->obd_recovery_queue)) {
1223                         obd->obd_processing_task = 0;
1224                         spin_unlock_bh(&obd->obd_processing_task_lock);
1225                         break;
1226                 }
1227                 spin_unlock_bh(&obd->obd_processing_task_lock);
1228         }
1229         EXIT;
1230 }
1231
1232 int target_queue_recovery_request(struct ptlrpc_request *req,
1233                                   struct obd_device *obd)
1234 {
1235         struct list_head *tmp;
1236         int inserted = 0;
1237         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
1238         struct ptlrpc_request *saved_req;
1239         struct lustre_msg *reqmsg;
1240
1241         /* CAVEAT EMPTOR: The incoming request message has been swabbed
1242          * (i.e. buflens etc are in my own byte order), but type-dependent
1243          * buffers (eg mds_body, ost_body etc) have NOT been swabbed. */
1244
1245         if (!transno) {
1246                 CFS_INIT_LIST_HEAD(&req->rq_list);
1247                 DEBUG_REQ(D_HA, req, "not queueing");
1248                 return 1;
1249         }
1250
1251         /* XXX If I were a real man, these LBUGs would be sane cleanups. */
1252         /* XXX just like the request-dup code in queue_final_reply */
1253         OBD_ALLOC(saved_req, sizeof *saved_req);
1254         if (!saved_req)
1255                 LBUG();
1256         OBD_ALLOC(reqmsg, req->rq_reqlen);
1257         if (!reqmsg)
1258                 LBUG();
1259
1260         spin_lock_bh(&obd->obd_processing_task_lock);
1261
1262         /* If we're processing the queue, we want don't want to queue this
1263          * message.
1264          *
1265          * Also, if this request has a transno less than the one we're waiting
1266          * for, we should process it now.  It could (and currently always will)
1267          * be an open request for a descriptor that was opened some time ago.
1268          *
1269          * Also, a resent, replayed request that has already been
1270          * handled will pass through here and be processed immediately.
1271          */
1272         if (obd->obd_processing_task == cfs_curproc_pid() ||
1273             transno < obd->obd_next_recovery_transno) {
1274                 /* Processing the queue right now, don't re-add. */
1275                 LASSERT(list_empty(&req->rq_list));
1276                 spin_unlock_bh(&obd->obd_processing_task_lock);
1277                 OBD_FREE(reqmsg, req->rq_reqlen);
1278                 OBD_FREE(saved_req, sizeof *saved_req);
1279                 return 1;
1280         }
1281
1282         /* A resent, replayed request that is still on the queue; just drop it.
1283            The queued request will handle this. */
1284         if ((lustre_msg_get_flags(req->rq_reqmsg) & (MSG_RESENT|MSG_REPLAY)) ==
1285             (MSG_RESENT | MSG_REPLAY)) {
1286                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
1287                 spin_unlock_bh(&obd->obd_processing_task_lock);
1288                 OBD_FREE(reqmsg, req->rq_reqlen);
1289                 OBD_FREE(saved_req, sizeof *saved_req);
1290                 return 0;
1291         }
1292
1293         memcpy(saved_req, req, sizeof *req);
1294         memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
1295         req = saved_req;
1296         req->rq_reqmsg = reqmsg;
1297         class_export_get(req->rq_export);
1298         CFS_INIT_LIST_HEAD(&req->rq_list);
1299
1300         /* XXX O(n^2) */
1301         list_for_each(tmp, &obd->obd_recovery_queue) {
1302                 struct ptlrpc_request *reqiter =
1303                         list_entry(tmp, struct ptlrpc_request, rq_list);
1304
1305                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
1306                         list_add_tail(&req->rq_list, &reqiter->rq_list);
1307                         inserted = 1;
1308                         break;
1309                 }
1310         }
1311
1312         if (!inserted) {
1313                 list_add_tail(&req->rq_list, &obd->obd_recovery_queue);
1314         }
1315
1316         obd->obd_requests_queued_for_recovery++;
1317
1318         if (obd->obd_processing_task != 0) {
1319                 /* Someone else is processing this queue, we'll leave it to
1320                  * them.
1321                  */
1322                 cfs_waitq_signal(&obd->obd_next_transno_waitq);
1323                 spin_unlock_bh(&obd->obd_processing_task_lock);
1324                 return 0;
1325         }
1326
1327         /* Nobody is processing, and we know there's (at least) one to process
1328          * now, so we'll do the honours.
1329          */
1330         obd->obd_processing_task = cfs_curproc_pid();
1331         spin_unlock_bh(&obd->obd_processing_task_lock);
1332
1333         process_recovery_queue(obd);
1334         return 0;
1335 }
1336
1337 struct obd_device * target_req2obd(struct ptlrpc_request *req)
1338 {
1339         return req->rq_export->exp_obd;
1340 }
1341
1342 int target_queue_last_replay_reply(struct ptlrpc_request *req, int rc)
1343 {
1344         struct obd_device *obd = target_req2obd(req);
1345         struct ptlrpc_request *saved_req;
1346         struct lustre_msg *reqmsg;
1347         int recovery_done = 0;
1348
1349         LASSERT ((rc == 0) == req->rq_packed_final);
1350
1351         if (!req->rq_packed_final) {
1352                 /* Just like ptlrpc_error, but without the sending. */
1353                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1354                 if (rc)
1355                         return rc;
1356                 req->rq_type = PTL_RPC_MSG_ERR;
1357         }
1358
1359         LASSERT(!req->rq_reply_state->rs_difficult);
1360         LASSERT(list_empty(&req->rq_list));
1361         /* XXX a bit like the request-dup code in queue_recovery_request */
1362         OBD_ALLOC(saved_req, sizeof *saved_req);
1363         if (!saved_req)
1364                 return -ENOMEM;
1365         OBD_ALLOC(reqmsg, req->rq_reqlen);
1366         if (!reqmsg) {
1367                 OBD_FREE(saved_req, sizeof *req);
1368                 return -ENOMEM;
1369         }
1370         *saved_req = *req;
1371         memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
1372
1373         /* Don't race cleanup */
1374         spin_lock_bh(&obd->obd_processing_task_lock);
1375         if (obd->obd_stopping) {
1376                 spin_unlock_bh(&obd->obd_processing_task_lock);
1377                 OBD_FREE(reqmsg, req->rq_reqlen);
1378                 OBD_FREE(saved_req, sizeof *req);
1379                 req->rq_status = -ENOTCONN;
1380                 /* rv is ignored anyhow */
1381                 return -ENOTCONN;
1382         }
1383         ptlrpc_rs_addref(req->rq_reply_state);  /* +1 ref for saved reply */
1384         req = saved_req;
1385         req->rq_reqmsg = reqmsg;
1386         class_export_get(req->rq_export);
1387         list_add(&req->rq_list, &obd->obd_delayed_reply_queue);
1388
1389         /* only count the first "replay over" request from each
1390            export */
1391         if (req->rq_export->exp_replay_needed) {
1392                 --obd->obd_recoverable_clients;
1393                 
1394                 spin_lock(&req->rq_export->exp_lock);
1395                 req->rq_export->exp_replay_needed = 0;
1396                 spin_unlock(&req->rq_export->exp_lock);
1397         }
1398         recovery_done = (obd->obd_recoverable_clients == 0);
1399         spin_unlock_bh(&obd->obd_processing_task_lock);
1400
1401         OBD_RACE(OBD_FAIL_LDLM_RECOV_CLIENTS);
1402         if (recovery_done) {
1403                 spin_lock_bh(&obd->obd_processing_task_lock);
1404                 obd->obd_recovering = obd->obd_abort_recovery = 0;
1405                 target_cancel_recovery_timer(obd);
1406                 spin_unlock_bh(&obd->obd_processing_task_lock);
1407
1408                 target_finish_recovery(obd);
1409                 CDEBUG(D_HA, "%s: recovery complete\n",
1410                        obd_uuid2str(&obd->obd_uuid));
1411         } else {
1412                 CWARN("%s: %d recoverable clients remain\n",
1413                        obd->obd_name, obd->obd_recoverable_clients);
1414                 cfs_waitq_signal(&obd->obd_next_transno_waitq);
1415         }
1416
1417         return 1;
1418 }
1419
1420 static inline struct ldlm_pool *ldlm_exp2pl(struct obd_export *exp)
1421 {
1422         LASSERT(exp != NULL);
1423         return &exp->exp_obd->obd_namespace->ns_pool;
1424 }
1425
1426 int target_pack_pool_reply(struct ptlrpc_request *req)
1427 {
1428         struct ldlm_pool *pl;
1429         ENTRY;
1430     
1431         if (!exp_connect_lru_resize(req->rq_export)) {
1432                 lustre_msg_set_slv(req->rq_repmsg, 0);
1433                 lustre_msg_set_limit(req->rq_repmsg, 0);
1434                 RETURN(0);
1435         }
1436         
1437         pl = ldlm_exp2pl(req->rq_export);
1438
1439         spin_lock(&pl->pl_lock);
1440         LASSERT(ldlm_pool_get_slv(pl) != 0 && ldlm_pool_get_limit(pl) != 0);
1441         lustre_msg_set_slv(req->rq_repmsg, ldlm_pool_get_slv(pl));
1442         lustre_msg_set_limit(req->rq_repmsg, ldlm_pool_get_limit(pl));
1443         spin_unlock(&pl->pl_lock);
1444
1445         RETURN(0);
1446 }
1447
1448 int
1449 target_send_reply_msg (struct ptlrpc_request *req, int rc, int fail_id)
1450 {
1451         if (OBD_FAIL_CHECK(fail_id | OBD_FAIL_ONCE)) {
1452                 obd_fail_loc |= OBD_FAIL_ONCE | OBD_FAILED;
1453                 DEBUG_REQ(D_ERROR, req, "dropping reply");
1454                 return (-ECOMM);
1455         }
1456
1457         if (rc) {
1458                 DEBUG_REQ(D_ERROR, req, "processing error (%d)", rc);
1459                 req->rq_status = rc;
1460                 return (ptlrpc_error(req));
1461         } else {
1462                 DEBUG_REQ(D_NET, req, "sending reply");
1463         }
1464
1465         return (ptlrpc_send_reply(req, PTLRPC_REPLY_MAYBE_DIFFICULT));
1466 }
1467
1468 void
1469 target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
1470 {
1471         int                        netrc;
1472         struct ptlrpc_reply_state *rs;
1473         struct obd_device         *obd;
1474         struct obd_export         *exp;
1475         struct ptlrpc_service     *svc;
1476
1477         svc = req->rq_rqbd->rqbd_service;
1478         rs = req->rq_reply_state;
1479         if (rs == NULL || !rs->rs_difficult) {
1480                 /* no notifiers */
1481                 target_send_reply_msg (req, rc, fail_id);
1482                 return;
1483         }
1484
1485         /* must be an export if locks saved */
1486         LASSERT (req->rq_export != NULL);
1487         /* req/reply consistent */
1488         LASSERT (rs->rs_service == svc);
1489
1490         /* "fresh" reply */
1491         LASSERT (!rs->rs_scheduled);
1492         LASSERT (!rs->rs_scheduled_ever);
1493         LASSERT (!rs->rs_handled);
1494         LASSERT (!rs->rs_on_net);
1495         LASSERT (rs->rs_export == NULL);
1496         LASSERT (list_empty(&rs->rs_obd_list));
1497         LASSERT (list_empty(&rs->rs_exp_list));
1498
1499         exp = class_export_get (req->rq_export);
1500         obd = exp->exp_obd;
1501
1502         /* disable reply scheduling onto srv_reply_queue while I'm setting up */
1503         rs->rs_scheduled = 1;
1504         rs->rs_on_net    = 1;
1505         rs->rs_xid       = req->rq_xid;
1506         rs->rs_transno   = req->rq_transno;
1507         rs->rs_export    = exp;
1508
1509         spin_lock(&obd->obd_uncommitted_replies_lock);
1510
1511         if (rs->rs_transno > obd->obd_last_committed) {
1512                 /* not committed already */
1513                 list_add_tail (&rs->rs_obd_list,
1514                                &obd->obd_uncommitted_replies);
1515         }
1516
1517         spin_unlock (&obd->obd_uncommitted_replies_lock);
1518         spin_lock (&exp->exp_lock);
1519
1520         list_add_tail (&rs->rs_exp_list, &exp->exp_outstanding_replies);
1521
1522         spin_unlock(&exp->exp_lock);
1523
1524         netrc = target_send_reply_msg (req, rc, fail_id);
1525
1526         spin_lock(&svc->srv_lock);
1527
1528         svc->srv_n_difficult_replies++;
1529
1530         if (netrc != 0) {
1531                 /* error sending: reply is off the net.  Also we need +1
1532                  * reply ref until ptlrpc_server_handle_reply() is done
1533                  * with the reply state (if the send was successful, there
1534                  * would have been +1 ref for the net, which
1535                  * reply_out_callback leaves alone) */
1536                 rs->rs_on_net = 0;
1537                 ptlrpc_rs_addref(rs);
1538                 atomic_inc (&svc->srv_outstanding_replies);
1539         }
1540
1541         if (!rs->rs_on_net ||                   /* some notifier */
1542             list_empty(&rs->rs_exp_list) ||     /* completed already */
1543             list_empty(&rs->rs_obd_list)) {
1544                 list_add_tail (&rs->rs_list, &svc->srv_reply_queue);
1545                 cfs_waitq_signal (&svc->srv_waitq);
1546         } else {
1547                 list_add (&rs->rs_list, &svc->srv_active_replies);
1548                 rs->rs_scheduled = 0;           /* allow notifier to schedule */
1549         }
1550
1551         spin_unlock(&svc->srv_lock);
1552 }
1553
1554 int target_handle_ping(struct ptlrpc_request *req)
1555 {
1556         obd_ping(req->rq_export);
1557         return lustre_pack_reply(req, 1, NULL, NULL);
1558 }
1559
1560 void target_committed_to_req(struct ptlrpc_request *req)
1561 {
1562         struct obd_device *obd = req->rq_export->exp_obd;
1563
1564         if (!obd->obd_no_transno && req->rq_repmsg != NULL)
1565                 lustre_msg_set_last_committed(req->rq_repmsg,
1566                                               obd->obd_last_committed);
1567         else
1568                 DEBUG_REQ(D_IOCTL, req, "not sending last_committed update (%d/"
1569                           "%d)", obd->obd_no_transno, req->rq_repmsg == NULL);
1570
1571         CDEBUG(D_INFO, "last_committed x"LPU64", this req x"LPU64"\n",
1572                obd->obd_last_committed, req->rq_xid);
1573 }
1574
1575 EXPORT_SYMBOL(target_committed_to_req);
1576
1577 #ifdef HAVE_QUOTA_SUPPORT
1578 int target_handle_qc_callback(struct ptlrpc_request *req)
1579 {
1580         struct obd_quotactl *oqctl;
1581         struct client_obd *cli = &req->rq_export->exp_obd->u.cli;
1582
1583         oqctl = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*oqctl),
1584                                    lustre_swab_obd_quotactl);
1585         if (oqctl == NULL) {
1586                 CERROR("Can't unpack obd_quotactl\n");
1587                 RETURN(-EPROTO);
1588         }
1589
1590         cli->cl_qchk_stat = oqctl->qc_stat;
1591
1592         return 0;
1593 }
1594
1595 int target_handle_dqacq_callback(struct ptlrpc_request *req)
1596 {
1597 #ifdef __KERNEL__
1598         struct obd_device *obd = req->rq_export->exp_obd;
1599         struct obd_device *master_obd;
1600         struct lustre_quota_ctxt *qctxt;
1601         struct qunit_data *qdata;
1602         void* rep;
1603         struct qunit_data_old *qdata_old;
1604         int rc = 0;
1605         int repsize[2] = { sizeof(struct ptlrpc_body),
1606                            sizeof(struct qunit_data) };
1607         ENTRY;
1608         
1609         rc = lustre_pack_reply(req, 2, repsize, NULL);
1610         if (rc)
1611                 RETURN(rc);
1612
1613         LASSERT(req->rq_export);
1614
1615         /* fixed for bug10707 */
1616         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
1617             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
1618                 CDEBUG(D_QUOTA, "qd_count is 64bit!\n");
1619                 rep = lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF, 
1620                                      sizeof(struct qunit_data));
1621                 LASSERT(rep);
1622                 qdata = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*qdata), 
1623                                            lustre_swab_qdata);
1624         } else {
1625                 CDEBUG(D_QUOTA, "qd_count is 32bit!\n");
1626                 rep = lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF, 
1627                                      sizeof(struct qunit_data_old));
1628                 LASSERT(rep);
1629                 qdata_old = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*qdata_old), 
1630                                                lustre_swab_qdata_old);
1631                 qdata = lustre_quota_old_to_new(qdata_old);
1632         }
1633
1634         if (qdata == NULL) {
1635                 CERROR("Can't unpack qunit_data\n");
1636                 RETURN(-EPROTO);
1637         }
1638
1639         /* we use the observer */
1640         LASSERT(obd->obd_observer && obd->obd_observer->obd_observer);
1641         master_obd = obd->obd_observer->obd_observer;
1642         qctxt = &master_obd->u.obt.obt_qctxt;
1643         
1644         LASSERT(qctxt->lqc_handler);
1645         rc = qctxt->lqc_handler(master_obd, qdata,
1646                                 lustre_msg_get_opc(req->rq_reqmsg));
1647         if (rc && rc != -EDQUOT)
1648                 CDEBUG(rc == -EBUSY  ? D_QUOTA : D_ERROR, 
1649                        "dqacq failed! (rc:%d)\n", rc);
1650         
1651         /* the qd_count might be changed in lqc_handler */
1652         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
1653             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
1654                 memcpy(rep,qdata,sizeof(*qdata));
1655         } else {
1656                 qdata_old = lustre_quota_new_to_old(qdata);
1657                 memcpy(rep,qdata_old,sizeof(*qdata_old));
1658         }
1659         req->rq_status = rc;
1660         rc = ptlrpc_reply(req);
1661         
1662         RETURN(rc);     
1663 #else
1664         return 0;
1665 #endif /* !__KERNEL__ */
1666 }
1667 #endif /* HAVE_QUOTA_SUPPORT */
1668
1669 ldlm_mode_t lck_compat_array[] = {
1670         [LCK_EX] LCK_COMPAT_EX,
1671         [LCK_PW] LCK_COMPAT_PW,
1672         [LCK_PR] LCK_COMPAT_PR,
1673         [LCK_CW] LCK_COMPAT_CW,
1674         [LCK_CR] LCK_COMPAT_CR,
1675         [LCK_NL] LCK_COMPAT_NL,
1676         [LCK_GROUP] LCK_COMPAT_GROUP
1677 };