Whamcloud - gitweb
LU-1842 protocol: add support for OBD_IDX_READ
[fs/lustre-release.git] / lustre / mdt / mdt_handler.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2012, Whamcloud, Inc.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/mdt/mdt_handler.c
37  *
38  * Lustre Metadata Target (mdt) request handler
39  *
40  * Author: Peter Braam <braam@clusterfs.com>
41  * Author: Andreas Dilger <adilger@clusterfs.com>
42  * Author: Phil Schwan <phil@clusterfs.com>
43  * Author: Mike Shaver <shaver@clusterfs.com>
44  * Author: Nikita Danilov <nikita@clusterfs.com>
45  * Author: Huang Hua <huanghua@clusterfs.com>
46  * Author: Yury Umanets <umka@clusterfs.com>
47  */
48
49 #define DEBUG_SUBSYSTEM S_MDS
50
51 #include <linux/module.h>
52 /*
53  * struct OBD_{ALLOC,FREE}*()
54  */
55 #include <obd_support.h>
56 /* struct ptlrpc_request */
57 #include <lustre_net.h>
58 /* struct obd_export */
59 #include <lustre_export.h>
60 /* struct obd_device */
61 #include <obd.h>
62 /* lu2dt_dev() */
63 #include <dt_object.h>
64 #include <lustre_mds.h>
65 #include <lustre_mdt.h>
66 #include <lustre_log.h>
67 #include "mdt_internal.h"
68 #ifdef HAVE_QUOTA_SUPPORT
69 # include <lustre_quota.h>
70 #endif
71 #include <lustre_acl.h>
72 #include <lustre_param.h>
73
74 mdl_mode_t mdt_mdl_lock_modes[] = {
75         [LCK_MINMODE] = MDL_MINMODE,
76         [LCK_EX]      = MDL_EX,
77         [LCK_PW]      = MDL_PW,
78         [LCK_PR]      = MDL_PR,
79         [LCK_CW]      = MDL_CW,
80         [LCK_CR]      = MDL_CR,
81         [LCK_NL]      = MDL_NL,
82         [LCK_GROUP]   = MDL_GROUP
83 };
84
85 ldlm_mode_t mdt_dlm_lock_modes[] = {
86         [MDL_MINMODE] = LCK_MINMODE,
87         [MDL_EX]      = LCK_EX,
88         [MDL_PW]      = LCK_PW,
89         [MDL_PR]      = LCK_PR,
90         [MDL_CW]      = LCK_CW,
91         [MDL_CR]      = LCK_CR,
92         [MDL_NL]      = LCK_NL,
93         [MDL_GROUP]   = LCK_GROUP
94 };
95
96 /*
97  * Initialized in mdt_mod_init().
98  */
99 static unsigned long mdt_num_threads;
100 CFS_MODULE_PARM(mdt_num_threads, "ul", ulong, 0444,
101                 "number of MDS service threads to start "
102                 "(deprecated in favor of mds_num_threads)");
103
104 static unsigned long mds_num_threads;
105 CFS_MODULE_PARM(mds_num_threads, "ul", ulong, 0444,
106                 "number of MDS service threads to start");
107
108 static char *mds_num_cpts;
109 CFS_MODULE_PARM(mds_num_cpts, "c", charp, 0444,
110                 "CPU partitions MDS threads should run on");
111
112 static unsigned long mds_rdpg_num_threads;
113 CFS_MODULE_PARM(mds_rdpg_num_threads, "ul", ulong, 0444,
114                 "number of MDS readpage service threads to start");
115
116 static char *mds_rdpg_num_cpts;
117 CFS_MODULE_PARM(mds_rdpg_num_cpts, "c", charp, 0444,
118                 "CPU partitions MDS readpage threads should run on");
119
120 /* NB: these two should be removed along with setattr service in the future */
121 static unsigned long mds_attr_num_threads;
122 CFS_MODULE_PARM(mds_attr_num_threads, "ul", ulong, 0444,
123                 "number of MDS setattr service threads to start");
124
125 static char *mds_attr_num_cpts;
126 CFS_MODULE_PARM(mds_attr_num_cpts, "c", charp, 0444,
127                 "CPU partitions MDS setattr threads should run on");
128
129 /* ptlrpc request handler for MDT. All handlers are
130  * grouped into several slices - struct mdt_opc_slice,
131  * and stored in an array - mdt_handlers[].
132  */
133 struct mdt_handler {
134         /* The name of this handler. */
135         const char *mh_name;
136         /* Fail id for this handler, checked at the beginning of this handler*/
137         int         mh_fail_id;
138         /* Operation code for this handler */
139         __u32       mh_opc;
140         /* flags are listed in enum mdt_handler_flags below. */
141         __u32       mh_flags;
142         /* The actual handler function to execute. */
143         int (*mh_act)(struct mdt_thread_info *info);
144         /* Request format for this request. */
145         const struct req_format *mh_fmt;
146 };
147
148 enum mdt_handler_flags {
149         /*
150          * struct mdt_body is passed in the incoming message, and object
151          * identified by this fid exists on disk.
152          *
153          * "habeo corpus" == "I have a body"
154          */
155         HABEO_CORPUS = (1 << 0),
156         /*
157          * struct ldlm_request is passed in the incoming message.
158          *
159          * "habeo clavis" == "I have a key"
160          */
161         HABEO_CLAVIS = (1 << 1),
162         /*
163          * this request has fixed reply format, so that reply message can be
164          * packed by generic code.
165          *
166          * "habeo refero" == "I have a reply"
167          */
168         HABEO_REFERO = (1 << 2),
169         /*
170          * this request will modify something, so check whether the filesystem
171          * is readonly or not, then return -EROFS to client asap if necessary.
172          *
173          * "mutabor" == "I shall modify"
174          */
175         MUTABOR      = (1 << 3)
176 };
177
178 struct mdt_opc_slice {
179         __u32               mos_opc_start;
180         int                 mos_opc_end;
181         struct mdt_handler *mos_hs;
182 };
183
184 static struct mdt_opc_slice mdt_regular_handlers[];
185 static struct mdt_opc_slice mdt_readpage_handlers[];
186 static struct mdt_opc_slice mdt_xmds_handlers[];
187 static struct mdt_opc_slice mdt_seq_handlers[];
188 static struct mdt_opc_slice mdt_fld_handlers[];
189
190 static struct mdt_device *mdt_dev(struct lu_device *d);
191 static int mdt_regular_handle(struct ptlrpc_request *req);
192 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags);
193 static int mdt_fid2path(const struct lu_env *env, struct mdt_device *mdt,
194                         struct getinfo_fid2path *fp);
195
196 static const struct lu_object_operations mdt_obj_ops;
197
198 /* Slab for MDT object allocation */
199 static cfs_mem_cache_t *mdt_object_kmem;
200
201 static struct lu_kmem_descr mdt_caches[] = {
202         {
203                 .ckd_cache = &mdt_object_kmem,
204                 .ckd_name  = "mdt_obj",
205                 .ckd_size  = sizeof(struct mdt_object)
206         },
207         {
208                 .ckd_cache = NULL
209         }
210 };
211
212 int mdt_get_disposition(struct ldlm_reply *rep, int flag)
213 {
214         if (!rep)
215                 return 0;
216         return (rep->lock_policy_res1 & flag);
217 }
218
219 void mdt_clear_disposition(struct mdt_thread_info *info,
220                            struct ldlm_reply *rep, int flag)
221 {
222         if (info)
223                 info->mti_opdata &= ~flag;
224         if (rep)
225                 rep->lock_policy_res1 &= ~flag;
226 }
227
228 void mdt_set_disposition(struct mdt_thread_info *info,
229                          struct ldlm_reply *rep, int flag)
230 {
231         if (info)
232                 info->mti_opdata |= flag;
233         if (rep)
234                 rep->lock_policy_res1 |= flag;
235 }
236
237 void mdt_lock_reg_init(struct mdt_lock_handle *lh, ldlm_mode_t lm)
238 {
239         lh->mlh_pdo_hash = 0;
240         lh->mlh_reg_mode = lm;
241         lh->mlh_type = MDT_REG_LOCK;
242 }
243
244 void mdt_lock_pdo_init(struct mdt_lock_handle *lh, ldlm_mode_t lm,
245                        const char *name, int namelen)
246 {
247         lh->mlh_reg_mode = lm;
248         lh->mlh_type = MDT_PDO_LOCK;
249
250         if (name != NULL && (name[0] != '\0')) {
251                 LASSERT(namelen > 0);
252                 lh->mlh_pdo_hash = full_name_hash(name, namelen);
253         } else {
254                 LASSERT(namelen == 0);
255                 lh->mlh_pdo_hash = 0ull;
256         }
257 }
258
259 static void mdt_lock_pdo_mode(struct mdt_thread_info *info, struct mdt_object *o,
260                               struct mdt_lock_handle *lh)
261 {
262         mdl_mode_t mode;
263         ENTRY;
264
265         /*
266          * Any dir access needs couple of locks:
267          *
268          * 1) on part of dir we gonna take lookup/modify;
269          *
270          * 2) on whole dir to protect it from concurrent splitting and/or to
271          * flush client's cache for readdir().
272          *
273          * so, for a given mode and object this routine decides what lock mode
274          * to use for lock #2:
275          *
276          * 1) if caller's gonna lookup in dir then we need to protect dir from
277          * being splitted only - LCK_CR
278          *
279          * 2) if caller's gonna modify dir then we need to protect dir from
280          * being splitted and to flush cache - LCK_CW
281          *
282          * 3) if caller's gonna modify dir and that dir seems ready for
283          * splitting then we need to protect it from any type of access
284          * (lookup/modify/split) - LCK_EX --bzzz
285          */
286
287         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
288         LASSERT(lh->mlh_pdo_mode == LCK_MINMODE);
289
290         /*
291          * Ask underlaying level its opinion about preferable PDO lock mode
292          * having access type passed as regular lock mode:
293          *
294          * - MDL_MINMODE means that lower layer does not want to specify lock
295          * mode;
296          *
297          * - MDL_NL means that no PDO lock should be taken. This is used in some
298          * cases. Say, for non-splittable directories no need to use PDO locks
299          * at all.
300          */
301         mode = mdo_lock_mode(info->mti_env, mdt_object_child(o),
302                              mdt_dlm_mode2mdl_mode(lh->mlh_reg_mode));
303
304         if (mode != MDL_MINMODE) {
305                 lh->mlh_pdo_mode = mdt_mdl_mode2dlm_mode(mode);
306         } else {
307                 /*
308                  * Lower layer does not want to specify locking mode. We do it
309                  * our selves. No special protection is needed, just flush
310                  * client's cache on modification and allow concurrent
311                  * mondification.
312                  */
313                 switch (lh->mlh_reg_mode) {
314                 case LCK_EX:
315                         lh->mlh_pdo_mode = LCK_EX;
316                         break;
317                 case LCK_PR:
318                         lh->mlh_pdo_mode = LCK_CR;
319                         break;
320                 case LCK_PW:
321                         lh->mlh_pdo_mode = LCK_CW;
322                         break;
323                 default:
324                         CERROR("Not expected lock type (0x%x)\n",
325                                (int)lh->mlh_reg_mode);
326                         LBUG();
327                 }
328         }
329
330         LASSERT(lh->mlh_pdo_mode != LCK_MINMODE);
331         EXIT;
332 }
333
334 static int mdt_getstatus(struct mdt_thread_info *info)
335 {
336         struct mdt_device *mdt  = info->mti_mdt;
337         struct md_device  *next = mdt->mdt_child;
338         struct mdt_body   *repbody;
339         int                rc;
340
341         ENTRY;
342
343         rc = mdt_check_ucred(info);
344         if (rc)
345                 RETURN(err_serious(rc));
346
347         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETSTATUS_PACK))
348                 RETURN(err_serious(-ENOMEM));
349
350         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
351         rc = next->md_ops->mdo_root_get(info->mti_env, next, &repbody->fid1);
352         if (rc != 0)
353                 RETURN(rc);
354
355         repbody->valid |= OBD_MD_FLID;
356
357         if (mdt->mdt_opts.mo_mds_capa &&
358             info->mti_exp->exp_connect_flags & OBD_CONNECT_MDS_CAPA) {
359                 struct mdt_object  *root;
360                 struct lustre_capa *capa;
361
362                 root = mdt_object_find(info->mti_env, mdt, &repbody->fid1);
363                 if (IS_ERR(root))
364                         RETURN(PTR_ERR(root));
365
366                 capa = req_capsule_server_get(info->mti_pill, &RMF_CAPA1);
367                 LASSERT(capa);
368                 capa->lc_opc = CAPA_OPC_MDS_DEFAULT;
369                 rc = mo_capa_get(info->mti_env, mdt_object_child(root), capa,
370                                  0);
371                 mdt_object_put(info->mti_env, root);
372                 if (rc == 0)
373                         repbody->valid |= OBD_MD_FLMDSCAPA;
374         }
375
376         RETURN(rc);
377 }
378
379 static int mdt_statfs(struct mdt_thread_info *info)
380 {
381         struct ptlrpc_request           *req = mdt_info_req(info);
382         struct md_device                *next = info->mti_mdt->mdt_child;
383         struct ptlrpc_service_part      *svcpt;
384         struct obd_statfs               *osfs;
385         int                             rc;
386
387         ENTRY;
388
389         svcpt = info->mti_pill->rc_req->rq_rqbd->rqbd_svcpt;
390
391         /* This will trigger a watchdog timeout */
392         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_STATFS_LCW_SLEEP,
393                          (MDT_SERVICE_WATCHDOG_FACTOR *
394                           at_get(&svcpt->scp_at_estimate)) + 1);
395
396         rc = mdt_check_ucred(info);
397         if (rc)
398                 RETURN(err_serious(rc));
399
400         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_STATFS_PACK))
401                 RETURN(err_serious(-ENOMEM));
402
403         osfs = req_capsule_server_get(info->mti_pill, &RMF_OBD_STATFS);
404         if (!osfs)
405                 RETURN(-EPROTO);
406
407         /** statfs information are cached in the mdt_device */
408         if (cfs_time_before_64(info->mti_mdt->mdt_osfs_age,
409                                cfs_time_shift_64(-OBD_STATFS_CACHE_SECONDS))) {
410                 /** statfs data is too old, get up-to-date one */
411                 rc = next->md_ops->mdo_statfs(info->mti_env, next, osfs);
412                 if (rc)
413                         RETURN(rc);
414                 cfs_spin_lock(&info->mti_mdt->mdt_osfs_lock);
415                 info->mti_mdt->mdt_osfs = *osfs;
416                 info->mti_mdt->mdt_osfs_age = cfs_time_current_64();
417                 cfs_spin_unlock(&info->mti_mdt->mdt_osfs_lock);
418         } else {
419                 /** use cached statfs data */
420                 cfs_spin_lock(&info->mti_mdt->mdt_osfs_lock);
421                 *osfs = info->mti_mdt->mdt_osfs;
422                 cfs_spin_unlock(&info->mti_mdt->mdt_osfs_lock);
423         }
424
425         if (rc == 0)
426                 mdt_counter_incr(req, LPROC_MDT_STATFS);
427
428         RETURN(rc);
429 }
430
431 /**
432  * Pack SOM attributes into the reply.
433  * Call under a DLM UPDATE lock.
434  */
435 static void mdt_pack_size2body(struct mdt_thread_info *info,
436                                struct mdt_object *mo)
437 {
438         struct mdt_body *b;
439         struct md_attr *ma = &info->mti_attr;
440
441         LASSERT(ma->ma_attr.la_valid & LA_MODE);
442         b = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
443
444         /* Check if Size-on-MDS is supported, if this is a regular file,
445          * if SOM is enabled on the object and if SOM cache exists and valid.
446          * Otherwise do not pack Size-on-MDS attributes to the reply. */
447         if (!(mdt_conn_flags(info) & OBD_CONNECT_SOM) ||
448             !S_ISREG(ma->ma_attr.la_mode) ||
449             !mdt_object_is_som_enabled(mo) ||
450             !(ma->ma_valid & MA_SOM))
451                 return;
452
453         b->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
454         b->size = ma->ma_som->msd_size;
455         b->blocks = ma->ma_som->msd_blocks;
456 }
457
458 void mdt_pack_attr2body(struct mdt_thread_info *info, struct mdt_body *b,
459                         const struct lu_attr *attr, const struct lu_fid *fid)
460 {
461         struct md_attr *ma = &info->mti_attr;
462
463         LASSERT(ma->ma_valid & MA_INODE);
464
465         b->atime      = attr->la_atime;
466         b->mtime      = attr->la_mtime;
467         b->ctime      = attr->la_ctime;
468         b->mode       = attr->la_mode;
469         b->size       = attr->la_size;
470         b->blocks     = attr->la_blocks;
471         b->uid        = attr->la_uid;
472         b->gid        = attr->la_gid;
473         b->flags      = attr->la_flags;
474         b->nlink      = attr->la_nlink;
475         b->rdev       = attr->la_rdev;
476
477         /*XXX should pack the reply body according to lu_valid*/
478         b->valid |= OBD_MD_FLCTIME | OBD_MD_FLUID   |
479                     OBD_MD_FLGID   | OBD_MD_FLTYPE  |
480                     OBD_MD_FLMODE  | OBD_MD_FLNLINK | OBD_MD_FLFLAGS |
481                     OBD_MD_FLATIME | OBD_MD_FLMTIME ;
482
483         if (!S_ISREG(attr->la_mode)) {
484                 b->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS | OBD_MD_FLRDEV;
485         } else if (ma->ma_need & MA_LOV && ma->ma_lmm_size == 0) {
486                 /* means no objects are allocated on osts. */
487                 LASSERT(!(ma->ma_valid & MA_LOV));
488                 /* just ignore blocks occupied by extend attributes on MDS */
489                 b->blocks = 0;
490                 /* if no object is allocated on osts, the size on mds is valid. b=22272 */
491                 b->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
492         }
493
494         if (fid) {
495                 b->fid1 = *fid;
496                 b->valid |= OBD_MD_FLID;
497
498                 /* FIXME: these should be fixed when new igif ready.*/
499                 b->ino  =  fid_oid(fid);       /* 1.6 compatibility */
500                 b->generation = fid_ver(fid);  /* 1.6 compatibility */
501                 b->valid |= OBD_MD_FLGENER;    /* 1.6 compatibility */
502
503                 CDEBUG(D_INODE, DFID": nlink=%d, mode=%o, size="LPU64"\n",
504                                 PFID(fid), b->nlink, b->mode, b->size);
505         }
506
507         if (info)
508                 mdt_body_reverse_idmap(info, b);
509
510         if (b->valid & OBD_MD_FLSIZE)
511                 CDEBUG(D_VFSTRACE, DFID": returning size %llu\n",
512                        PFID(fid), (unsigned long long)b->size);
513 }
514
515 static inline int mdt_body_has_lov(const struct lu_attr *la,
516                                    const struct mdt_body *body)
517 {
518         return ((S_ISREG(la->la_mode) && (body->valid & OBD_MD_FLEASIZE)) ||
519                 (S_ISDIR(la->la_mode) && (body->valid & OBD_MD_FLDIREA )) );
520 }
521
522 void mdt_client_compatibility(struct mdt_thread_info *info)
523 {
524         struct mdt_body       *body;
525         struct ptlrpc_request *req = mdt_info_req(info);
526         struct obd_export     *exp = req->rq_export;
527         struct md_attr        *ma = &info->mti_attr;
528         struct lu_attr        *la = &ma->ma_attr;
529         ENTRY;
530
531         if (exp->exp_connect_flags & OBD_CONNECT_LAYOUTLOCK)
532                 /* the client can deal with 16-bit lmm_stripe_count */
533                 RETURN_EXIT;
534
535         body = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
536
537         if (!mdt_body_has_lov(la, body))
538                 RETURN_EXIT;
539
540         /* now we have a reply with a lov for a client not compatible with the
541          * layout lock so we have to clean the layout generation number */
542         if (S_ISREG(la->la_mode))
543                 ma->ma_lmm->lmm_layout_gen = 0;
544         EXIT;
545 }
546
547
548 static int mdt_getattr_internal(struct mdt_thread_info *info,
549                                 struct mdt_object *o, int ma_need)
550 {
551         struct md_object        *next = mdt_object_child(o);
552         const struct mdt_body   *reqbody = info->mti_body;
553         struct ptlrpc_request   *req = mdt_info_req(info);
554         struct md_attr          *ma = &info->mti_attr;
555         struct lu_attr          *la = &ma->ma_attr;
556         struct req_capsule      *pill = info->mti_pill;
557         const struct lu_env     *env = info->mti_env;
558         struct mdt_body         *repbody;
559         struct lu_buf           *buffer = &info->mti_buf;
560         int                     rc;
561         ENTRY;
562
563         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETATTR_PACK))
564                 RETURN(err_serious(-ENOMEM));
565
566         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
567
568         ma->ma_valid = 0;
569
570         rc = mdt_object_exists(o);
571         if (rc < 0) {
572                 /* This object is located on remote node.*/
573                 repbody->fid1 = *mdt_object_fid(o);
574                 repbody->valid = OBD_MD_FLID | OBD_MD_MDS;
575                 GOTO(out, rc = 0);
576         }
577
578         buffer->lb_buf = req_capsule_server_get(pill, &RMF_MDT_MD);
579         buffer->lb_len = req_capsule_get_size(pill, &RMF_MDT_MD, RCL_SERVER);
580
581         /* If it is dir object and client require MEA, then we got MEA */
582         if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
583             reqbody->valid & OBD_MD_MEA) {
584                 /* Assumption: MDT_MD size is enough for lmv size. */
585                 ma->ma_lmv = buffer->lb_buf;
586                 ma->ma_lmv_size = buffer->lb_len;
587                 ma->ma_need = MA_LMV | MA_INODE;
588         } else {
589                 ma->ma_lmm = buffer->lb_buf;
590                 ma->ma_lmm_size = buffer->lb_len;
591                 ma->ma_need = MA_LOV | MA_INODE;
592         }
593
594         if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
595             reqbody->valid & OBD_MD_FLDIREA  &&
596             lustre_msg_get_opc(req->rq_reqmsg) == MDS_GETATTR) {
597                 /* get default stripe info for this dir. */
598                 ma->ma_need |= MA_LOV_DEF;
599         }
600         ma->ma_need |= ma_need;
601         if (ma->ma_need & MA_SOM)
602                 ma->ma_som = &info->mti_u.som.data;
603
604         rc = mo_attr_get(env, next, ma);
605         if (unlikely(rc)) {
606                 CERROR("getattr error for "DFID": %d\n",
607                         PFID(mdt_object_fid(o)), rc);
608                 RETURN(rc);
609         }
610
611         if (likely(ma->ma_valid & MA_INODE))
612                 mdt_pack_attr2body(info, repbody, la, mdt_object_fid(o));
613         else
614                 RETURN(-EFAULT);
615
616         if (mdt_body_has_lov(la, reqbody)) {
617                 if (ma->ma_valid & MA_LOV) {
618                         LASSERT(ma->ma_lmm_size);
619                         mdt_dump_lmm(D_INFO, ma->ma_lmm);
620                         repbody->eadatasize = ma->ma_lmm_size;
621                         if (S_ISDIR(la->la_mode))
622                                 repbody->valid |= OBD_MD_FLDIREA;
623                         else
624                                 repbody->valid |= OBD_MD_FLEASIZE;
625                 }
626                 if (ma->ma_valid & MA_LMV) {
627                         LASSERT(S_ISDIR(la->la_mode));
628                         repbody->eadatasize = ma->ma_lmv_size;
629                         repbody->valid |= (OBD_MD_FLDIREA|OBD_MD_MEA);
630                 }
631         } else if (S_ISLNK(la->la_mode) &&
632                    reqbody->valid & OBD_MD_LINKNAME) {
633                 buffer->lb_buf = ma->ma_lmm;
634                 /* eadatasize from client includes NULL-terminator, so
635                  * there is no need to read it */
636                 buffer->lb_len = reqbody->eadatasize - 1;
637                 rc = mo_readlink(env, next, buffer);
638                 if (unlikely(rc <= 0)) {
639                         CERROR("readlink failed: %d\n", rc);
640                         rc = -EFAULT;
641                 } else {
642                         int print_limit = min_t(int, CFS_PAGE_SIZE - 128, rc);
643
644                         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READLINK_EPROTO))
645                                 rc -= 2;
646                         repbody->valid |= OBD_MD_LINKNAME;
647                         /* we need to report back size with NULL-terminator
648                          * because client expects that */
649                         repbody->eadatasize = rc + 1;
650                         if (repbody->eadatasize != reqbody->eadatasize)
651                                 CERROR("Read shorter symlink %d, expected %d\n",
652                                        rc, reqbody->eadatasize - 1);
653                         /* NULL terminate */
654                         ((char *)ma->ma_lmm)[rc] = 0;
655
656                         /* If the total CDEBUG() size is larger than a page, it
657                          * will print a warning to the console, avoid this by
658                          * printing just the last part of the symlink. */
659                         CDEBUG(D_INODE, "symlink dest %s%.*s, len = %d\n",
660                                print_limit < rc ? "..." : "", print_limit,
661                                (char *)ma->ma_lmm + rc - print_limit, rc);
662                         rc = 0;
663                 }
664         }
665
666         if (reqbody->valid & OBD_MD_FLMODEASIZE) {
667                 repbody->max_cookiesize = info->mti_mdt->mdt_max_cookiesize;
668                 repbody->max_mdsize = info->mti_mdt->mdt_max_mdsize;
669                 repbody->valid |= OBD_MD_FLMODEASIZE;
670                 CDEBUG(D_INODE, "I am going to change the MAX_MD_SIZE & "
671                        "MAX_COOKIE to : %d:%d\n", repbody->max_mdsize,
672                        repbody->max_cookiesize);
673         }
674
675         if (exp_connect_rmtclient(info->mti_exp) &&
676             reqbody->valid & OBD_MD_FLRMTPERM) {
677                 void *buf = req_capsule_server_get(pill, &RMF_ACL);
678
679                 /* mdt_getattr_lock only */
680                 rc = mdt_pack_remote_perm(info, o, buf);
681                 if (rc) {
682                         repbody->valid &= ~OBD_MD_FLRMTPERM;
683                         repbody->aclsize = 0;
684                         RETURN(rc);
685                 } else {
686                         repbody->valid |= OBD_MD_FLRMTPERM;
687                         repbody->aclsize = sizeof(struct mdt_remote_perm);
688                 }
689         }
690 #ifdef CONFIG_FS_POSIX_ACL
691         else if ((req->rq_export->exp_connect_flags & OBD_CONNECT_ACL) &&
692                  (reqbody->valid & OBD_MD_FLACL)) {
693                 buffer->lb_buf = req_capsule_server_get(pill, &RMF_ACL);
694                 buffer->lb_len = req_capsule_get_size(pill,
695                                                       &RMF_ACL, RCL_SERVER);
696                 if (buffer->lb_len > 0) {
697                         rc = mo_xattr_get(env, next, buffer,
698                                           XATTR_NAME_ACL_ACCESS);
699                         if (rc < 0) {
700                                 if (rc == -ENODATA) {
701                                         repbody->aclsize = 0;
702                                         repbody->valid |= OBD_MD_FLACL;
703                                         rc = 0;
704                                 } else if (rc == -EOPNOTSUPP) {
705                                         rc = 0;
706                                 } else {
707                                         CERROR("got acl size: %d\n", rc);
708                                 }
709                         } else {
710                                 repbody->aclsize = rc;
711                                 repbody->valid |= OBD_MD_FLACL;
712                                 rc = 0;
713                         }
714                 }
715         }
716 #endif
717
718         if (reqbody->valid & OBD_MD_FLMDSCAPA &&
719             info->mti_mdt->mdt_opts.mo_mds_capa &&
720             info->mti_exp->exp_connect_flags & OBD_CONNECT_MDS_CAPA) {
721                 struct lustre_capa *capa;
722
723                 capa = req_capsule_server_get(pill, &RMF_CAPA1);
724                 LASSERT(capa);
725                 capa->lc_opc = CAPA_OPC_MDS_DEFAULT;
726                 rc = mo_capa_get(env, next, capa, 0);
727                 if (rc)
728                         RETURN(rc);
729                 repbody->valid |= OBD_MD_FLMDSCAPA;
730         }
731
732 out:
733         if (rc == 0)
734                 mdt_counter_incr(req, LPROC_MDT_GETATTR);
735
736         RETURN(rc);
737 }
738
739 static int mdt_renew_capa(struct mdt_thread_info *info)
740 {
741         struct mdt_object  *obj = info->mti_object;
742         struct mdt_body    *body;
743         struct lustre_capa *capa, *c;
744         int rc;
745         ENTRY;
746
747         /* if object doesn't exist, or server has disabled capability,
748          * return directly, client will find body->valid OBD_MD_FLOSSCAPA
749          * flag not set.
750          */
751         if (!obj || !info->mti_mdt->mdt_opts.mo_oss_capa ||
752             !(info->mti_exp->exp_connect_flags & OBD_CONNECT_OSS_CAPA))
753                 RETURN(0);
754
755         body = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
756         LASSERT(body != NULL);
757
758         c = req_capsule_client_get(info->mti_pill, &RMF_CAPA1);
759         LASSERT(c);
760
761         capa = req_capsule_server_get(info->mti_pill, &RMF_CAPA2);
762         LASSERT(capa);
763
764         *capa = *c;
765         rc = mo_capa_get(info->mti_env, mdt_object_child(obj), capa, 1);
766         if (rc == 0)
767                 body->valid |= OBD_MD_FLOSSCAPA;
768         RETURN(rc);
769 }
770
771 static int mdt_getattr(struct mdt_thread_info *info)
772 {
773         struct mdt_object       *obj = info->mti_object;
774         struct req_capsule      *pill = info->mti_pill;
775         struct mdt_body         *reqbody;
776         struct mdt_body         *repbody;
777         mode_t                   mode;
778         int rc, rc2;
779         ENTRY;
780
781         reqbody = req_capsule_client_get(pill, &RMF_MDT_BODY);
782         LASSERT(reqbody);
783
784         if (reqbody->valid & OBD_MD_FLOSSCAPA) {
785                 rc = req_capsule_server_pack(pill);
786                 if (unlikely(rc))
787                         RETURN(err_serious(rc));
788                 rc = mdt_renew_capa(info);
789                 GOTO(out_shrink, rc);
790         }
791
792         LASSERT(obj != NULL);
793         LASSERT(lu_object_assert_exists(&obj->mot_obj.mo_lu));
794
795         mode = lu_object_attr(&obj->mot_obj.mo_lu);
796
797         /* old clients may not report needed easize, use max value then */
798         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
799                              reqbody->eadatasize == 0 ?
800                              info->mti_mdt->mdt_max_mdsize :
801                              reqbody->eadatasize);
802
803         rc = req_capsule_server_pack(pill);
804         if (unlikely(rc != 0))
805                 RETURN(err_serious(rc));
806
807         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
808         LASSERT(repbody != NULL);
809         repbody->eadatasize = 0;
810         repbody->aclsize = 0;
811
812         if (reqbody->valid & OBD_MD_FLRMTPERM)
813                 rc = mdt_init_ucred(info, reqbody);
814         else
815                 rc = mdt_check_ucred(info);
816         if (unlikely(rc))
817                 GOTO(out_shrink, rc);
818
819         info->mti_spec.sp_ck_split = !!(reqbody->valid & OBD_MD_FLCKSPLIT);
820         info->mti_cross_ref = !!(reqbody->valid & OBD_MD_FLCROSSREF);
821
822         /*
823          * Don't check capability at all, because rename might getattr for
824          * remote obj, and at that time no capability is available.
825          */
826         mdt_set_capainfo(info, 1, &reqbody->fid1, BYPASS_CAPA);
827         rc = mdt_getattr_internal(info, obj, 0);
828         if (reqbody->valid & OBD_MD_FLRMTPERM)
829                 mdt_exit_ucred(info);
830         EXIT;
831 out_shrink:
832         mdt_client_compatibility(info);
833         rc2 = mdt_fix_reply(info);
834         if (rc == 0)
835                 rc = rc2;
836         return rc;
837 }
838
839 static int mdt_is_subdir(struct mdt_thread_info *info)
840 {
841         struct mdt_object     *o = info->mti_object;
842         struct req_capsule    *pill = info->mti_pill;
843         const struct mdt_body *body = info->mti_body;
844         struct mdt_body       *repbody;
845         int                    rc;
846         ENTRY;
847
848         LASSERT(o != NULL);
849
850         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
851
852         /*
853          * We save last checked parent fid to @repbody->fid1 for remote
854          * directory case.
855          */
856         LASSERT(fid_is_sane(&body->fid2));
857         LASSERT(mdt_object_exists(o) > 0);
858         rc = mdo_is_subdir(info->mti_env, mdt_object_child(o),
859                            &body->fid2, &repbody->fid1);
860         if (rc == 0 || rc == -EREMOTE)
861                 repbody->valid |= OBD_MD_FLID;
862
863         RETURN(rc);
864 }
865
866 static int mdt_raw_lookup(struct mdt_thread_info *info,
867                           struct mdt_object *parent,
868                           const struct lu_name *lname,
869                           struct ldlm_reply *ldlm_rep)
870 {
871         struct md_object *next = mdt_object_child(info->mti_object);
872         const struct mdt_body *reqbody = info->mti_body;
873         struct lu_fid *child_fid = &info->mti_tmp_fid1;
874         struct mdt_body *repbody;
875         int rc;
876         ENTRY;
877
878         if (reqbody->valid != OBD_MD_FLID)
879                 RETURN(0);
880
881         LASSERT(!info->mti_cross_ref);
882
883         /* Only got the fid of this obj by name */
884         fid_zero(child_fid);
885         rc = mdo_lookup(info->mti_env, next, lname, child_fid,
886                         &info->mti_spec);
887 #if 0
888         /* XXX is raw_lookup possible as intent operation? */
889         if (rc != 0) {
890                 if (rc == -ENOENT)
891                         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_NEG);
892                 RETURN(rc);
893         } else
894                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
895
896         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
897 #endif
898         if (rc == 0) {
899                 repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
900                 repbody->fid1 = *child_fid;
901                 repbody->valid = OBD_MD_FLID;
902         }
903         RETURN(1);
904 }
905
906 /*
907  * UPDATE lock should be taken against parent, and be release before exit;
908  * child_bits lock should be taken against child, and be returned back:
909  *            (1)normal request should release the child lock;
910  *            (2)intent request will grant the lock to client.
911  */
912 static int mdt_getattr_name_lock(struct mdt_thread_info *info,
913                                  struct mdt_lock_handle *lhc,
914                                  __u64 child_bits,
915                                  struct ldlm_reply *ldlm_rep)
916 {
917         struct ptlrpc_request  *req       = mdt_info_req(info);
918         struct mdt_body        *reqbody   = NULL;
919         struct mdt_object      *parent    = info->mti_object;
920         struct mdt_object      *child;
921         struct md_object       *next      = mdt_object_child(parent);
922         struct lu_fid          *child_fid = &info->mti_tmp_fid1;
923         struct lu_name         *lname     = NULL;
924         const char             *name      = NULL;
925         int                     namelen   = 0;
926         struct mdt_lock_handle *lhp       = NULL;
927         struct ldlm_lock       *lock;
928         struct ldlm_res_id     *res_id;
929         int                     is_resent;
930         int                     ma_need = 0;
931         int                     rc;
932
933         ENTRY;
934
935         is_resent = lustre_handle_is_used(&lhc->mlh_reg_lh);
936         LASSERT(ergo(is_resent,
937                      lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT));
938
939         LASSERT(parent != NULL);
940         name = req_capsule_client_get(info->mti_pill, &RMF_NAME);
941         if (name == NULL)
942                 RETURN(err_serious(-EFAULT));
943
944         namelen = req_capsule_get_size(info->mti_pill, &RMF_NAME,
945                                        RCL_CLIENT) - 1;
946         if (!info->mti_cross_ref) {
947                 /*
948                  * XXX: Check for "namelen == 0" is for getattr by fid
949                  * (OBD_CONNECT_ATTRFID), otherwise do not allow empty name,
950                  * that is the name must contain at least one character and
951                  * the terminating '\0'
952                  */
953                 if (namelen == 0) {
954                         reqbody = req_capsule_client_get(info->mti_pill,
955                                                          &RMF_MDT_BODY);
956                         if (unlikely(reqbody == NULL))
957                                 RETURN(err_serious(-EFAULT));
958
959                         if (unlikely(!fid_is_sane(&reqbody->fid2)))
960                                 RETURN(err_serious(-EINVAL));
961
962                         name = NULL;
963                         CDEBUG(D_INODE, "getattr with lock for "DFID"/"DFID", "
964                                "ldlm_rep = %p\n",
965                                PFID(mdt_object_fid(parent)),
966                                PFID(&reqbody->fid2), ldlm_rep);
967                 } else {
968                         lname = mdt_name(info->mti_env, (char *)name, namelen);
969                         CDEBUG(D_INODE, "getattr with lock for "DFID"/%s, "
970                                "ldlm_rep = %p\n", PFID(mdt_object_fid(parent)),
971                                name, ldlm_rep);
972                 }
973         }
974         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_EXECD);
975
976         rc = mdt_object_exists(parent);
977         if (unlikely(rc == 0)) {
978                 LU_OBJECT_DEBUG(D_INODE, info->mti_env,
979                                 &parent->mot_obj.mo_lu,
980                                 "Parent doesn't exist!\n");
981                 RETURN(-ESTALE);
982         } else if (!info->mti_cross_ref) {
983                 LASSERTF(rc > 0, "Parent "DFID" is on remote server\n",
984                          PFID(mdt_object_fid(parent)));
985         }
986         if (lname) {
987                 rc = mdt_raw_lookup(info, parent, lname, ldlm_rep);
988                 if (rc != 0) {
989                         if (rc > 0)
990                                 rc = 0;
991                         RETURN(rc);
992                 }
993         }
994
995         if (info->mti_cross_ref) {
996                 /* Only getattr on the child. Parent is on another node. */
997                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
998                 child = parent;
999                 CDEBUG(D_INODE, "partial getattr_name child_fid = "DFID", "
1000                        "ldlm_rep=%p\n", PFID(mdt_object_fid(child)), ldlm_rep);
1001
1002                 if (is_resent) {
1003                         /* Do not take lock for resent case. */
1004                         lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
1005                         LASSERTF(lock != NULL, "Invalid lock handle "LPX64"\n",
1006                                  lhc->mlh_reg_lh.cookie);
1007                         LASSERT(fid_res_name_eq(mdt_object_fid(child),
1008                                                 &lock->l_resource->lr_name));
1009                         LDLM_LOCK_PUT(lock);
1010                         rc = 0;
1011                 } else {
1012                         mdt_lock_handle_init(lhc);
1013                         mdt_lock_reg_init(lhc, LCK_PR);
1014
1015                         /*
1016                          * Object's name is on another MDS, no lookup lock is
1017                          * needed here but update is.
1018                          */
1019                         child_bits &= ~MDS_INODELOCK_LOOKUP;
1020                         child_bits |= MDS_INODELOCK_UPDATE;
1021
1022                         rc = mdt_object_lock(info, child, lhc, child_bits,
1023                                              MDT_LOCAL_LOCK);
1024                 }
1025                 if (rc == 0) {
1026                         /* Finally, we can get attr for child. */
1027                         mdt_set_capainfo(info, 0, mdt_object_fid(child),
1028                                          BYPASS_CAPA);
1029                         rc = mdt_getattr_internal(info, child, 0);
1030                         if (unlikely(rc != 0))
1031                                 mdt_object_unlock(info, child, lhc, 1);
1032                 }
1033                 RETURN(rc);
1034         }
1035
1036         if (lname) {
1037                 /* step 1: lock parent only if parent is a directory */
1038                 if (S_ISDIR(lu_object_attr(&parent->mot_obj.mo_lu))) {
1039                         lhp = &info->mti_lh[MDT_LH_PARENT];
1040                         mdt_lock_pdo_init(lhp, LCK_PR, name, namelen);
1041                         rc = mdt_object_lock(info, parent, lhp,
1042                                              MDS_INODELOCK_UPDATE,
1043                                              MDT_LOCAL_LOCK);
1044                         if (unlikely(rc != 0))
1045                                 RETURN(rc);
1046                 }
1047
1048                 /* step 2: lookup child's fid by name */
1049                 fid_zero(child_fid);
1050                 rc = mdo_lookup(info->mti_env, next, lname, child_fid,
1051                                 &info->mti_spec);
1052
1053                 if (rc != 0) {
1054                         if (rc == -ENOENT)
1055                                 mdt_set_disposition(info, ldlm_rep,
1056                                                     DISP_LOOKUP_NEG);
1057                         GOTO(out_parent, rc);
1058                 } else
1059                         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
1060         } else {
1061                 *child_fid = reqbody->fid2;
1062                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
1063         }
1064
1065         /*
1066          *step 3: find the child object by fid & lock it.
1067          *        regardless if it is local or remote.
1068          */
1069         child = mdt_object_find(info->mti_env, info->mti_mdt, child_fid);
1070
1071         if (unlikely(IS_ERR(child)))
1072                 GOTO(out_parent, rc = PTR_ERR(child));
1073         if (is_resent) {
1074                 /* Do not take lock for resent case. */
1075                 lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
1076                 LASSERTF(lock != NULL, "Invalid lock handle "LPX64"\n",
1077                          lhc->mlh_reg_lh.cookie);
1078
1079                 res_id = &lock->l_resource->lr_name;
1080                 if (!fid_res_name_eq(mdt_object_fid(child),
1081                                     &lock->l_resource->lr_name)) {
1082                          LASSERTF(fid_res_name_eq(mdt_object_fid(parent),
1083                                                  &lock->l_resource->lr_name),
1084                                  "Lock res_id: %lu/%lu/%lu, Fid: "DFID".\n",
1085                                  (unsigned long)res_id->name[0],
1086                                  (unsigned long)res_id->name[1],
1087                                  (unsigned long)res_id->name[2],
1088                                  PFID(mdt_object_fid(parent)));
1089                           CWARN("Although resent, but still not get child lock"
1090                                 "parent:"DFID" child:"DFID"\n",
1091                                 PFID(mdt_object_fid(parent)),
1092                                 PFID(mdt_object_fid(child)));
1093                           lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
1094                           LDLM_LOCK_PUT(lock);
1095                           GOTO(relock, 0);
1096                 }
1097                 LDLM_LOCK_PUT(lock);
1098                 rc = 0;
1099         } else {
1100 relock:
1101                 OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_RESEND, obd_timeout*2);
1102                 mdt_lock_handle_init(lhc);
1103                 if (child_bits == MDS_INODELOCK_LAYOUT)
1104                         mdt_lock_reg_init(lhc, LCK_CR);
1105                 else
1106                         mdt_lock_reg_init(lhc, LCK_PR);
1107
1108                 if (mdt_object_exists(child) == 0) {
1109                         LU_OBJECT_DEBUG(D_INODE, info->mti_env,
1110                                         &child->mot_obj.mo_lu,
1111                                         "Object doesn't exist!\n");
1112                         GOTO(out_child, rc = -ENOENT);
1113                 }
1114
1115                 if (!(child_bits & MDS_INODELOCK_UPDATE)) {
1116                         struct md_attr *ma = &info->mti_attr;
1117
1118                         ma->ma_valid = 0;
1119                         ma->ma_need = MA_INODE;
1120                         rc = mo_attr_get(info->mti_env,
1121                                          mdt_object_child(child), ma);
1122                         if (unlikely(rc != 0))
1123                                 GOTO(out_child, rc);
1124
1125                         /* layout lock is used only on regular files */
1126                         if ((ma->ma_valid & MA_INODE) &&
1127                             (ma->ma_attr.la_valid & LA_MODE) &&
1128                             !S_ISREG(ma->ma_attr.la_mode))
1129                                 child_bits &= ~MDS_INODELOCK_LAYOUT;
1130
1131                         /* If the file has not been changed for some time, we
1132                          * return not only a LOOKUP lock, but also an UPDATE
1133                          * lock and this might save us RPC on later STAT. For
1134                          * directories, it also let negative dentry starts
1135                          * working for this dir. */
1136                         if (ma->ma_valid & MA_INODE &&
1137                             ma->ma_attr.la_valid & LA_CTIME &&
1138                             info->mti_mdt->mdt_namespace->ns_ctime_age_limit +
1139                                 ma->ma_attr.la_ctime < cfs_time_current_sec())
1140                                 child_bits |= MDS_INODELOCK_UPDATE;
1141                 }
1142
1143                 rc = mdt_object_lock(info, child, lhc, child_bits,
1144                                      MDT_CROSS_LOCK);
1145
1146                 if (unlikely(rc != 0))
1147                         GOTO(out_child, rc);
1148         }
1149
1150         lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
1151         /* Get MA_SOM attributes if update lock is given. */
1152         if (lock &&
1153             lock->l_policy_data.l_inodebits.bits & MDS_INODELOCK_UPDATE &&
1154             S_ISREG(lu_object_attr(&mdt_object_child(child)->mo_lu)))
1155                 ma_need = MA_SOM;
1156
1157         /* finally, we can get attr for child. */
1158         mdt_set_capainfo(info, 1, child_fid, BYPASS_CAPA);
1159         rc = mdt_getattr_internal(info, child, ma_need);
1160         if (unlikely(rc != 0)) {
1161                 mdt_object_unlock(info, child, lhc, 1);
1162         } else if (lock) {
1163                 /* Debugging code. */
1164                 res_id = &lock->l_resource->lr_name;
1165                 LDLM_DEBUG(lock, "Returning lock to client");
1166                 LASSERTF(fid_res_name_eq(mdt_object_fid(child),
1167                                          &lock->l_resource->lr_name),
1168                          "Lock res_id: %lu/%lu/%lu, Fid: "DFID".\n",
1169                          (unsigned long)res_id->name[0],
1170                          (unsigned long)res_id->name[1],
1171                          (unsigned long)res_id->name[2],
1172                          PFID(mdt_object_fid(child)));
1173                 mdt_pack_size2body(info, child);
1174         }
1175         if (lock)
1176                 LDLM_LOCK_PUT(lock);
1177
1178         EXIT;
1179 out_child:
1180         mdt_object_put(info->mti_env, child);
1181 out_parent:
1182         if (lhp)
1183                 mdt_object_unlock(info, parent, lhp, 1);
1184         return rc;
1185 }
1186
1187 /* normal handler: should release the child lock */
1188 static int mdt_getattr_name(struct mdt_thread_info *info)
1189 {
1190         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_CHILD];
1191         struct mdt_body        *reqbody;
1192         struct mdt_body        *repbody;
1193         int rc, rc2;
1194         ENTRY;
1195
1196         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1197         LASSERT(reqbody != NULL);
1198         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1199         LASSERT(repbody != NULL);
1200
1201         info->mti_spec.sp_ck_split = !!(reqbody->valid & OBD_MD_FLCKSPLIT);
1202         info->mti_cross_ref = !!(reqbody->valid & OBD_MD_FLCROSSREF);
1203         repbody->eadatasize = 0;
1204         repbody->aclsize = 0;
1205
1206         rc = mdt_init_ucred(info, reqbody);
1207         if (unlikely(rc))
1208                 GOTO(out_shrink, rc);
1209
1210         rc = mdt_getattr_name_lock(info, lhc, MDS_INODELOCK_UPDATE, NULL);
1211         if (lustre_handle_is_used(&lhc->mlh_reg_lh)) {
1212                 ldlm_lock_decref(&lhc->mlh_reg_lh, lhc->mlh_reg_mode);
1213                 lhc->mlh_reg_lh.cookie = 0;
1214         }
1215         mdt_exit_ucred(info);
1216         EXIT;
1217 out_shrink:
1218         mdt_client_compatibility(info);
1219         rc2 = mdt_fix_reply(info);
1220         if (rc == 0)
1221                 rc = rc2;
1222         return rc;
1223 }
1224
1225 static const struct lu_device_operations mdt_lu_ops;
1226
1227 static int lu_device_is_mdt(struct lu_device *d)
1228 {
1229         return ergo(d != NULL && d->ld_ops != NULL, d->ld_ops == &mdt_lu_ops);
1230 }
1231
1232 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
1233                          void *karg, void *uarg);
1234
1235 static int mdt_set_info(struct mdt_thread_info *info)
1236 {
1237         struct ptlrpc_request *req = mdt_info_req(info);
1238         char *key;
1239         void *val;
1240         int keylen, vallen, rc = 0;
1241         ENTRY;
1242
1243         rc = req_capsule_server_pack(info->mti_pill);
1244         if (rc)
1245                 RETURN(rc);
1246
1247         key = req_capsule_client_get(info->mti_pill, &RMF_SETINFO_KEY);
1248         if (key == NULL) {
1249                 DEBUG_REQ(D_HA, req, "no set_info key");
1250                 RETURN(-EFAULT);
1251         }
1252
1253         keylen = req_capsule_get_size(info->mti_pill, &RMF_SETINFO_KEY,
1254                                       RCL_CLIENT);
1255
1256         val = req_capsule_client_get(info->mti_pill, &RMF_SETINFO_VAL);
1257         if (val == NULL) {
1258                 DEBUG_REQ(D_HA, req, "no set_info val");
1259                 RETURN(-EFAULT);
1260         }
1261
1262         vallen = req_capsule_get_size(info->mti_pill, &RMF_SETINFO_VAL,
1263                                       RCL_CLIENT);
1264
1265         /* Swab any part of val you need to here */
1266         if (KEY_IS(KEY_READ_ONLY)) {
1267                 req->rq_status = 0;
1268                 lustre_msg_set_status(req->rq_repmsg, 0);
1269
1270                 cfs_spin_lock(&req->rq_export->exp_lock);
1271                 if (*(__u32 *)val)
1272                         req->rq_export->exp_connect_flags |= OBD_CONNECT_RDONLY;
1273                 else
1274                         req->rq_export->exp_connect_flags &=~OBD_CONNECT_RDONLY;
1275                 cfs_spin_unlock(&req->rq_export->exp_lock);
1276
1277         } else if (KEY_IS(KEY_CHANGELOG_CLEAR)) {
1278                 struct changelog_setinfo *cs =
1279                         (struct changelog_setinfo *)val;
1280                 if (vallen != sizeof(*cs)) {
1281                         CERROR("Bad changelog_clear setinfo size %d\n", vallen);
1282                         RETURN(-EINVAL);
1283                 }
1284                 if (ptlrpc_req_need_swab(req)) {
1285                         __swab64s(&cs->cs_recno);
1286                         __swab32s(&cs->cs_id);
1287                 }
1288
1289                 rc = mdt_iocontrol(OBD_IOC_CHANGELOG_CLEAR, info->mti_exp,
1290                                    vallen, val, NULL);
1291                 lustre_msg_set_status(req->rq_repmsg, rc);
1292
1293         } else {
1294                 RETURN(-EINVAL);
1295         }
1296         RETURN(0);
1297 }
1298
1299 static int mdt_connect(struct mdt_thread_info *info)
1300 {
1301         int rc;
1302         struct ptlrpc_request *req;
1303
1304         req = mdt_info_req(info);
1305         rc = target_handle_connect(req);
1306         if (rc == 0) {
1307                 LASSERT(req->rq_export != NULL);
1308                 info->mti_mdt = mdt_dev(req->rq_export->exp_obd->obd_lu_dev);
1309                 rc = mdt_init_sec_level(info);
1310                 if (rc == 0)
1311                         rc = mdt_init_idmap(info);
1312                 if (rc != 0)
1313                         obd_disconnect(class_export_get(req->rq_export));
1314         } else {
1315                 rc = err_serious(rc);
1316         }
1317         return rc;
1318 }
1319
1320 static int mdt_disconnect(struct mdt_thread_info *info)
1321 {
1322         int rc;
1323         ENTRY;
1324
1325         rc = target_handle_disconnect(mdt_info_req(info));
1326         if (rc)
1327                 rc = err_serious(rc);
1328         RETURN(rc);
1329 }
1330
1331 static int mdt_sendpage(struct mdt_thread_info *info,
1332                         struct lu_rdpg *rdpg, int nob)
1333 {
1334         struct ptlrpc_request   *req = mdt_info_req(info);
1335         struct obd_export       *exp = req->rq_export;
1336         struct ptlrpc_bulk_desc *desc;
1337         struct l_wait_info      *lwi = &info->mti_u.rdpg.mti_wait_info;
1338         int                      tmpcount;
1339         int                      tmpsize;
1340         int                      i;
1341         int                      rc;
1342         ENTRY;
1343
1344         desc = ptlrpc_prep_bulk_exp(req, rdpg->rp_npages, BULK_PUT_SOURCE,
1345                                     MDS_BULK_PORTAL);
1346         if (desc == NULL)
1347                 RETURN(-ENOMEM);
1348
1349         if (!(exp->exp_connect_flags & OBD_CONNECT_BRW_SIZE))
1350                 /* old client requires reply size in it's PAGE_SIZE,
1351                  * which is rdpg->rp_count */
1352                 nob = rdpg->rp_count;
1353
1354         for (i = 0, tmpcount = nob; i < rdpg->rp_npages && tmpcount > 0;
1355              i++, tmpcount -= tmpsize) {
1356                 tmpsize = min_t(int, tmpcount, CFS_PAGE_SIZE);
1357                 ptlrpc_prep_bulk_page(desc, rdpg->rp_pages[i], 0, tmpsize);
1358         }
1359
1360         LASSERT(desc->bd_nob == nob);
1361         rc = target_bulk_io(exp, desc, lwi);
1362         ptlrpc_free_bulk(desc);
1363         RETURN(rc);
1364 }
1365
1366 #ifdef HAVE_SPLIT_SUPPORT
1367 /*
1368  * Retrieve dir entry from the page and insert it to the slave object, actually,
1369  * this should be in osd layer, but since it will not in the final product, so
1370  * just do it here and do not define more moo api anymore for this.
1371  */
1372 static int mdt_write_dir_page(struct mdt_thread_info *info, struct page *page,
1373                               int size)
1374 {
1375         struct mdt_object *object = info->mti_object;
1376         struct lu_fid *lf = &info->mti_tmp_fid2;
1377         struct md_attr *ma = &info->mti_attr;
1378         struct lu_dirpage *dp;
1379         struct lu_dirent *ent;
1380         int rc = 0, offset = 0;
1381         ENTRY;
1382
1383         /* Make sure we have at least one entry. */
1384         if (size == 0)
1385                 RETURN(-EINVAL);
1386
1387         /*
1388          * Disable trans for this name insert, since it will include many trans
1389          * for this.
1390          */
1391         info->mti_no_need_trans = 1;
1392         /*
1393          * When write_dir_page, no need update parent's ctime,
1394          * and no permission check for name_insert.
1395          */
1396         ma->ma_attr.la_ctime = 0;
1397         ma->ma_attr.la_valid = LA_MODE;
1398         ma->ma_valid = MA_INODE;
1399
1400         cfs_kmap(page);
1401         dp = page_address(page);
1402         offset = (int)((__u32)lu_dirent_start(dp) - (__u32)dp);
1403
1404         for (ent = lu_dirent_start(dp); ent != NULL;
1405              ent = lu_dirent_next(ent)) {
1406                 struct lu_name *lname;
1407                 char *name;
1408
1409                 if (le16_to_cpu(ent->lde_namelen) == 0)
1410                         continue;
1411
1412                 fid_le_to_cpu(lf, &ent->lde_fid);
1413                 if (le64_to_cpu(ent->lde_hash) & MAX_HASH_HIGHEST_BIT)
1414                         ma->ma_attr.la_mode = S_IFDIR;
1415                 else
1416                         ma->ma_attr.la_mode = 0;
1417                 OBD_ALLOC(name, le16_to_cpu(ent->lde_namelen) + 1);
1418                 if (name == NULL)
1419                         GOTO(out, rc = -ENOMEM);
1420
1421                 memcpy(name, ent->lde_name, le16_to_cpu(ent->lde_namelen));
1422                 lname = mdt_name(info->mti_env, name,
1423                                  le16_to_cpu(ent->lde_namelen));
1424                 ma->ma_attr_flags |= (MDS_PERM_BYPASS | MDS_QUOTA_IGNORE);
1425                 rc = mdo_name_insert(info->mti_env,
1426                                      md_object_next(&object->mot_obj),
1427                                      lname, lf, ma);
1428                 OBD_FREE(name, le16_to_cpu(ent->lde_namelen) + 1);
1429                 if (rc) {
1430                         CERROR("Can't insert %*.*s, rc %d\n",
1431                                le16_to_cpu(ent->lde_namelen),
1432                                le16_to_cpu(ent->lde_namelen),
1433                                ent->lde_name, rc);
1434                         GOTO(out, rc);
1435                 }
1436
1437                 offset += lu_dirent_size(ent);
1438                 if (offset >= size)
1439                         break;
1440         }
1441         EXIT;
1442 out:
1443         cfs_kunmap(page);
1444         return rc;
1445 }
1446
1447 static int mdt_bulk_timeout(void *data)
1448 {
1449         ENTRY;
1450
1451         CERROR("mdt bulk transfer timeout \n");
1452
1453         RETURN(1);
1454 }
1455
1456 static int mdt_writepage(struct mdt_thread_info *info)
1457 {
1458         struct ptlrpc_request   *req = mdt_info_req(info);
1459         struct mdt_body         *reqbody;
1460         struct l_wait_info      *lwi;
1461         struct ptlrpc_bulk_desc *desc;
1462         struct page             *page;
1463         int                rc;
1464         ENTRY;
1465
1466
1467         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1468         if (reqbody == NULL)
1469                 RETURN(err_serious(-EFAULT));
1470
1471         desc = ptlrpc_prep_bulk_exp(req, 1, BULK_GET_SINK, MDS_BULK_PORTAL);
1472         if (desc == NULL)
1473                 RETURN(err_serious(-ENOMEM));
1474
1475         /* allocate the page for the desc */
1476         page = cfs_alloc_page(CFS_ALLOC_STD);
1477         if (page == NULL)
1478                 GOTO(desc_cleanup, rc = -ENOMEM);
1479
1480         CDEBUG(D_INFO, "Received page offset %d size %d \n",
1481                (int)reqbody->size, (int)reqbody->nlink);
1482
1483         ptlrpc_prep_bulk_page(desc, page, (int)reqbody->size,
1484                               (int)reqbody->nlink);
1485
1486         rc = sptlrpc_svc_prep_bulk(req, desc);
1487         if (rc != 0)
1488                 GOTO(cleanup_page, rc);
1489         /*
1490          * Check if client was evicted while we were doing i/o before touching
1491          * network.
1492          */
1493         OBD_ALLOC_PTR(lwi);
1494         if (!lwi)
1495                 GOTO(cleanup_page, rc = -ENOMEM);
1496
1497         if (desc->bd_export->exp_failed)
1498                 rc = -ENOTCONN;
1499         else
1500                 rc = ptlrpc_start_bulk_transfer (desc);
1501         if (rc == 0) {
1502                 *lwi = LWI_TIMEOUT_INTERVAL(obd_timeout * CFS_HZ / 4, CFS_HZ,
1503                                             mdt_bulk_timeout, desc);
1504                 rc = l_wait_event(desc->bd_waitq, !ptlrpc_bulk_active(desc) ||
1505                                   desc->bd_export->exp_failed, lwi);
1506                 LASSERT(rc == 0 || rc == -ETIMEDOUT);
1507                 if (rc == -ETIMEDOUT) {
1508                         DEBUG_REQ(D_ERROR, req, "timeout on bulk GET");
1509                         ptlrpc_abort_bulk(desc);
1510                 } else if (desc->bd_export->exp_failed) {
1511                         DEBUG_REQ(D_ERROR, req, "Eviction on bulk GET");
1512                         rc = -ENOTCONN;
1513                         ptlrpc_abort_bulk(desc);
1514                 } else if (!desc->bd_success ||
1515                            desc->bd_nob_transferred != desc->bd_nob) {
1516                         DEBUG_REQ(D_ERROR, req, "%s bulk GET %d(%d)",
1517                                   desc->bd_success ?
1518                                   "truncated" : "network error on",
1519                                   desc->bd_nob_transferred, desc->bd_nob);
1520                         /* XXX should this be a different errno? */
1521                         rc = -ETIMEDOUT;
1522                 }
1523         } else {
1524                 DEBUG_REQ(D_ERROR, req, "ptlrpc_bulk_get failed: rc %d", rc);
1525         }
1526         if (rc)
1527                 GOTO(cleanup_lwi, rc);
1528         rc = mdt_write_dir_page(info, page, reqbody->nlink);
1529
1530 cleanup_lwi:
1531         OBD_FREE_PTR(lwi);
1532 cleanup_page:
1533         cfs_free_page(page);
1534 desc_cleanup:
1535         ptlrpc_free_bulk(desc);
1536         RETURN(rc);
1537 }
1538 #endif
1539
1540 static int mdt_readpage(struct mdt_thread_info *info)
1541 {
1542         struct mdt_object *object = info->mti_object;
1543         struct lu_rdpg    *rdpg = &info->mti_u.rdpg.mti_rdpg;
1544         struct mdt_body   *reqbody;
1545         struct mdt_body   *repbody;
1546         int                rc;
1547         int                i;
1548         ENTRY;
1549
1550         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READPAGE_PACK))
1551                 RETURN(err_serious(-ENOMEM));
1552
1553         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1554         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1555         if (reqbody == NULL || repbody == NULL)
1556                 RETURN(err_serious(-EFAULT));
1557
1558         /*
1559          * prepare @rdpg before calling lower layers and transfer itself. Here
1560          * reqbody->size contains offset of where to start to read and
1561          * reqbody->nlink contains number bytes to read.
1562          */
1563         rdpg->rp_hash = reqbody->size;
1564         if (rdpg->rp_hash != reqbody->size) {
1565                 CERROR("Invalid hash: "LPX64" != "LPX64"\n",
1566                        rdpg->rp_hash, reqbody->size);
1567                 RETURN(-EFAULT);
1568         }
1569
1570         rdpg->rp_attrs = reqbody->mode;
1571         if (info->mti_exp->exp_connect_flags & OBD_CONNECT_64BITHASH)
1572                 rdpg->rp_attrs |= LUDA_64BITHASH;
1573         rdpg->rp_count  = min_t(unsigned int, reqbody->nlink,
1574                                 PTLRPC_MAX_BRW_SIZE);
1575         rdpg->rp_npages = (rdpg->rp_count + CFS_PAGE_SIZE - 1) >>
1576                           CFS_PAGE_SHIFT;
1577         OBD_ALLOC(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1578         if (rdpg->rp_pages == NULL)
1579                 RETURN(-ENOMEM);
1580
1581         for (i = 0; i < rdpg->rp_npages; ++i) {
1582                 rdpg->rp_pages[i] = cfs_alloc_page(CFS_ALLOC_STD);
1583                 if (rdpg->rp_pages[i] == NULL)
1584                         GOTO(free_rdpg, rc = -ENOMEM);
1585         }
1586
1587         /* call lower layers to fill allocated pages with directory data */
1588         rc = mo_readpage(info->mti_env, mdt_object_child(object), rdpg);
1589         if (rc < 0)
1590                 GOTO(free_rdpg, rc);
1591
1592         /* send pages to client */
1593         rc = mdt_sendpage(info, rdpg, rc);
1594
1595         EXIT;
1596 free_rdpg:
1597
1598         for (i = 0; i < rdpg->rp_npages; i++)
1599                 if (rdpg->rp_pages[i] != NULL)
1600                         cfs_free_page(rdpg->rp_pages[i]);
1601         OBD_FREE(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1602
1603         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE))
1604                 RETURN(0);
1605
1606         return rc;
1607 }
1608
1609 static int mdt_reint_internal(struct mdt_thread_info *info,
1610                               struct mdt_lock_handle *lhc,
1611                               __u32 op)
1612 {
1613         struct req_capsule      *pill = info->mti_pill;
1614         struct md_quota         *mq = md_quota(info->mti_env);
1615         struct mdt_body         *repbody;
1616         int                      rc = 0, rc2;
1617         ENTRY;
1618
1619
1620         rc = mdt_reint_unpack(info, op);
1621         if (rc != 0) {
1622                 CERROR("Can't unpack reint, rc %d\n", rc);
1623                 RETURN(err_serious(rc));
1624         }
1625
1626         /* for replay (no_create) lmm is not needed, client has it already */
1627         if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1628                 req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
1629                                      info->mti_rr.rr_eadatalen);
1630
1631         if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
1632                 req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER,
1633                                      info->mti_mdt->mdt_max_cookiesize);
1634
1635         rc = req_capsule_server_pack(pill);
1636         if (rc != 0) {
1637                 CERROR("Can't pack response, rc %d\n", rc);
1638                 RETURN(err_serious(rc));
1639         }
1640
1641         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_SERVER)) {
1642                 repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
1643                 LASSERT(repbody);
1644                 repbody->eadatasize = 0;
1645                 repbody->aclsize = 0;
1646         }
1647
1648         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_REINT_DELAY, 10);
1649
1650         /* for replay no cookkie / lmm need, because client have this already */
1651         if (info->mti_spec.no_create)
1652                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1653                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, 0);
1654
1655         rc = mdt_init_ucred_reint(info);
1656         if (rc)
1657                 GOTO(out_shrink, rc);
1658
1659         rc = mdt_fix_attr_ucred(info, op);
1660         if (rc != 0)
1661                 GOTO(out_ucred, rc = err_serious(rc));
1662
1663         if (mdt_check_resent(info, mdt_reconstruct, lhc)) {
1664                 rc = lustre_msg_get_status(mdt_info_req(info)->rq_repmsg);
1665                 GOTO(out_ucred, rc);
1666         }
1667         mq->mq_exp = info->mti_exp;
1668         rc = mdt_reint_rec(info, lhc);
1669         EXIT;
1670 out_ucred:
1671         mdt_exit_ucred(info);
1672 out_shrink:
1673         mdt_client_compatibility(info);
1674         rc2 = mdt_fix_reply(info);
1675         if (rc == 0)
1676                 rc = rc2;
1677         return rc;
1678 }
1679
1680 static long mdt_reint_opcode(struct mdt_thread_info *info,
1681                              const struct req_format **fmt)
1682 {
1683         struct mdt_rec_reint *rec;
1684         long opc;
1685
1686         opc = err_serious(-EFAULT);
1687         rec = req_capsule_client_get(info->mti_pill, &RMF_REC_REINT);
1688         if (rec != NULL) {
1689                 opc = rec->rr_opcode;
1690                 DEBUG_REQ(D_INODE, mdt_info_req(info), "reint opt = %ld", opc);
1691                 if (opc < REINT_MAX && fmt[opc] != NULL)
1692                         req_capsule_extend(info->mti_pill, fmt[opc]);
1693                 else {
1694                         CERROR("Unsupported opc: %ld\n", opc);
1695                         opc = err_serious(opc);
1696                 }
1697         }
1698         return opc;
1699 }
1700
1701 static int mdt_reint(struct mdt_thread_info *info)
1702 {
1703         long opc;
1704         int  rc;
1705
1706         static const struct req_format *reint_fmts[REINT_MAX] = {
1707                 [REINT_SETATTR]  = &RQF_MDS_REINT_SETATTR,
1708                 [REINT_CREATE]   = &RQF_MDS_REINT_CREATE,
1709                 [REINT_LINK]     = &RQF_MDS_REINT_LINK,
1710                 [REINT_UNLINK]   = &RQF_MDS_REINT_UNLINK,
1711                 [REINT_RENAME]   = &RQF_MDS_REINT_RENAME,
1712                 [REINT_OPEN]     = &RQF_MDS_REINT_OPEN,
1713                 [REINT_SETXATTR] = &RQF_MDS_REINT_SETXATTR
1714         };
1715
1716         ENTRY;
1717
1718         opc = mdt_reint_opcode(info, reint_fmts);
1719         if (opc >= 0) {
1720                 /*
1721                  * No lock possible here from client to pass it to reint code
1722                  * path.
1723                  */
1724                 rc = mdt_reint_internal(info, NULL, opc);
1725         } else {
1726                 rc = opc;
1727         }
1728
1729         info->mti_fail_id = OBD_FAIL_MDS_REINT_NET_REP;
1730         RETURN(rc);
1731 }
1732
1733 /* this should sync the whole device */
1734 static int mdt_device_sync(const struct lu_env *env, struct mdt_device *mdt)
1735 {
1736         struct dt_device *dt = mdt->mdt_bottom;
1737         int rc;
1738         ENTRY;
1739
1740         rc = dt->dd_ops->dt_sync(env, dt);
1741         RETURN(rc);
1742 }
1743
1744 /* this should sync this object */
1745 static int mdt_object_sync(struct mdt_thread_info *info)
1746 {
1747         struct md_object *next;
1748         int rc;
1749         ENTRY;
1750
1751         if (!mdt_object_exists(info->mti_object)) {
1752                 CWARN("Non existing object  "DFID"!\n",
1753                       PFID(mdt_object_fid(info->mti_object)));
1754                 RETURN(-ESTALE);
1755         }
1756         next = mdt_object_child(info->mti_object);
1757         rc = mo_object_sync(info->mti_env, next);
1758
1759         RETURN(rc);
1760 }
1761
1762 static int mdt_sync(struct mdt_thread_info *info)
1763 {
1764         struct ptlrpc_request *req = mdt_info_req(info);
1765         struct req_capsule *pill = info->mti_pill;
1766         struct mdt_body *body;
1767         int rc;
1768         ENTRY;
1769
1770         /* The fid may be zero, so we req_capsule_set manually */
1771         req_capsule_set(pill, &RQF_MDS_SYNC);
1772
1773         body = req_capsule_client_get(pill, &RMF_MDT_BODY);
1774         if (body == NULL)
1775                 RETURN(err_serious(-EINVAL));
1776
1777         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SYNC_PACK))
1778                 RETURN(err_serious(-ENOMEM));
1779
1780         if (fid_seq(&body->fid1) == 0) {
1781                 /* sync the whole device */
1782                 rc = req_capsule_server_pack(pill);
1783                 if (rc == 0)
1784                         rc = mdt_device_sync(info->mti_env, info->mti_mdt);
1785                 else
1786                         rc = err_serious(rc);
1787         } else {
1788                 /* sync an object */
1789                 rc = mdt_unpack_req_pack_rep(info, HABEO_CORPUS|HABEO_REFERO);
1790                 if (rc == 0) {
1791                         rc = mdt_object_sync(info);
1792                         if (rc == 0) {
1793                                 struct md_object *next;
1794                                 const struct lu_fid *fid;
1795                                 struct lu_attr *la = &info->mti_attr.ma_attr;
1796
1797                                 next = mdt_object_child(info->mti_object);
1798                                 info->mti_attr.ma_need = MA_INODE;
1799                                 info->mti_attr.ma_valid = 0;
1800                                 rc = mo_attr_get(info->mti_env, next,
1801                                                  &info->mti_attr);
1802                                 if (rc == 0) {
1803                                         body = req_capsule_server_get(pill,
1804                                                                 &RMF_MDT_BODY);
1805                                         fid = mdt_object_fid(info->mti_object);
1806                                         mdt_pack_attr2body(info, body, la, fid);
1807                                 }
1808                         }
1809                 } else
1810                         rc = err_serious(rc);
1811         }
1812         if (rc == 0)
1813                 mdt_counter_incr(req, LPROC_MDT_SYNC);
1814
1815         RETURN(rc);
1816 }
1817
1818 #ifdef HAVE_QUOTA_SUPPORT
1819 static int mdt_quotacheck_handle(struct mdt_thread_info *info)
1820 {
1821         struct obd_quotactl *oqctl;
1822         struct req_capsule *pill = info->mti_pill;
1823         struct obd_export *exp = info->mti_exp;
1824         struct md_quota *mq = md_quota(info->mti_env);
1825         struct md_device *next = info->mti_mdt->mdt_child;
1826         int rc;
1827         ENTRY;
1828
1829         oqctl = req_capsule_client_get(pill, &RMF_OBD_QUOTACTL);
1830         if (oqctl == NULL)
1831                 RETURN(-EPROTO);
1832
1833         /* remote client has no permission for quotacheck */
1834         if (unlikely(exp_connect_rmtclient(exp)))
1835                 RETURN(-EPERM);
1836
1837         rc = req_capsule_server_pack(pill);
1838         if (rc)
1839                 RETURN(rc);
1840
1841         mq->mq_exp = exp;
1842         rc = next->md_ops->mdo_quota.mqo_check(info->mti_env, next,
1843                                                oqctl->qc_type);
1844         RETURN(rc);
1845 }
1846
1847 static int mdt_quotactl_handle(struct mdt_thread_info *info)
1848 {
1849         struct obd_quotactl *oqctl, *repoqc;
1850         struct req_capsule *pill = info->mti_pill;
1851         struct obd_export *exp = info->mti_exp;
1852         struct md_quota *mq = md_quota(info->mti_env);
1853         struct md_device *next = info->mti_mdt->mdt_child;
1854         const struct md_quota_operations *mqo = &next->md_ops->mdo_quota;
1855         int id, rc;
1856         ENTRY;
1857
1858         oqctl = req_capsule_client_get(pill, &RMF_OBD_QUOTACTL);
1859         if (oqctl == NULL)
1860                 RETURN(-EPROTO);
1861
1862         id = oqctl->qc_id;
1863         if (exp_connect_rmtclient(exp)) {
1864                 struct ptlrpc_request *req = mdt_info_req(info);
1865                 struct mdt_export_data *med = mdt_req2med(req);
1866                 struct lustre_idmap_table *idmap = med->med_idmap;
1867
1868                 if (unlikely(oqctl->qc_cmd != Q_GETQUOTA &&
1869                              oqctl->qc_cmd != Q_GETINFO))
1870                         RETURN(-EPERM);
1871
1872
1873                 if (oqctl->qc_type == USRQUOTA)
1874                         id = lustre_idmap_lookup_uid(NULL, idmap, 0,
1875                                                      oqctl->qc_id);
1876                 else if (oqctl->qc_type == GRPQUOTA)
1877                         id = lustre_idmap_lookup_gid(NULL, idmap, 0,
1878                                                      oqctl->qc_id);
1879                 else
1880                         RETURN(-EINVAL);
1881
1882                 if (id == CFS_IDMAP_NOTFOUND) {
1883                         CDEBUG(D_QUOTA, "no mapping for id %u\n",
1884                                oqctl->qc_id);
1885                         RETURN(-EACCES);
1886                 }
1887         }
1888
1889         rc = req_capsule_server_pack(pill);
1890         if (rc)
1891                 RETURN(rc);
1892
1893         repoqc = req_capsule_server_get(pill, &RMF_OBD_QUOTACTL);
1894         LASSERT(repoqc != NULL);
1895
1896         mq->mq_exp = exp;
1897         switch (oqctl->qc_cmd) {
1898         case Q_QUOTAON:
1899                 rc = mqo->mqo_on(info->mti_env, next, oqctl->qc_type);
1900                 break;
1901         case Q_QUOTAOFF:
1902                 rc = mqo->mqo_off(info->mti_env, next, oqctl->qc_type);
1903                 break;
1904         case Q_SETINFO:
1905                 rc = mqo->mqo_setinfo(info->mti_env, next, oqctl->qc_type, id,
1906                                       &oqctl->qc_dqinfo);
1907                 break;
1908         case Q_GETINFO:
1909                 rc = mqo->mqo_getinfo(info->mti_env, next, oqctl->qc_type, id,
1910                                       &oqctl->qc_dqinfo);
1911                 break;
1912         case Q_SETQUOTA:
1913                 rc = mqo->mqo_setquota(info->mti_env, next, oqctl->qc_type, id,
1914                                        &oqctl->qc_dqblk);
1915                 break;
1916         case Q_GETQUOTA:
1917                 rc = mqo->mqo_getquota(info->mti_env, next, oqctl->qc_type, id,
1918                                        &oqctl->qc_dqblk);
1919                 break;
1920         case Q_GETOINFO:
1921                 rc = mqo->mqo_getoinfo(info->mti_env, next, oqctl->qc_type, id,
1922                                        &oqctl->qc_dqinfo);
1923                 break;
1924         case Q_GETOQUOTA:
1925                 rc = mqo->mqo_getoquota(info->mti_env, next, oqctl->qc_type, id,
1926                                         &oqctl->qc_dqblk);
1927                 break;
1928         case LUSTRE_Q_INVALIDATE:
1929                 rc = mqo->mqo_invalidate(info->mti_env, next, oqctl->qc_type);
1930                 break;
1931         case LUSTRE_Q_FINVALIDATE:
1932                 rc = mqo->mqo_finvalidate(info->mti_env, next, oqctl->qc_type);
1933                 break;
1934         default:
1935                 CERROR("unsupported mdt_quotactl command: %d\n",
1936                        oqctl->qc_cmd);
1937                 RETURN(-EFAULT);
1938         }
1939
1940         *repoqc = *oqctl;
1941         RETURN(rc);
1942 }
1943 #endif
1944
1945
1946 /*
1947  * OBD PING and other handlers.
1948  */
1949 static int mdt_obd_ping(struct mdt_thread_info *info)
1950 {
1951         int rc;
1952         ENTRY;
1953
1954         req_capsule_set(info->mti_pill, &RQF_OBD_PING);
1955
1956         rc = target_handle_ping(mdt_info_req(info));
1957         if (rc < 0)
1958                 rc = err_serious(rc);
1959         RETURN(rc);
1960 }
1961
1962 /*
1963  * OBD_IDX_READ handler
1964  */
1965 static int mdt_obd_idx_read(struct mdt_thread_info *info)
1966 {
1967         struct mdt_device       *mdt = info->mti_mdt;
1968         struct lu_rdpg          *rdpg = &info->mti_u.rdpg.mti_rdpg;
1969         struct idx_info         *req_ii, *rep_ii;
1970         int                      rc, i;
1971         ENTRY;
1972
1973         memset(rdpg, 0, sizeof(*rdpg));
1974         req_capsule_set(info->mti_pill, &RQF_OBD_IDX_READ);
1975
1976         /* extract idx_info buffer from request & reply */
1977         req_ii = req_capsule_client_get(info->mti_pill, &RMF_IDX_INFO);
1978         if (req_ii == NULL || req_ii->ii_magic != IDX_INFO_MAGIC)
1979                 RETURN(err_serious(-EPROTO));
1980
1981         rc = req_capsule_server_pack(info->mti_pill);
1982         if (rc)
1983                 RETURN(err_serious(rc));
1984
1985         rep_ii = req_capsule_server_get(info->mti_pill, &RMF_IDX_INFO);
1986         if (rep_ii == NULL)
1987                 RETURN(err_serious(-EFAULT));
1988         rep_ii->ii_magic = IDX_INFO_MAGIC;
1989
1990         /* extract hash to start with */
1991         rdpg->rp_hash = req_ii->ii_hash_start;
1992
1993         /* extract requested attributes */
1994         rdpg->rp_attrs = req_ii->ii_attrs;
1995
1996         /* check that fid packed in request is valid and supported */
1997         if (!fid_is_sane(&req_ii->ii_fid))
1998                 RETURN(-EINVAL);
1999         rep_ii->ii_fid = req_ii->ii_fid;
2000
2001         /* copy flags */
2002         rep_ii->ii_flags = req_ii->ii_flags;
2003
2004         /* compute number of pages to allocate, ii_count is the number of 4KB
2005          * containers */
2006         if (req_ii->ii_count <= 0)
2007                 GOTO(out, rc = -EFAULT);
2008         rdpg->rp_count = min_t(unsigned int, req_ii->ii_count << LU_PAGE_SHIFT,
2009                                PTLRPC_MAX_BRW_SIZE);
2010         rdpg->rp_npages = (rdpg->rp_count + CFS_PAGE_SIZE -1) >> CFS_PAGE_SHIFT;
2011
2012         /* allocate pages to store the containers */
2013         OBD_ALLOC(rdpg->rp_pages, rdpg->rp_npages * sizeof(rdpg->rp_pages[0]));
2014         if (rdpg->rp_pages == NULL)
2015                 GOTO(out, rc = -ENOMEM);
2016         for (i = 0; i < rdpg->rp_npages; i++) {
2017                 rdpg->rp_pages[i] = cfs_alloc_page(CFS_ALLOC_STD);
2018                 if (rdpg->rp_pages[i] == NULL)
2019                         GOTO(out, rc = -ENOMEM);
2020         }
2021
2022         /* populate pages with key/record pairs */
2023         rc = dt_index_read(info->mti_env, mdt->mdt_bottom, rep_ii, rdpg);
2024         if (rc < 0)
2025                 GOTO(out, rc);
2026
2027         LASSERTF(rc <= rdpg->rp_count, "dt_index_read() returned more than "
2028                  "asked %d > %d\n", rc, rdpg->rp_count);
2029
2030         /* send pages to client */
2031         rc = mdt_sendpage(info, rdpg, rc);
2032
2033         GOTO(out, rc);
2034 out:
2035         if (rdpg->rp_pages) {
2036                 for (i = 0; i < rdpg->rp_npages; i++)
2037                         if (rdpg->rp_pages[i])
2038                                 cfs_free_page(rdpg->rp_pages[i]);
2039                 OBD_FREE(rdpg->rp_pages,
2040                          rdpg->rp_npages * sizeof(rdpg->rp_pages[0]));
2041         }
2042         return rc;
2043 }
2044
2045 static int mdt_obd_log_cancel(struct mdt_thread_info *info)
2046 {
2047         return err_serious(-EOPNOTSUPP);
2048 }
2049
2050 static int mdt_obd_qc_callback(struct mdt_thread_info *info)
2051 {
2052         return err_serious(-EOPNOTSUPP);
2053 }
2054
2055
2056 /*
2057  * LLOG handlers.
2058  */
2059
2060 /** clone llog ctxt from child (mdd)
2061  * This allows remote llog (replicator) access.
2062  * We can either pass all llog RPCs (eg mdt_llog_create) on to child where the
2063  * context was originally set up, or we can handle them directly.
2064  * I choose the latter, but that means I need any llog
2065  * contexts set up by child to be accessable by the mdt.  So we clone the
2066  * context into our context list here.
2067  */
2068 static int mdt_llog_ctxt_clone(const struct lu_env *env, struct mdt_device *mdt,
2069                                int idx)
2070 {
2071         struct md_device  *next = mdt->mdt_child;
2072         struct llog_ctxt *ctxt;
2073         int rc;
2074
2075         if (!llog_ctxt_null(mdt2obd_dev(mdt), idx))
2076                 return 0;
2077
2078         rc = next->md_ops->mdo_llog_ctxt_get(env, next, idx, (void **)&ctxt);
2079         if (rc || ctxt == NULL) {
2080                 CERROR("Can't get mdd ctxt %d\n", rc);
2081                 return rc;
2082         }
2083
2084         rc = llog_group_set_ctxt(&mdt2obd_dev(mdt)->obd_olg, ctxt, idx);
2085         if (rc)
2086                 CERROR("Can't set mdt ctxt %d\n", rc);
2087
2088         return rc;
2089 }
2090
2091 static int mdt_llog_ctxt_unclone(const struct lu_env *env,
2092                                  struct mdt_device *mdt, int idx)
2093 {
2094         struct llog_ctxt *ctxt;
2095
2096         ctxt = llog_get_context(mdt2obd_dev(mdt), idx);
2097         if (ctxt == NULL)
2098                 return 0;
2099         /* Put once for the get we just did, and once for the clone */
2100         llog_ctxt_put(ctxt);
2101         llog_ctxt_put(ctxt);
2102         return 0;
2103 }
2104
2105 static int mdt_llog_create(struct mdt_thread_info *info)
2106 {
2107         int rc;
2108
2109         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
2110         rc = llog_origin_handle_open(mdt_info_req(info));
2111         return (rc < 0 ? err_serious(rc) : rc);
2112 }
2113
2114 static int mdt_llog_destroy(struct mdt_thread_info *info)
2115 {
2116         int rc;
2117
2118         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_DESTROY);
2119         rc = llog_origin_handle_destroy(mdt_info_req(info));
2120         return (rc < 0 ? err_serious(rc) : rc);
2121 }
2122
2123 static int mdt_llog_read_header(struct mdt_thread_info *info)
2124 {
2125         int rc;
2126
2127         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_READ_HEADER);
2128         rc = llog_origin_handle_read_header(mdt_info_req(info));
2129         return (rc < 0 ? err_serious(rc) : rc);
2130 }
2131
2132 static int mdt_llog_next_block(struct mdt_thread_info *info)
2133 {
2134         int rc;
2135
2136         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
2137         rc = llog_origin_handle_next_block(mdt_info_req(info));
2138         return (rc < 0 ? err_serious(rc) : rc);
2139 }
2140
2141 static int mdt_llog_prev_block(struct mdt_thread_info *info)
2142 {
2143         int rc;
2144
2145         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_PREV_BLOCK);
2146         rc = llog_origin_handle_prev_block(mdt_info_req(info));
2147         return (rc < 0 ? err_serious(rc) : rc);
2148 }
2149
2150
2151 /*
2152  * DLM handlers.
2153  */
2154 static struct ldlm_callback_suite cbs = {
2155         .lcs_completion = ldlm_server_completion_ast,
2156         .lcs_blocking   = ldlm_server_blocking_ast,
2157         .lcs_glimpse    = NULL
2158 };
2159
2160 static int mdt_enqueue(struct mdt_thread_info *info)
2161 {
2162         struct ptlrpc_request *req;
2163         int rc;
2164
2165         /*
2166          * info->mti_dlm_req already contains swapped and (if necessary)
2167          * converted dlm request.
2168          */
2169         LASSERT(info->mti_dlm_req != NULL);
2170
2171         req = mdt_info_req(info);
2172         rc = ldlm_handle_enqueue0(info->mti_mdt->mdt_namespace,
2173                                   req, info->mti_dlm_req, &cbs);
2174         info->mti_fail_id = OBD_FAIL_LDLM_REPLY;
2175         return rc ? err_serious(rc) : req->rq_status;
2176 }
2177
2178 static int mdt_convert(struct mdt_thread_info *info)
2179 {
2180         int rc;
2181         struct ptlrpc_request *req;
2182
2183         LASSERT(info->mti_dlm_req);
2184         req = mdt_info_req(info);
2185         rc = ldlm_handle_convert0(req, info->mti_dlm_req);
2186         return rc ? err_serious(rc) : req->rq_status;
2187 }
2188
2189 static int mdt_bl_callback(struct mdt_thread_info *info)
2190 {
2191         CERROR("bl callbacks should not happen on MDS\n");
2192         LBUG();
2193         return err_serious(-EOPNOTSUPP);
2194 }
2195
2196 static int mdt_cp_callback(struct mdt_thread_info *info)
2197 {
2198         CERROR("cp callbacks should not happen on MDS\n");
2199         LBUG();
2200         return err_serious(-EOPNOTSUPP);
2201 }
2202
2203 /*
2204  * sec context handlers
2205  */
2206 static int mdt_sec_ctx_handle(struct mdt_thread_info *info)
2207 {
2208         int rc;
2209
2210         rc = mdt_handle_idmap(info);
2211
2212         if (unlikely(rc)) {
2213                 struct ptlrpc_request *req = mdt_info_req(info);
2214                 __u32                  opc;
2215
2216                 opc = lustre_msg_get_opc(req->rq_reqmsg);
2217                 if (opc == SEC_CTX_INIT || opc == SEC_CTX_INIT_CONT)
2218                         sptlrpc_svc_ctx_invalidate(req);
2219         }
2220
2221         CFS_FAIL_TIMEOUT(OBD_FAIL_SEC_CTX_HDL_PAUSE, cfs_fail_val);
2222
2223         return rc;
2224 }
2225
2226 static struct mdt_object *mdt_obj(struct lu_object *o)
2227 {
2228         LASSERT(lu_device_is_mdt(o->lo_dev));
2229         return container_of0(o, struct mdt_object, mot_obj.mo_lu);
2230 }
2231
2232 struct mdt_object *mdt_object_new(const struct lu_env *env,
2233                                   struct mdt_device *d,
2234                                   const struct lu_fid *f)
2235 {
2236         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
2237         struct lu_object *o;
2238         struct mdt_object *m;
2239         ENTRY;
2240
2241         CDEBUG(D_INFO, "Allocate object for "DFID"\n", PFID(f));
2242         o = lu_object_find(env, &d->mdt_md_dev.md_lu_dev, f, &conf);
2243         if (unlikely(IS_ERR(o)))
2244                 m = (struct mdt_object *)o;
2245         else
2246                 m = mdt_obj(o);
2247         RETURN(m);
2248 }
2249
2250 struct mdt_object *mdt_object_find(const struct lu_env *env,
2251                                    struct mdt_device *d,
2252                                    const struct lu_fid *f)
2253 {
2254         struct lu_object *o;
2255         struct mdt_object *m;
2256         ENTRY;
2257
2258         CDEBUG(D_INFO, "Find object for "DFID"\n", PFID(f));
2259         o = lu_object_find(env, &d->mdt_md_dev.md_lu_dev, f, NULL);
2260         if (unlikely(IS_ERR(o)))
2261                 m = (struct mdt_object *)o;
2262         else
2263                 m = mdt_obj(o);
2264         RETURN(m);
2265 }
2266
2267 /**
2268  * Asyncronous commit for mdt device.
2269  *
2270  * Pass asynchonous commit call down the MDS stack.
2271  *
2272  * \param env environment
2273  * \param mdt the mdt device
2274  */
2275 static void mdt_device_commit_async(const struct lu_env *env,
2276                                     struct mdt_device *mdt)
2277 {
2278         struct dt_device *dt = mdt->mdt_bottom;
2279         int rc;
2280
2281         rc = dt->dd_ops->dt_commit_async(env, dt);
2282         if (unlikely(rc != 0))
2283                 CWARN("async commit start failed with rc = %d", rc);
2284 }
2285
2286 /**
2287  * Mark the lock as "synchonous".
2288  *
2289  * Mark the lock to deffer transaction commit to the unlock time.
2290  *
2291  * \param lock the lock to mark as "synchonous"
2292  *
2293  * \see mdt_is_lock_sync
2294  * \see mdt_save_lock
2295  */
2296 static inline void mdt_set_lock_sync(struct ldlm_lock *lock)
2297 {
2298         lock->l_ast_data = (void*)1;
2299 }
2300
2301 /**
2302  * Check whehter the lock "synchonous" or not.
2303  *
2304  * \param lock the lock to check
2305  * \retval 1 the lock is "synchonous"
2306  * \retval 0 the lock isn't "synchronous"
2307  *
2308  * \see mdt_set_lock_sync
2309  * \see mdt_save_lock
2310  */
2311 static inline int mdt_is_lock_sync(struct ldlm_lock *lock)
2312 {
2313         return lock->l_ast_data != NULL;
2314 }
2315
2316 /**
2317  * Blocking AST for mdt locks.
2318  *
2319  * Starts transaction commit if in case of COS lock conflict or
2320  * deffers such a commit to the mdt_save_lock.
2321  *
2322  * \param lock the lock which blocks a request or cancelling lock
2323  * \param desc unused
2324  * \param data unused
2325  * \param flag indicates whether this cancelling or blocking callback
2326  * \retval 0
2327  * \see ldlm_blocking_ast_nocheck
2328  */
2329 int mdt_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
2330                      void *data, int flag)
2331 {
2332         struct obd_device *obd = ldlm_lock_to_ns(lock)->ns_obd;
2333         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
2334         int rc;
2335         ENTRY;
2336
2337         if (flag == LDLM_CB_CANCELING)
2338                 RETURN(0);
2339         lock_res_and_lock(lock);
2340         if (lock->l_blocking_ast != mdt_blocking_ast) {
2341                 unlock_res_and_lock(lock);
2342                 RETURN(0);
2343         }
2344         if (mdt_cos_is_enabled(mdt) &&
2345             lock->l_req_mode & (LCK_PW | LCK_EX) &&
2346             lock->l_blocking_lock != NULL &&
2347             lock->l_client_cookie != lock->l_blocking_lock->l_client_cookie) {
2348                 mdt_set_lock_sync(lock);
2349         }
2350         rc = ldlm_blocking_ast_nocheck(lock);
2351
2352         /* There is no lock conflict if l_blocking_lock == NULL,
2353          * it indicates a blocking ast sent from ldlm_lock_decref_internal
2354          * when the last reference to a local lock was released */
2355         if (lock->l_req_mode == LCK_COS && lock->l_blocking_lock != NULL) {
2356                 struct lu_env env;
2357
2358                 rc = lu_env_init(&env, LCT_LOCAL);
2359                 if (unlikely(rc != 0))
2360                         CWARN("lu_env initialization failed with rc = %d,"
2361                               "cannot start asynchronous commit\n", rc);
2362                 else
2363                         mdt_device_commit_async(&env, mdt);
2364                 lu_env_fini(&env);
2365         }
2366         RETURN(rc);
2367 }
2368
2369 int mdt_object_lock(struct mdt_thread_info *info, struct mdt_object *o,
2370                     struct mdt_lock_handle *lh, __u64 ibits, int locality)
2371 {
2372         struct ldlm_namespace *ns = info->mti_mdt->mdt_namespace;
2373         ldlm_policy_data_t *policy = &info->mti_policy;
2374         struct ldlm_res_id *res_id = &info->mti_res_id;
2375         int rc;
2376         ENTRY;
2377
2378         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2379         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2380         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
2381         LASSERT(lh->mlh_type != MDT_NUL_LOCK);
2382
2383         if (mdt_object_exists(o) < 0) {
2384                 if (locality == MDT_CROSS_LOCK) {
2385                         /* cross-ref object fix */
2386                         ibits &= ~MDS_INODELOCK_UPDATE;
2387                         ibits |= MDS_INODELOCK_LOOKUP;
2388                 } else {
2389                         LASSERT(!(ibits & MDS_INODELOCK_UPDATE));
2390                         LASSERT(ibits & MDS_INODELOCK_LOOKUP);
2391                 }
2392                 /* No PDO lock on remote object */
2393                 LASSERT(lh->mlh_type != MDT_PDO_LOCK);
2394         }
2395
2396         if (lh->mlh_type == MDT_PDO_LOCK) {
2397                 /* check for exists after object is locked */
2398                 if (mdt_object_exists(o) == 0) {
2399                         /* Non-existent object shouldn't have PDO lock */
2400                         RETURN(-ESTALE);
2401                 } else {
2402                         /* Non-dir object shouldn't have PDO lock */
2403                         if (!S_ISDIR(lu_object_attr(&o->mot_obj.mo_lu)))
2404                                 RETURN(-ENOTDIR);
2405                 }
2406         }
2407
2408         memset(policy, 0, sizeof(*policy));
2409         fid_build_reg_res_name(mdt_object_fid(o), res_id);
2410
2411         /*
2412          * Take PDO lock on whole directory and build correct @res_id for lock
2413          * on part of directory.
2414          */
2415         if (lh->mlh_pdo_hash != 0) {
2416                 LASSERT(lh->mlh_type == MDT_PDO_LOCK);
2417                 mdt_lock_pdo_mode(info, o, lh);
2418                 if (lh->mlh_pdo_mode != LCK_NL) {
2419                         /*
2420                          * Do not use LDLM_FL_LOCAL_ONLY for parallel lock, it
2421                          * is never going to be sent to client and we do not
2422                          * want it slowed down due to possible cancels.
2423                          */
2424                         policy->l_inodebits.bits = MDS_INODELOCK_UPDATE;
2425                         rc = mdt_fid_lock(ns, &lh->mlh_pdo_lh, lh->mlh_pdo_mode,
2426                                           policy, res_id, LDLM_FL_ATOMIC_CB,
2427                                           &info->mti_exp->exp_handle.h_cookie);
2428                         if (unlikely(rc))
2429                                 RETURN(rc);
2430                 }
2431
2432                 /*
2433                  * Finish res_id initializing by name hash marking part of
2434                  * directory which is taking modification.
2435                  */
2436                 res_id->name[LUSTRE_RES_ID_HSH_OFF] = lh->mlh_pdo_hash;
2437         }
2438
2439         policy->l_inodebits.bits = ibits;
2440
2441         /*
2442          * Use LDLM_FL_LOCAL_ONLY for this lock. We do not know yet if it is
2443          * going to be sent to client. If it is - mdt_intent_policy() path will
2444          * fix it up and turn FL_LOCAL flag off.
2445          */
2446         rc = mdt_fid_lock(ns, &lh->mlh_reg_lh, lh->mlh_reg_mode, policy,
2447                           res_id, LDLM_FL_LOCAL_ONLY | LDLM_FL_ATOMIC_CB,
2448                           &info->mti_exp->exp_handle.h_cookie);
2449         if (rc)
2450                 mdt_object_unlock(info, o, lh, 1);
2451         else if (unlikely(OBD_FAIL_PRECHECK(OBD_FAIL_MDS_PDO_LOCK)) &&
2452                  lh->mlh_pdo_hash != 0 &&
2453                  (lh->mlh_reg_mode == LCK_PW || lh->mlh_reg_mode == LCK_EX)) {
2454                 OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_PDO_LOCK, 15);
2455         }
2456
2457         RETURN(rc);
2458 }
2459
2460 /**
2461  * Save a lock within request object.
2462  *
2463  * Keep the lock referenced until whether client ACK or transaction
2464  * commit happens or release the lock immediately depending on input
2465  * parameters. If COS is ON, a write lock is converted to COS lock
2466  * before saving.
2467  *
2468  * \param info thead info object
2469  * \param h lock handle
2470  * \param mode lock mode
2471  * \param decref force immediate lock releasing
2472  */
2473 static
2474 void mdt_save_lock(struct mdt_thread_info *info, struct lustre_handle *h,
2475                    ldlm_mode_t mode, int decref)
2476 {
2477         ENTRY;
2478
2479         if (lustre_handle_is_used(h)) {
2480                 if (decref || !info->mti_has_trans ||
2481                     !(mode & (LCK_PW | LCK_EX))){
2482                         mdt_fid_unlock(h, mode);
2483                 } else {
2484                         struct mdt_device *mdt = info->mti_mdt;
2485                         struct ldlm_lock *lock = ldlm_handle2lock(h);
2486                         struct ptlrpc_request *req = mdt_info_req(info);
2487                         int no_ack = 0;
2488
2489                         LASSERTF(lock != NULL, "no lock for cookie "LPX64"\n",
2490                                  h->cookie);
2491                         CDEBUG(D_HA, "request = %p reply state = %p"
2492                                " transno = "LPD64"\n",
2493                                req, req->rq_reply_state, req->rq_transno);
2494                         if (mdt_cos_is_enabled(mdt)) {
2495                                 no_ack = 1;
2496                                 ldlm_lock_downgrade(lock, LCK_COS);
2497                                 mode = LCK_COS;
2498                         }
2499                         ptlrpc_save_lock(req, h, mode, no_ack);
2500                         if (mdt_is_lock_sync(lock)) {
2501                                 CDEBUG(D_HA, "found sync-lock,"
2502                                        " async commit started\n");
2503                                 mdt_device_commit_async(info->mti_env,
2504                                                         mdt);
2505                         }
2506                         LDLM_LOCK_PUT(lock);
2507                 }
2508                 h->cookie = 0ull;
2509         }
2510
2511         EXIT;
2512 }
2513
2514 /**
2515  * Unlock mdt object.
2516  *
2517  * Immeditely release the regular lock and the PDO lock or save the
2518  * lock in reqeuest and keep them referenced until client ACK or
2519  * transaction commit.
2520  *
2521  * \param info thread info object
2522  * \param o mdt object
2523  * \param lh mdt lock handle referencing regular and PDO locks
2524  * \param decref force immediate lock releasing
2525  */
2526 void mdt_object_unlock(struct mdt_thread_info *info, struct mdt_object *o,
2527                        struct mdt_lock_handle *lh, int decref)
2528 {
2529         ENTRY;
2530
2531         mdt_save_lock(info, &lh->mlh_pdo_lh, lh->mlh_pdo_mode, decref);
2532         mdt_save_lock(info, &lh->mlh_reg_lh, lh->mlh_reg_mode, decref);
2533
2534         EXIT;
2535 }
2536
2537 struct mdt_object *mdt_object_find_lock(struct mdt_thread_info *info,
2538                                         const struct lu_fid *f,
2539                                         struct mdt_lock_handle *lh,
2540                                         __u64 ibits)
2541 {
2542         struct mdt_object *o;
2543
2544         o = mdt_object_find(info->mti_env, info->mti_mdt, f);
2545         if (!IS_ERR(o)) {
2546                 int rc;
2547
2548                 rc = mdt_object_lock(info, o, lh, ibits,
2549                                      MDT_LOCAL_LOCK);
2550                 if (rc != 0) {
2551                         mdt_object_put(info->mti_env, o);
2552                         o = ERR_PTR(rc);
2553                 }
2554         }
2555         return o;
2556 }
2557
2558 void mdt_object_unlock_put(struct mdt_thread_info * info,
2559                            struct mdt_object * o,
2560                            struct mdt_lock_handle *lh,
2561                            int decref)
2562 {
2563         mdt_object_unlock(info, o, lh, decref);
2564         mdt_object_put(info->mti_env, o);
2565 }
2566
2567 static struct mdt_handler *mdt_handler_find(__u32 opc,
2568                                             struct mdt_opc_slice *supported)
2569 {
2570         struct mdt_opc_slice *s;
2571         struct mdt_handler   *h;
2572
2573         h = NULL;
2574         for (s = supported; s->mos_hs != NULL; s++) {
2575                 if (s->mos_opc_start <= opc && opc < s->mos_opc_end) {
2576                         h = s->mos_hs + (opc - s->mos_opc_start);
2577                         if (likely(h->mh_opc != 0))
2578                                 LASSERTF(h->mh_opc == opc,
2579                                          "opcode mismatch %d != %d\n",
2580                                          h->mh_opc, opc);
2581                         else
2582                                 h = NULL; /* unsupported opc */
2583                         break;
2584                 }
2585         }
2586         return h;
2587 }
2588
2589 static int mdt_lock_resname_compat(struct mdt_device *m,
2590                                    struct ldlm_request *req)
2591 {
2592         /* XXX something... later. */
2593         return 0;
2594 }
2595
2596 static int mdt_lock_reply_compat(struct mdt_device *m, struct ldlm_reply *rep)
2597 {
2598         /* XXX something... later. */
2599         return 0;
2600 }
2601
2602 /*
2603  * Generic code handling requests that have struct mdt_body passed in:
2604  *
2605  *  - extract mdt_body from request and save it in @info, if present;
2606  *
2607  *  - create lu_object, corresponding to the fid in mdt_body, and save it in
2608  *  @info;
2609  *
2610  *  - if HABEO_CORPUS flag is set for this request type check whether object
2611  *  actually exists on storage (lu_object_exists()).
2612  *
2613  */
2614 static int mdt_body_unpack(struct mdt_thread_info *info, __u32 flags)
2615 {
2616         const struct mdt_body    *body;
2617         struct mdt_object        *obj;
2618         const struct lu_env      *env;
2619         struct req_capsule       *pill;
2620         int                       rc;
2621         ENTRY;
2622
2623         env = info->mti_env;
2624         pill = info->mti_pill;
2625
2626         body = info->mti_body = req_capsule_client_get(pill, &RMF_MDT_BODY);
2627         if (body == NULL)
2628                 RETURN(-EFAULT);
2629
2630         if (!(body->valid & OBD_MD_FLID))
2631                 RETURN(0);
2632
2633         if (!fid_is_sane(&body->fid1)) {
2634                 CERROR("Invalid fid: "DFID"\n", PFID(&body->fid1));
2635                 RETURN(-EINVAL);
2636         }
2637
2638         /*
2639          * Do not get size or any capa fields before we check that request
2640          * contains capa actually. There are some requests which do not, for
2641          * instance MDS_IS_SUBDIR.
2642          */
2643         if (req_capsule_has_field(pill, &RMF_CAPA1, RCL_CLIENT) &&
2644             req_capsule_get_size(pill, &RMF_CAPA1, RCL_CLIENT))
2645                 mdt_set_capainfo(info, 0, &body->fid1,
2646                                  req_capsule_client_get(pill, &RMF_CAPA1));
2647
2648         obj = mdt_object_find(env, info->mti_mdt, &body->fid1);
2649         if (!IS_ERR(obj)) {
2650                 if ((flags & HABEO_CORPUS) &&
2651                     !mdt_object_exists(obj)) {
2652                         mdt_object_put(env, obj);
2653                         /* for capability renew ENOENT will be handled in
2654                          * mdt_renew_capa */
2655                         if (body->valid & OBD_MD_FLOSSCAPA)
2656                                 rc = 0;
2657                         else
2658                                 rc = -ENOENT;
2659                 } else {
2660                         info->mti_object = obj;
2661                         rc = 0;
2662                 }
2663         } else
2664                 rc = PTR_ERR(obj);
2665
2666         RETURN(rc);
2667 }
2668
2669 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags)
2670 {
2671         struct req_capsule *pill = info->mti_pill;
2672         int rc;
2673         ENTRY;
2674
2675         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_CLIENT))
2676                 rc = mdt_body_unpack(info, flags);
2677         else
2678                 rc = 0;
2679
2680         if (rc == 0 && (flags & HABEO_REFERO)) {
2681                 /* Pack reply. */
2682                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
2683                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
2684                                              info->mti_body->eadatasize);
2685                 if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
2686                         req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER,
2687                                              info->mti_mdt->mdt_max_cookiesize);
2688
2689                 rc = req_capsule_server_pack(pill);
2690         }
2691         RETURN(rc);
2692 }
2693
2694 static int mdt_init_capa_ctxt(const struct lu_env *env, struct mdt_device *m)
2695 {
2696         struct md_device *next = m->mdt_child;
2697
2698         return next->md_ops->mdo_init_capa_ctxt(env, next,
2699                                                 m->mdt_opts.mo_mds_capa,
2700                                                 m->mdt_capa_timeout,
2701                                                 m->mdt_capa_alg,
2702                                                 m->mdt_capa_keys);
2703 }
2704
2705 /*
2706  * Invoke handler for this request opc. Also do necessary preprocessing
2707  * (according to handler ->mh_flags), and post-processing (setting of
2708  * ->last_{xid,committed}).
2709  */
2710 static int mdt_req_handle(struct mdt_thread_info *info,
2711                           struct mdt_handler *h, struct ptlrpc_request *req)
2712 {
2713         int   rc, serious = 0;
2714         __u32 flags;
2715
2716         ENTRY;
2717
2718         LASSERT(h->mh_act != NULL);
2719         LASSERT(h->mh_opc == lustre_msg_get_opc(req->rq_reqmsg));
2720         LASSERT(current->journal_info == NULL);
2721
2722         /*
2723          * Checking for various OBD_FAIL_$PREF_$OPC_NET codes. _Do_ not try
2724          * to put same checks into handlers like mdt_close(), mdt_reint(),
2725          * etc., without talking to mdt authors first. Checking same thing
2726          * there again is useless and returning 0 error without packing reply
2727          * is buggy! Handlers either pack reply or return error.
2728          *
2729          * We return 0 here and do not send any reply in order to emulate
2730          * network failure. Do not send any reply in case any of NET related
2731          * fail_id has occured.
2732          */
2733         if (OBD_FAIL_CHECK_ORSET(h->mh_fail_id, OBD_FAIL_ONCE))
2734                 RETURN(0);
2735
2736         rc = 0;
2737         flags = h->mh_flags;
2738         LASSERT(ergo(flags & (HABEO_CORPUS|HABEO_REFERO), h->mh_fmt != NULL));
2739
2740         if (h->mh_fmt != NULL) {
2741                 req_capsule_set(info->mti_pill, h->mh_fmt);
2742                 rc = mdt_unpack_req_pack_rep(info, flags);
2743         }
2744
2745         if (rc == 0 && flags & MUTABOR &&
2746             req->rq_export->exp_connect_flags & OBD_CONNECT_RDONLY)
2747                 /* should it be rq_status? */
2748                 rc = -EROFS;
2749
2750         if (rc == 0 && flags & HABEO_CLAVIS) {
2751                 struct ldlm_request *dlm_req;
2752
2753                 LASSERT(h->mh_fmt != NULL);
2754
2755                 dlm_req = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
2756                 if (dlm_req != NULL) {
2757                         if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
2758                                         LDLM_IBITS &&
2759                                      dlm_req->lock_desc.l_policy_data.\
2760                                         l_inodebits.bits == 0)) {
2761                                 /*
2762                                  * Lock without inodebits makes no sense and
2763                                  * will oops later in ldlm. If client miss to
2764                                  * set such bits, do not trigger ASSERTION.
2765                                  *
2766                                  * For liblustre flock case, it maybe zero.
2767                                  */
2768                                 rc = -EPROTO;
2769                         } else {
2770                                 if (info->mti_mdt->mdt_opts.mo_compat_resname)
2771                                         rc = mdt_lock_resname_compat(
2772                                                                 info->mti_mdt,
2773                                                                 dlm_req);
2774                                 info->mti_dlm_req = dlm_req;
2775                         }
2776                 } else {
2777                         rc = -EFAULT;
2778                 }
2779         }
2780
2781         /* capability setting changed via /proc, needs reinitialize ctxt */
2782         if (info->mti_mdt && info->mti_mdt->mdt_capa_conf) {
2783                 mdt_init_capa_ctxt(info->mti_env, info->mti_mdt);
2784                 info->mti_mdt->mdt_capa_conf = 0;
2785         }
2786
2787         if (likely(rc == 0)) {
2788                 /*
2789                  * Process request, there can be two types of rc:
2790                  * 1) errors with msg unpack/pack, other failures outside the
2791                  * operation itself. This is counted as serious errors;
2792                  * 2) errors during fs operation, should be placed in rq_status
2793                  * only
2794                  */
2795                 rc = h->mh_act(info);
2796                 if (rc == 0 &&
2797                     !req->rq_no_reply && req->rq_reply_state == NULL) {
2798                         DEBUG_REQ(D_ERROR, req, "MDT \"handler\" %s did not "
2799                                   "pack reply and returned 0 error\n",
2800                                   h->mh_name);
2801                         LBUG();
2802                 }
2803                 serious = is_serious(rc);
2804                 rc = clear_serious(rc);
2805         } else
2806                 serious = 1;
2807
2808         req->rq_status = rc;
2809
2810         /*
2811          * ELDLM_* codes which > 0 should be in rq_status only as well as
2812          * all non-serious errors.
2813          */
2814         if (rc > 0 || !serious)
2815                 rc = 0;
2816
2817         LASSERT(current->journal_info == NULL);
2818
2819         if (rc == 0 && (flags & HABEO_CLAVIS) &&
2820             info->mti_mdt->mdt_opts.mo_compat_resname) {
2821                 struct ldlm_reply *dlmrep;
2822
2823                 dlmrep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
2824                 if (dlmrep != NULL)
2825                         rc = mdt_lock_reply_compat(info->mti_mdt, dlmrep);
2826         }
2827
2828         /* If we're DISCONNECTing, the mdt_export_data is already freed */
2829         if (likely(rc == 0 && req->rq_export && h->mh_opc != MDS_DISCONNECT))
2830                 target_committed_to_req(req);
2831
2832         if (unlikely(req_is_replay(req) &&
2833                      lustre_msg_get_transno(req->rq_reqmsg) == 0)) {
2834                 DEBUG_REQ(D_ERROR, req, "transno is 0 during REPLAY");
2835                 LBUG();
2836         }
2837
2838         target_send_reply(req, rc, info->mti_fail_id);
2839         RETURN(0);
2840 }
2841
2842 void mdt_lock_handle_init(struct mdt_lock_handle *lh)
2843 {
2844         lh->mlh_type = MDT_NUL_LOCK;
2845         lh->mlh_reg_lh.cookie = 0ull;
2846         lh->mlh_reg_mode = LCK_MINMODE;
2847         lh->mlh_pdo_lh.cookie = 0ull;
2848         lh->mlh_pdo_mode = LCK_MINMODE;
2849 }
2850
2851 void mdt_lock_handle_fini(struct mdt_lock_handle *lh)
2852 {
2853         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2854         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2855 }
2856
2857 /*
2858  * Initialize fields of struct mdt_thread_info. Other fields are left in
2859  * uninitialized state, because it's too expensive to zero out whole
2860  * mdt_thread_info (> 1K) on each request arrival.
2861  */
2862 static void mdt_thread_info_init(struct ptlrpc_request *req,
2863                                  struct mdt_thread_info *info)
2864 {
2865         int i;
2866         struct md_capainfo *ci;
2867
2868         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2869         info->mti_pill = &req->rq_pill;
2870
2871         /* lock handle */
2872         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
2873                 mdt_lock_handle_init(&info->mti_lh[i]);
2874
2875         /* mdt device: it can be NULL while CONNECT */
2876         if (req->rq_export) {
2877                 info->mti_mdt = mdt_dev(req->rq_export->exp_obd->obd_lu_dev);
2878                 info->mti_exp = req->rq_export;
2879         } else
2880                 info->mti_mdt = NULL;
2881         info->mti_env = req->rq_svc_thread->t_env;
2882         ci = md_capainfo(info->mti_env);
2883         memset(ci, 0, sizeof *ci);
2884         if (req->rq_export) {
2885                 if (exp_connect_rmtclient(req->rq_export))
2886                         ci->mc_auth = LC_ID_CONVERT;
2887                 else if (req->rq_export->exp_connect_flags &
2888                          OBD_CONNECT_MDS_CAPA)
2889                         ci->mc_auth = LC_ID_PLAIN;
2890                 else
2891                         ci->mc_auth = LC_ID_NONE;
2892         }
2893
2894         info->mti_fail_id = OBD_FAIL_MDS_ALL_REPLY_NET;
2895         info->mti_transno = lustre_msg_get_transno(req->rq_reqmsg);
2896         info->mti_mos = NULL;
2897
2898         memset(&info->mti_attr, 0, sizeof(info->mti_attr));
2899         info->mti_body = NULL;
2900         info->mti_object = NULL;
2901         info->mti_dlm_req = NULL;
2902         info->mti_has_trans = 0;
2903         info->mti_no_need_trans = 0;
2904         info->mti_cross_ref = 0;
2905         info->mti_opdata = 0;
2906
2907         /* To not check for split by default. */
2908         info->mti_spec.sp_ck_split = 0;
2909         info->mti_spec.no_create = 0;
2910 }
2911
2912 static void mdt_thread_info_fini(struct mdt_thread_info *info)
2913 {
2914         int i;
2915
2916         req_capsule_fini(info->mti_pill);
2917         if (info->mti_object != NULL) {
2918                 /*
2919                  * freeing an object may lead to OSD level transaction, do not
2920                  * let it mess with MDT. bz19385.
2921                  */
2922                 info->mti_no_need_trans = 1;
2923                 mdt_object_put(info->mti_env, info->mti_object);
2924                 info->mti_object = NULL;
2925         }
2926         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
2927                 mdt_lock_handle_fini(&info->mti_lh[i]);
2928         info->mti_env = NULL;
2929 }
2930
2931 static int mdt_filter_recovery_request(struct ptlrpc_request *req,
2932                                        struct obd_device *obd, int *process)
2933 {
2934         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2935         case MDS_CONNECT: /* This will never get here, but for completeness. */
2936         case OST_CONNECT: /* This will never get here, but for completeness. */
2937         case MDS_DISCONNECT:
2938         case OST_DISCONNECT:
2939                *process = 1;
2940                RETURN(0);
2941
2942         case MDS_CLOSE:
2943         case MDS_DONE_WRITING:
2944         case MDS_SYNC: /* used in unmounting */
2945         case OBD_PING:
2946         case MDS_REINT:
2947         case SEQ_QUERY:
2948         case FLD_QUERY:
2949         case LDLM_ENQUEUE:
2950                 *process = target_queue_recovery_request(req, obd);
2951                 RETURN(0);
2952
2953         default:
2954                 DEBUG_REQ(D_ERROR, req, "not permitted during recovery");
2955                 *process = -EAGAIN;
2956                 RETURN(0);
2957         }
2958 }
2959
2960 /*
2961  * Handle recovery. Return:
2962  *        +1: continue request processing;
2963  *       -ve: abort immediately with the given error code;
2964  *         0: send reply with error code in req->rq_status;
2965  */
2966 static int mdt_recovery(struct mdt_thread_info *info)
2967 {
2968         struct ptlrpc_request *req = mdt_info_req(info);
2969         struct obd_device *obd;
2970
2971         ENTRY;
2972
2973         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2974         case MDS_CONNECT:
2975         case SEC_CTX_INIT:
2976         case SEC_CTX_INIT_CONT:
2977         case SEC_CTX_FINI:
2978                 {
2979 #if 0
2980                         int rc;
2981
2982                         rc = mdt_handle_idmap(info);
2983                         if (rc)
2984                                 RETURN(rc);
2985                         else
2986 #endif
2987                                 RETURN(+1);
2988                 }
2989         }
2990
2991         if (unlikely(!class_connected_export(req->rq_export))) {
2992                 CERROR("operation %d on unconnected MDS from %s\n",
2993                        lustre_msg_get_opc(req->rq_reqmsg),
2994                        libcfs_id2str(req->rq_peer));
2995                 /* FIXME: For CMD cleanup, when mds_B stop, the req from
2996                  * mds_A will get -ENOTCONN(especially for ping req),
2997                  * which will cause that mds_A deactive timeout, then when
2998                  * mds_A cleanup, the cleanup process will be suspended since
2999                  * deactive timeout is not zero.
3000                  */
3001                 req->rq_status = -ENOTCONN;
3002                 target_send_reply(req, -ENOTCONN, info->mti_fail_id);
3003                 RETURN(0);
3004         }
3005
3006         /* sanity check: if the xid matches, the request must be marked as a
3007          * resent or replayed */
3008         if (req_xid_is_last(req)) {
3009                 if (!(lustre_msg_get_flags(req->rq_reqmsg) &
3010                       (MSG_RESENT | MSG_REPLAY))) {
3011                         DEBUG_REQ(D_WARNING, req, "rq_xid "LPU64" matches last_xid, "
3012                                   "expected REPLAY or RESENT flag (%x)", req->rq_xid,
3013                                   lustre_msg_get_flags(req->rq_reqmsg));
3014                         LBUG();
3015                         req->rq_status = -ENOTCONN;
3016                         RETURN(-ENOTCONN);
3017                 }
3018         }
3019
3020         /* else: note the opposite is not always true; a RESENT req after a
3021          * failover will usually not match the last_xid, since it was likely
3022          * never committed. A REPLAYed request will almost never match the
3023          * last xid, however it could for a committed, but still retained,
3024          * open. */
3025
3026         obd = req->rq_export->exp_obd;
3027
3028         /* Check for aborted recovery... */
3029         if (unlikely(obd->obd_recovering)) {
3030                 int rc;
3031                 int should_process;
3032                 DEBUG_REQ(D_INFO, req, "Got new replay");
3033                 rc = mdt_filter_recovery_request(req, obd, &should_process);
3034                 if (rc != 0 || !should_process)
3035                         RETURN(rc);
3036                 else if (should_process < 0) {
3037                         req->rq_status = should_process;
3038                         rc = ptlrpc_error(req);
3039                         RETURN(rc);
3040                 }
3041         }
3042         RETURN(+1);
3043 }
3044
3045 static int mdt_msg_check_version(struct lustre_msg *msg)
3046 {
3047         int rc;
3048
3049         switch (lustre_msg_get_opc(msg)) {
3050         case MDS_CONNECT:
3051         case MDS_DISCONNECT:
3052         case OBD_PING:
3053         case SEC_CTX_INIT:
3054         case SEC_CTX_INIT_CONT:
3055         case SEC_CTX_FINI:
3056         case OBD_IDX_READ:
3057                 rc = lustre_msg_check_version(msg, LUSTRE_OBD_VERSION);
3058                 if (rc)
3059                         CERROR("bad opc %u version %08x, expecting %08x\n",
3060                                lustre_msg_get_opc(msg),
3061                                lustre_msg_get_version(msg),
3062                                LUSTRE_OBD_VERSION);
3063                 break;
3064         case MDS_GETSTATUS:
3065         case MDS_GETATTR:
3066         case MDS_GETATTR_NAME:
3067         case MDS_STATFS:
3068         case MDS_READPAGE:
3069         case MDS_WRITEPAGE:
3070         case MDS_IS_SUBDIR:
3071         case MDS_REINT:
3072         case MDS_CLOSE:
3073         case MDS_DONE_WRITING:
3074         case MDS_PIN:
3075         case MDS_SYNC:
3076         case MDS_GETXATTR:
3077         case MDS_SETXATTR:
3078         case MDS_SET_INFO:
3079         case MDS_GET_INFO:
3080         case MDS_QUOTACHECK:
3081         case MDS_QUOTACTL:
3082         case QUOTA_DQACQ:
3083         case QUOTA_DQREL:
3084         case SEQ_QUERY:
3085         case FLD_QUERY:
3086                 rc = lustre_msg_check_version(msg, LUSTRE_MDS_VERSION);
3087                 if (rc)
3088                         CERROR("bad opc %u version %08x, expecting %08x\n",
3089                                lustre_msg_get_opc(msg),
3090                                lustre_msg_get_version(msg),
3091                                LUSTRE_MDS_VERSION);
3092                 break;
3093         case LDLM_ENQUEUE:
3094         case LDLM_CONVERT:
3095         case LDLM_BL_CALLBACK:
3096         case LDLM_CP_CALLBACK:
3097                 rc = lustre_msg_check_version(msg, LUSTRE_DLM_VERSION);
3098                 if (rc)
3099                         CERROR("bad opc %u version %08x, expecting %08x\n",
3100                                lustre_msg_get_opc(msg),
3101                                lustre_msg_get_version(msg),
3102                                LUSTRE_DLM_VERSION);
3103                 break;
3104         case OBD_LOG_CANCEL:
3105         case LLOG_ORIGIN_HANDLE_CREATE:
3106         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
3107         case LLOG_ORIGIN_HANDLE_READ_HEADER:
3108         case LLOG_ORIGIN_HANDLE_CLOSE:
3109         case LLOG_ORIGIN_HANDLE_DESTROY:
3110         case LLOG_ORIGIN_HANDLE_PREV_BLOCK:
3111         case LLOG_CATINFO:
3112                 rc = lustre_msg_check_version(msg, LUSTRE_LOG_VERSION);
3113                 if (rc)
3114                         CERROR("bad opc %u version %08x, expecting %08x\n",
3115                                lustre_msg_get_opc(msg),
3116                                lustre_msg_get_version(msg),
3117                                LUSTRE_LOG_VERSION);
3118                 break;
3119         default:
3120                 CERROR("MDS unknown opcode %d\n", lustre_msg_get_opc(msg));
3121                 rc = -ENOTSUPP;
3122         }
3123         return rc;
3124 }
3125
3126 static int mdt_handle0(struct ptlrpc_request *req,
3127                        struct mdt_thread_info *info,
3128                        struct mdt_opc_slice *supported)
3129 {
3130         struct mdt_handler *h;
3131         struct lustre_msg  *msg;
3132         int                 rc;
3133
3134         ENTRY;
3135
3136         if (OBD_FAIL_CHECK_ORSET(OBD_FAIL_MDS_ALL_REQUEST_NET, OBD_FAIL_ONCE))
3137                 RETURN(0);
3138
3139         LASSERT(current->journal_info == NULL);
3140
3141         msg = req->rq_reqmsg;
3142         rc = mdt_msg_check_version(msg);
3143         if (likely(rc == 0)) {
3144                 rc = mdt_recovery(info);
3145                 if (likely(rc == +1)) {
3146                         h = mdt_handler_find(lustre_msg_get_opc(msg),
3147                                              supported);
3148                         if (likely(h != NULL)) {
3149                                 rc = mdt_req_handle(info, h, req);
3150                         } else {
3151                                 CERROR("The unsupported opc: 0x%x\n",
3152                                        lustre_msg_get_opc(msg) );
3153                                 req->rq_status = -ENOTSUPP;
3154                                 rc = ptlrpc_error(req);
3155                                 RETURN(rc);
3156                         }
3157                 }
3158         } else
3159                 CERROR(LUSTRE_MDT_NAME" drops mal-formed request\n");
3160         RETURN(rc);
3161 }
3162
3163 /*
3164  * MDT handler function called by ptlrpc service thread when request comes.
3165  *
3166  * XXX common "target" functionality should be factored into separate module
3167  * shared by mdt, ost and stand-alone services like fld.
3168  */
3169 static int mdt_handle_common(struct ptlrpc_request *req,
3170                              struct mdt_opc_slice *supported)
3171 {
3172         struct lu_env          *env;
3173         struct mdt_thread_info *info;
3174         int                     rc;
3175         ENTRY;
3176
3177         env = req->rq_svc_thread->t_env;
3178         LASSERT(env != NULL);
3179         LASSERT(env->le_ses != NULL);
3180         LASSERT(env->le_ctx.lc_thread == req->rq_svc_thread);
3181         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
3182         LASSERT(info != NULL);
3183
3184         mdt_thread_info_init(req, info);
3185
3186         rc = mdt_handle0(req, info, supported);
3187
3188         mdt_thread_info_fini(info);
3189         RETURN(rc);
3190 }
3191
3192 /*
3193  * This is called from recovery code as handler of _all_ RPC types, FLD and SEQ
3194  * as well.
3195  */
3196 int mdt_recovery_handle(struct ptlrpc_request *req)
3197 {
3198         int rc;
3199         ENTRY;
3200
3201         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
3202         case FLD_QUERY:
3203                 rc = mdt_handle_common(req, mdt_fld_handlers);
3204                 break;
3205         case SEQ_QUERY:
3206                 rc = mdt_handle_common(req, mdt_seq_handlers);
3207                 break;
3208         default:
3209                 rc = mdt_handle_common(req, mdt_regular_handlers);
3210                 break;
3211         }
3212
3213         RETURN(rc);
3214 }
3215
3216 static int mdt_regular_handle(struct ptlrpc_request *req)
3217 {
3218         return mdt_handle_common(req, mdt_regular_handlers);
3219 }
3220
3221 static int mdt_readpage_handle(struct ptlrpc_request *req)
3222 {
3223         return mdt_handle_common(req, mdt_readpage_handlers);
3224 }
3225
3226 static int mdt_xmds_handle(struct ptlrpc_request *req)
3227 {
3228         return mdt_handle_common(req, mdt_xmds_handlers);
3229 }
3230
3231 static int mdt_mdsc_handle(struct ptlrpc_request *req)
3232 {
3233         return mdt_handle_common(req, mdt_seq_handlers);
3234 }
3235
3236 static int mdt_mdss_handle(struct ptlrpc_request *req)
3237 {
3238         return mdt_handle_common(req, mdt_seq_handlers);
3239 }
3240
3241 static int mdt_dtss_handle(struct ptlrpc_request *req)
3242 {
3243         return mdt_handle_common(req, mdt_seq_handlers);
3244 }
3245
3246 static int mdt_fld_handle(struct ptlrpc_request *req)
3247 {
3248         return mdt_handle_common(req, mdt_fld_handlers);
3249 }
3250
3251 enum mdt_it_code {
3252         MDT_IT_OPEN,
3253         MDT_IT_OCREAT,
3254         MDT_IT_CREATE,
3255         MDT_IT_GETATTR,
3256         MDT_IT_READDIR,
3257         MDT_IT_LOOKUP,
3258         MDT_IT_UNLINK,
3259         MDT_IT_TRUNC,
3260         MDT_IT_GETXATTR,
3261         MDT_IT_LAYOUT,
3262         MDT_IT_NR
3263 };
3264
3265 static int mdt_intent_getattr(enum mdt_it_code opcode,
3266                               struct mdt_thread_info *info,
3267                               struct ldlm_lock **,
3268                               int);
3269 static int mdt_intent_reint(enum mdt_it_code opcode,
3270                             struct mdt_thread_info *info,
3271                             struct ldlm_lock **,
3272                             int);
3273
3274 static struct mdt_it_flavor {
3275         const struct req_format *it_fmt;
3276         __u32                    it_flags;
3277         int                    (*it_act)(enum mdt_it_code ,
3278                                          struct mdt_thread_info *,
3279                                          struct ldlm_lock **,
3280                                          int);
3281         long                     it_reint;
3282 } mdt_it_flavor[] = {
3283         [MDT_IT_OPEN]     = {
3284                 .it_fmt   = &RQF_LDLM_INTENT,
3285                 /*.it_flags = HABEO_REFERO,*/
3286                 .it_flags = 0,
3287                 .it_act   = mdt_intent_reint,
3288                 .it_reint = REINT_OPEN
3289         },
3290         [MDT_IT_OCREAT]   = {
3291                 .it_fmt   = &RQF_LDLM_INTENT,
3292                 .it_flags = MUTABOR,
3293                 .it_act   = mdt_intent_reint,
3294                 .it_reint = REINT_OPEN
3295         },
3296         [MDT_IT_CREATE]   = {
3297                 .it_fmt   = &RQF_LDLM_INTENT,
3298                 .it_flags = MUTABOR,
3299                 .it_act   = mdt_intent_reint,
3300                 .it_reint = REINT_CREATE
3301         },
3302         [MDT_IT_GETATTR]  = {
3303                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3304                 .it_flags = HABEO_REFERO,
3305                 .it_act   = mdt_intent_getattr
3306         },
3307         [MDT_IT_READDIR]  = {
3308                 .it_fmt   = NULL,
3309                 .it_flags = 0,
3310                 .it_act   = NULL
3311         },
3312         [MDT_IT_LOOKUP]   = {
3313                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3314                 .it_flags = HABEO_REFERO,
3315                 .it_act   = mdt_intent_getattr
3316         },
3317         [MDT_IT_UNLINK]   = {
3318                 .it_fmt   = &RQF_LDLM_INTENT_UNLINK,
3319                 .it_flags = MUTABOR,
3320                 .it_act   = NULL,
3321                 .it_reint = REINT_UNLINK
3322         },
3323         [MDT_IT_TRUNC]    = {
3324                 .it_fmt   = NULL,
3325                 .it_flags = MUTABOR,
3326                 .it_act   = NULL
3327         },
3328         [MDT_IT_GETXATTR] = {
3329                 .it_fmt   = NULL,
3330                 .it_flags = 0,
3331                 .it_act   = NULL
3332         },
3333         [MDT_IT_LAYOUT] = {
3334                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3335                 .it_flags = HABEO_REFERO,
3336                 .it_act   = mdt_intent_getattr
3337         }
3338 };
3339
3340 int mdt_intent_lock_replace(struct mdt_thread_info *info,
3341                             struct ldlm_lock **lockp,
3342                             struct ldlm_lock *new_lock,
3343                             struct mdt_lock_handle *lh,
3344                             int flags)
3345 {
3346         struct ptlrpc_request  *req = mdt_info_req(info);
3347         struct ldlm_lock       *lock = *lockp;
3348
3349         /*
3350          * Get new lock only for cases when possible resent did not find any
3351          * lock.
3352          */
3353         if (new_lock == NULL)
3354                 new_lock = ldlm_handle2lock_long(&lh->mlh_reg_lh, 0);
3355
3356         if (new_lock == NULL && (flags & LDLM_FL_INTENT_ONLY)) {
3357                 lh->mlh_reg_lh.cookie = 0;
3358                 RETURN(0);
3359         }
3360
3361         LASSERTF(new_lock != NULL,
3362                  "lockh "LPX64"\n", lh->mlh_reg_lh.cookie);
3363
3364         /*
3365          * If we've already given this lock to a client once, then we should
3366          * have no readers or writers.  Otherwise, we should have one reader
3367          * _or_ writer ref (which will be zeroed below) before returning the
3368          * lock to a client.
3369          */
3370         if (new_lock->l_export == req->rq_export) {
3371                 LASSERT(new_lock->l_readers + new_lock->l_writers == 0);
3372         } else {
3373                 LASSERT(new_lock->l_export == NULL);
3374                 LASSERT(new_lock->l_readers + new_lock->l_writers == 1);
3375         }
3376
3377         *lockp = new_lock;
3378
3379         if (new_lock->l_export == req->rq_export) {
3380                 /*
3381                  * Already gave this to the client, which means that we
3382                  * reconstructed a reply.
3383                  */
3384                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) &
3385                         MSG_RESENT);
3386                 lh->mlh_reg_lh.cookie = 0;
3387                 RETURN(ELDLM_LOCK_REPLACED);
3388         }
3389
3390         /*
3391          * Fixup the lock to be given to the client.
3392          */
3393         lock_res_and_lock(new_lock);
3394         /* Zero new_lock->l_readers and new_lock->l_writers without triggering
3395          * possible blocking AST. */
3396         while (new_lock->l_readers > 0) {
3397                 lu_ref_del(&new_lock->l_reference, "reader", new_lock);
3398                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3399                 new_lock->l_readers--;
3400         }
3401         while (new_lock->l_writers > 0) {
3402                 lu_ref_del(&new_lock->l_reference, "writer", new_lock);
3403                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3404                 new_lock->l_writers--;
3405         }
3406
3407         new_lock->l_export = class_export_lock_get(req->rq_export, new_lock);
3408         new_lock->l_blocking_ast = lock->l_blocking_ast;
3409         new_lock->l_completion_ast = lock->l_completion_ast;
3410         new_lock->l_remote_handle = lock->l_remote_handle;
3411         new_lock->l_flags &= ~LDLM_FL_LOCAL;
3412
3413         unlock_res_and_lock(new_lock);
3414
3415         cfs_hash_add(new_lock->l_export->exp_lock_hash,
3416                      &new_lock->l_remote_handle,
3417                      &new_lock->l_exp_hash);
3418
3419         LDLM_LOCK_RELEASE(new_lock);
3420         lh->mlh_reg_lh.cookie = 0;
3421
3422         RETURN(ELDLM_LOCK_REPLACED);
3423 }
3424
3425 static void mdt_intent_fixup_resent(struct mdt_thread_info *info,
3426                                     struct ldlm_lock *new_lock,
3427                                     struct ldlm_lock **old_lock,
3428                                     struct mdt_lock_handle *lh)
3429 {
3430         struct ptlrpc_request  *req = mdt_info_req(info);
3431         struct obd_export      *exp = req->rq_export;
3432         struct lustre_handle    remote_hdl;
3433         struct ldlm_request    *dlmreq;
3434         struct ldlm_lock       *lock;
3435
3436         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT))
3437                 return;
3438
3439         dlmreq = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
3440         remote_hdl = dlmreq->lock_handle[0];
3441
3442         lock = cfs_hash_lookup(exp->exp_lock_hash, &remote_hdl);
3443         if (lock) {
3444                 if (lock != new_lock) {
3445                         lh->mlh_reg_lh.cookie = lock->l_handle.h_cookie;
3446                         lh->mlh_reg_mode = lock->l_granted_mode;
3447
3448                         LDLM_DEBUG(lock, "Restoring lock cookie");
3449                         DEBUG_REQ(D_DLMTRACE, req,
3450                                   "restoring lock cookie "LPX64,
3451                                   lh->mlh_reg_lh.cookie);
3452                         if (old_lock)
3453                                 *old_lock = LDLM_LOCK_GET(lock);
3454                         cfs_hash_put(exp->exp_lock_hash, &lock->l_exp_hash);
3455                         return;
3456                 }
3457
3458                 cfs_hash_put(exp->exp_lock_hash, &lock->l_exp_hash);
3459         }
3460
3461         /*
3462          * If the xid matches, then we know this is a resent request, and allow
3463          * it. (It's probably an OPEN, for which we don't send a lock.
3464          */
3465         if (req_xid_is_last(req))
3466                 return;
3467
3468         /*
3469          * This remote handle isn't enqueued, so we never received or processed
3470          * this request.  Clear MSG_RESENT, because it can be handled like any
3471          * normal request now.
3472          */
3473         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
3474
3475         DEBUG_REQ(D_DLMTRACE, req, "no existing lock with rhandle "LPX64,
3476                   remote_hdl.cookie);
3477 }
3478
3479 static int mdt_intent_getattr(enum mdt_it_code opcode,
3480                               struct mdt_thread_info *info,
3481                               struct ldlm_lock **lockp,
3482                               int flags)
3483 {
3484         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3485         struct ldlm_lock       *new_lock = NULL;
3486         __u64                   child_bits;
3487         struct ldlm_reply      *ldlm_rep;
3488         struct ptlrpc_request  *req;
3489         struct mdt_body        *reqbody;
3490         struct mdt_body        *repbody;
3491         int                     rc, rc2;
3492         ENTRY;
3493
3494         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
3495         LASSERT(reqbody);
3496
3497         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
3498         LASSERT(repbody);
3499
3500         info->mti_spec.sp_ck_split = !!(reqbody->valid & OBD_MD_FLCKSPLIT);
3501         info->mti_cross_ref = !!(reqbody->valid & OBD_MD_FLCROSSREF);
3502         repbody->eadatasize = 0;
3503         repbody->aclsize = 0;
3504
3505         switch (opcode) {
3506         case MDT_IT_LOOKUP:
3507                 child_bits = MDS_INODELOCK_LOOKUP;
3508                 break;
3509         case MDT_IT_GETATTR:
3510                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
3511                 break;
3512         case MDT_IT_LAYOUT: {
3513                 static int printed = 0;
3514
3515                 if (!printed) {
3516                         CERROR("layout lock not supported by this version\n");
3517                         printed = 1;
3518                 }
3519                 GOTO(out_shrink, rc = -EINVAL);
3520                 break;
3521         }
3522         default:
3523                 CERROR("Unsupported intent (%d)\n", opcode);
3524                 GOTO(out_shrink, rc = -EINVAL);
3525         }
3526
3527         rc = mdt_init_ucred(info, reqbody);
3528         if (rc)
3529                 GOTO(out_shrink, rc);
3530
3531         req = info->mti_pill->rc_req;
3532         ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3533         mdt_set_disposition(info, ldlm_rep, DISP_IT_EXECD);
3534
3535         /* Get lock from request for possible resent case. */
3536         mdt_intent_fixup_resent(info, *lockp, &new_lock, lhc);
3537
3538         ldlm_rep->lock_policy_res2 =
3539                 mdt_getattr_name_lock(info, lhc, child_bits, ldlm_rep);
3540
3541         if (mdt_get_disposition(ldlm_rep, DISP_LOOKUP_NEG))
3542                 ldlm_rep->lock_policy_res2 = 0;
3543         if (!mdt_get_disposition(ldlm_rep, DISP_LOOKUP_POS) ||
3544             ldlm_rep->lock_policy_res2) {
3545                 lhc->mlh_reg_lh.cookie = 0ull;
3546                 GOTO(out_ucred, rc = ELDLM_LOCK_ABORTED);
3547         }
3548
3549         rc = mdt_intent_lock_replace(info, lockp, new_lock, lhc, flags);
3550         EXIT;
3551 out_ucred:
3552         mdt_exit_ucred(info);
3553 out_shrink:
3554         mdt_client_compatibility(info);
3555         rc2 = mdt_fix_reply(info);
3556         if (rc == 0)
3557                 rc = rc2;
3558         return rc;
3559 }
3560
3561 static int mdt_intent_reint(enum mdt_it_code opcode,
3562                             struct mdt_thread_info *info,
3563                             struct ldlm_lock **lockp,
3564                             int flags)
3565 {
3566         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3567         struct ldlm_reply      *rep = NULL;
3568         long                    opc;
3569         int                     rc;
3570
3571         static const struct req_format *intent_fmts[REINT_MAX] = {
3572                 [REINT_CREATE]  = &RQF_LDLM_INTENT_CREATE,
3573                 [REINT_OPEN]    = &RQF_LDLM_INTENT_OPEN
3574         };
3575
3576         ENTRY;
3577
3578         opc = mdt_reint_opcode(info, intent_fmts);
3579         if (opc < 0)
3580                 RETURN(opc);
3581
3582         if (mdt_it_flavor[opcode].it_reint != opc) {
3583                 CERROR("Reint code %ld doesn't match intent: %d\n",
3584                        opc, opcode);
3585                 RETURN(err_serious(-EPROTO));
3586         }
3587
3588         /* Get lock from request for possible resent case. */
3589         mdt_intent_fixup_resent(info, *lockp, NULL, lhc);
3590
3591         rc = mdt_reint_internal(info, lhc, opc);
3592
3593         /* Check whether the reply has been packed successfully. */
3594         if (mdt_info_req(info)->rq_repmsg != NULL)
3595                 rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3596         if (rep == NULL)
3597                 RETURN(err_serious(-EFAULT));
3598
3599         /* MDC expects this in any case */
3600         if (rc != 0)
3601                 mdt_set_disposition(info, rep, DISP_LOOKUP_EXECD);
3602
3603         /* Cross-ref case, the lock should be returned to the client */
3604         if (rc == -EREMOTE) {
3605                 LASSERT(lustre_handle_is_used(&lhc->mlh_reg_lh));
3606                 rep->lock_policy_res2 = 0;
3607                 rc = mdt_intent_lock_replace(info, lockp, NULL, lhc, flags);
3608                 RETURN(rc);
3609         }
3610         rep->lock_policy_res2 = clear_serious(rc);
3611
3612         if (rep->lock_policy_res2 == -ENOENT &&
3613             mdt_get_disposition(rep, DISP_LOOKUP_NEG))
3614                 rep->lock_policy_res2 = 0;
3615
3616         if (rc == -ENOTCONN || rc == -ENODEV ||
3617             rc == -EOVERFLOW) { /**< if VBR failure then return error */
3618                 /*
3619                  * If it is the disconnect error (ENODEV & ENOCONN), the error
3620                  * will be returned by rq_status, and client at ptlrpc layer
3621                  * will detect this, then disconnect, reconnect the import
3622                  * immediately, instead of impacting the following the rpc.
3623                  */
3624                 lhc->mlh_reg_lh.cookie = 0ull;
3625                 RETURN(rc);
3626         } else {
3627                 /*
3628                  * For other cases, the error will be returned by intent.
3629                  * and client will retrieve the result from intent.
3630                  */
3631                  /*
3632                   * FIXME: when open lock is finished, that should be
3633                   * checked here.
3634                   */
3635                 if (lustre_handle_is_used(&lhc->mlh_reg_lh)) {
3636                         LASSERTF(rc == 0, "Error occurred but lock handle "
3637                                  "is still in use\n");
3638                         rep->lock_policy_res2 = 0;
3639                         rc = mdt_intent_lock_replace(info, lockp, NULL, lhc, flags);
3640                         RETURN(rc);
3641                 } else {
3642                         lhc->mlh_reg_lh.cookie = 0ull;
3643                         RETURN(ELDLM_LOCK_ABORTED);
3644                 }
3645         }
3646 }
3647
3648 static int mdt_intent_code(long itcode)
3649 {
3650         int rc;
3651
3652         switch(itcode) {
3653         case IT_OPEN:
3654                 rc = MDT_IT_OPEN;
3655                 break;
3656         case IT_OPEN|IT_CREAT:
3657                 rc = MDT_IT_OCREAT;
3658                 break;
3659         case IT_CREAT:
3660                 rc = MDT_IT_CREATE;
3661                 break;
3662         case IT_READDIR:
3663                 rc = MDT_IT_READDIR;
3664                 break;
3665         case IT_GETATTR:
3666                 rc = MDT_IT_GETATTR;
3667                 break;
3668         case IT_LOOKUP:
3669                 rc = MDT_IT_LOOKUP;
3670                 break;
3671         case IT_UNLINK:
3672                 rc = MDT_IT_UNLINK;
3673                 break;
3674         case IT_TRUNC:
3675                 rc = MDT_IT_TRUNC;
3676                 break;
3677         case IT_GETXATTR:
3678                 rc = MDT_IT_GETXATTR;
3679                 break;
3680         case IT_LAYOUT:
3681                 rc = MDT_IT_LAYOUT;
3682                 break;
3683         default:
3684                 CERROR("Unknown intent opcode: %ld\n", itcode);
3685                 rc = -EINVAL;
3686                 break;
3687         }
3688         return rc;
3689 }
3690
3691 static int mdt_intent_opc(long itopc, struct mdt_thread_info *info,
3692                           struct ldlm_lock **lockp, int flags)
3693 {
3694         struct req_capsule   *pill;
3695         struct mdt_it_flavor *flv;
3696         int opc;
3697         int rc;
3698         ENTRY;
3699
3700         opc = mdt_intent_code(itopc);
3701         if (opc < 0)
3702                 RETURN(-EINVAL);
3703
3704         pill = info->mti_pill;
3705         flv  = &mdt_it_flavor[opc];
3706
3707         if (flv->it_fmt != NULL)
3708                 req_capsule_extend(pill, flv->it_fmt);
3709
3710         rc = mdt_unpack_req_pack_rep(info, flv->it_flags);
3711         if (rc == 0) {
3712                 struct ptlrpc_request *req = mdt_info_req(info);
3713                 if (flv->it_flags & MUTABOR &&
3714                     req->rq_export->exp_connect_flags & OBD_CONNECT_RDONLY)
3715                         RETURN(-EROFS);
3716         }
3717         if (rc == 0 && flv->it_act != NULL) {
3718                 /* execute policy */
3719                 rc = flv->it_act(opc, info, lockp, flags);
3720         } else {
3721                 rc = -EOPNOTSUPP;
3722         }
3723         RETURN(rc);
3724 }
3725
3726 static int mdt_intent_policy(struct ldlm_namespace *ns,
3727                              struct ldlm_lock **lockp, void *req_cookie,
3728                              ldlm_mode_t mode, int flags, void *data)
3729 {
3730         struct mdt_thread_info *info;
3731         struct ptlrpc_request  *req  =  req_cookie;
3732         struct ldlm_intent     *it;
3733         struct req_capsule     *pill;
3734         int rc;
3735
3736         ENTRY;
3737
3738         LASSERT(req != NULL);
3739
3740         info = lu_context_key_get(&req->rq_svc_thread->t_env->le_ctx,
3741                                   &mdt_thread_key);
3742         LASSERT(info != NULL);
3743         pill = info->mti_pill;
3744         LASSERT(pill->rc_req == req);
3745
3746         if (req->rq_reqmsg->lm_bufcount > DLM_INTENT_IT_OFF) {
3747                 req_capsule_extend(pill, &RQF_LDLM_INTENT);
3748                 it = req_capsule_client_get(pill, &RMF_LDLM_INTENT);
3749                 if (it != NULL) {
3750                         rc = mdt_intent_opc(it->opc, info, lockp, flags);
3751                         if (rc == 0)
3752                                 rc = ELDLM_OK;
3753
3754                         /* Lock without inodebits makes no sense and will oops
3755                          * later in ldlm. Let's check it now to see if we have
3756                          * ibits corrupted somewhere in mdt_intent_opc().
3757                          * The case for client miss to set ibits has been
3758                          * processed by others. */
3759                         LASSERT(ergo(info->mti_dlm_req->lock_desc.l_resource.\
3760                                         lr_type == LDLM_IBITS,
3761                                      info->mti_dlm_req->lock_desc.\
3762                                         l_policy_data.l_inodebits.bits != 0));
3763                 } else
3764                         rc = err_serious(-EFAULT);
3765         } else {
3766                 /* No intent was provided */
3767                 LASSERT(pill->rc_fmt == &RQF_LDLM_ENQUEUE);
3768                 rc = req_capsule_server_pack(pill);
3769                 if (rc)
3770                         rc = err_serious(rc);
3771         }
3772         RETURN(rc);
3773 }
3774
3775 static int mdt_seq_fini(const struct lu_env *env,
3776                         struct mdt_device *m)
3777 {
3778         struct md_site *ms = mdt_md_site(m);
3779         ENTRY;
3780
3781         if (ms != NULL) {
3782                 if (ms->ms_server_seq) {
3783                         seq_server_fini(ms->ms_server_seq, env);
3784                         OBD_FREE_PTR(ms->ms_server_seq);
3785                         ms->ms_server_seq = NULL;
3786         }
3787
3788                 if (ms->ms_control_seq) {
3789                         seq_server_fini(ms->ms_control_seq, env);
3790                         OBD_FREE_PTR(ms->ms_control_seq);
3791                         ms->ms_control_seq = NULL;
3792         }
3793
3794                 if (ms->ms_client_seq) {
3795                         seq_client_fini(ms->ms_client_seq);
3796                         OBD_FREE_PTR(ms->ms_client_seq);
3797                         ms->ms_client_seq = NULL;
3798                 }
3799         }
3800
3801         RETURN(0);
3802 }
3803
3804 static int mdt_seq_init(const struct lu_env *env,
3805                         const char *uuid,
3806                         struct mdt_device *m)
3807 {
3808         struct md_site *ms;
3809         char *prefix;
3810         int rc;
3811         ENTRY;
3812
3813         ms = mdt_md_site(m);
3814
3815         /*
3816          * This is sequence-controller node. Init seq-controller server on local
3817          * MDT.
3818          */
3819         if (ms->ms_node_id == 0) {
3820                 LASSERT(ms->ms_control_seq == NULL);
3821
3822                 OBD_ALLOC_PTR(ms->ms_control_seq);
3823                 if (ms->ms_control_seq == NULL)
3824                         RETURN(-ENOMEM);
3825
3826                 rc = seq_server_init(ms->ms_control_seq,
3827                                      m->mdt_bottom, uuid,
3828                                      LUSTRE_SEQ_CONTROLLER,
3829                                      ms,
3830                                      env);
3831
3832                 if (rc)
3833                         GOTO(out_seq_fini, rc);
3834
3835                 OBD_ALLOC_PTR(ms->ms_client_seq);
3836                 if (ms->ms_client_seq == NULL)
3837                         GOTO(out_seq_fini, rc = -ENOMEM);
3838
3839                 OBD_ALLOC(prefix, MAX_OBD_NAME + 5);
3840                 if (prefix == NULL) {
3841                         OBD_FREE_PTR(ms->ms_client_seq);
3842                         GOTO(out_seq_fini, rc = -ENOMEM);
3843                 }
3844
3845                 snprintf(prefix, MAX_OBD_NAME + 5, "ctl-%s",
3846                          uuid);
3847
3848                 /*
3849                  * Init seq-controller client after seq-controller server is
3850                  * ready. Pass ms->ms_control_seq to it for direct talking.
3851                  */
3852                 rc = seq_client_init(ms->ms_client_seq, NULL,
3853                                      LUSTRE_SEQ_METADATA, prefix,
3854                                      ms->ms_control_seq);
3855                 OBD_FREE(prefix, MAX_OBD_NAME + 5);
3856
3857                 if (rc)
3858                         GOTO(out_seq_fini, rc);
3859         }
3860
3861         /* Init seq-server on local MDT */
3862         LASSERT(ms->ms_server_seq == NULL);
3863
3864         OBD_ALLOC_PTR(ms->ms_server_seq);
3865         if (ms->ms_server_seq == NULL)
3866                 GOTO(out_seq_fini, rc = -ENOMEM);
3867
3868         rc = seq_server_init(ms->ms_server_seq,
3869                              m->mdt_bottom, uuid,
3870                              LUSTRE_SEQ_SERVER,
3871                              ms,
3872                              env);
3873         if (rc)
3874                 GOTO(out_seq_fini, rc = -ENOMEM);
3875
3876         /* Assign seq-controller client to local seq-server. */
3877         if (ms->ms_node_id == 0) {
3878                 LASSERT(ms->ms_client_seq != NULL);
3879
3880                 rc = seq_server_set_cli(ms->ms_server_seq,
3881                                         ms->ms_client_seq,
3882                                         env);
3883         }
3884
3885         EXIT;
3886 out_seq_fini:
3887         if (rc)
3888                 mdt_seq_fini(env, m);
3889
3890         return rc;
3891 }
3892 /*
3893  * Init client sequence manager which is used by local MDS to talk to sequence
3894  * controller on remote node.
3895  */
3896 static int mdt_seq_init_cli(const struct lu_env *env,
3897                             struct mdt_device *m,
3898                             struct lustre_cfg *cfg)
3899 {
3900         struct md_site    *ms = mdt_md_site(m);
3901         struct obd_device *mdc;
3902         struct obd_uuid   *uuidp, *mdcuuidp;
3903         char              *uuid_str, *mdc_uuid_str;
3904         int                rc;
3905         int                index;
3906         struct mdt_thread_info *info;
3907         char *p, *index_string = lustre_cfg_string(cfg, 2);
3908         ENTRY;
3909
3910         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
3911         uuidp = &info->mti_u.uuid[0];
3912         mdcuuidp = &info->mti_u.uuid[1];
3913
3914         LASSERT(index_string);
3915
3916         index = simple_strtol(index_string, &p, 10);
3917         if (*p) {
3918                 CERROR("Invalid index in lustre_cgf, offset 2\n");
3919                 RETURN(-EINVAL);
3920         }
3921
3922         /* check if this is adding the first MDC and controller is not yet
3923          * initialized. */
3924         if (index != 0 || ms->ms_client_seq)
3925                 RETURN(0);
3926
3927         uuid_str = lustre_cfg_string(cfg, 1);
3928         mdc_uuid_str = lustre_cfg_string(cfg, 4);
3929         obd_str2uuid(uuidp, uuid_str);
3930         obd_str2uuid(mdcuuidp, mdc_uuid_str);
3931
3932         mdc = class_find_client_obd(uuidp, LUSTRE_MDC_NAME, mdcuuidp);
3933         if (!mdc) {
3934                 CERROR("can't find controller MDC by uuid %s\n",
3935                        uuid_str);
3936                 rc = -ENOENT;
3937         } else if (!mdc->obd_set_up) {
3938                 CERROR("target %s not set up\n", mdc->obd_name);
3939                 rc = -EINVAL;
3940         } else {
3941                 LASSERT(ms->ms_control_exp);
3942                 OBD_ALLOC_PTR(ms->ms_client_seq);
3943                 if (ms->ms_client_seq != NULL) {
3944                         char *prefix;
3945
3946                         OBD_ALLOC(prefix, MAX_OBD_NAME + 5);
3947                         if (!prefix)
3948                                 RETURN(-ENOMEM);
3949
3950                         snprintf(prefix, MAX_OBD_NAME + 5, "ctl-%s",
3951                                  mdc->obd_name);
3952
3953                         rc = seq_client_init(ms->ms_client_seq,
3954                                              ms->ms_control_exp,
3955                                              LUSTRE_SEQ_METADATA,
3956                                              prefix, NULL);
3957                         OBD_FREE(prefix, MAX_OBD_NAME + 5);
3958                 } else
3959                         rc = -ENOMEM;
3960
3961                 if (rc)
3962                         RETURN(rc);
3963
3964                 LASSERT(ms->ms_server_seq != NULL);
3965                 rc = seq_server_set_cli(ms->ms_server_seq, ms->ms_client_seq,
3966                                         env);
3967         }
3968
3969         RETURN(rc);
3970 }
3971
3972 static void mdt_seq_fini_cli(struct mdt_device *m)
3973 {
3974         struct md_site *ms;
3975
3976         ENTRY;
3977
3978         ms = mdt_md_site(m);
3979
3980         if (ms != NULL) {
3981                 if (ms->ms_server_seq)
3982                         seq_server_set_cli(ms->ms_server_seq,
3983                                    NULL, NULL);
3984
3985                 if (ms->ms_control_exp) {
3986                         class_export_put(ms->ms_control_exp);
3987                         ms->ms_control_exp = NULL;
3988                 }
3989         }
3990         EXIT;
3991 }
3992
3993 /*
3994  * FLD wrappers
3995  */
3996 static int mdt_fld_fini(const struct lu_env *env,
3997                         struct mdt_device *m)
3998 {
3999         struct md_site *ms = mdt_md_site(m);
4000         ENTRY;
4001
4002         if (ms && ms->ms_server_fld) {
4003                 fld_server_fini(ms->ms_server_fld, env);
4004                 OBD_FREE_PTR(ms->ms_server_fld);
4005                 ms->ms_server_fld = NULL;
4006         }
4007
4008         RETURN(0);
4009 }
4010
4011 static int mdt_fld_init(const struct lu_env *env,
4012                         const char *uuid,
4013                         struct mdt_device *m)
4014 {
4015         struct md_site *ms;
4016         int rc;
4017         ENTRY;
4018
4019         ms = mdt_md_site(m);
4020
4021         OBD_ALLOC_PTR(ms->ms_server_fld);
4022         if (ms->ms_server_fld == NULL)
4023                 RETURN(rc = -ENOMEM);
4024
4025         rc = fld_server_init(ms->ms_server_fld,
4026                              m->mdt_bottom, uuid,
4027                              env, ms->ms_node_id);
4028         if (rc) {
4029                 OBD_FREE_PTR(ms->ms_server_fld);
4030                 ms->ms_server_fld = NULL;
4031                 RETURN(rc);
4032         }
4033
4034         RETURN(0);
4035 }
4036
4037 /* device init/fini methods */
4038 static void mdt_stop_ptlrpc_service(struct mdt_device *m)
4039 {
4040         ENTRY;
4041         if (m->mdt_regular_service != NULL) {
4042                 ptlrpc_unregister_service(m->mdt_regular_service);
4043                 m->mdt_regular_service = NULL;
4044         }
4045         if (m->mdt_readpage_service != NULL) {
4046                 ptlrpc_unregister_service(m->mdt_readpage_service);
4047                 m->mdt_readpage_service = NULL;
4048         }
4049         if (m->mdt_xmds_service != NULL) {
4050                 ptlrpc_unregister_service(m->mdt_xmds_service);
4051                 m->mdt_xmds_service = NULL;
4052         }
4053         if (m->mdt_setattr_service != NULL) {
4054                 ptlrpc_unregister_service(m->mdt_setattr_service);
4055                 m->mdt_setattr_service = NULL;
4056         }
4057         if (m->mdt_mdsc_service != NULL) {
4058                 ptlrpc_unregister_service(m->mdt_mdsc_service);
4059                 m->mdt_mdsc_service = NULL;
4060         }
4061         if (m->mdt_mdss_service != NULL) {
4062                 ptlrpc_unregister_service(m->mdt_mdss_service);
4063                 m->mdt_mdss_service = NULL;
4064         }
4065         if (m->mdt_dtss_service != NULL) {
4066                 ptlrpc_unregister_service(m->mdt_dtss_service);
4067                 m->mdt_dtss_service = NULL;
4068         }
4069         if (m->mdt_fld_service != NULL) {
4070                 ptlrpc_unregister_service(m->mdt_fld_service);
4071                 m->mdt_fld_service = NULL;
4072         }
4073         EXIT;
4074 }
4075
4076 static int mdt_start_ptlrpc_service(struct mdt_device *m)
4077 {
4078         static struct ptlrpc_service_conf conf;
4079         cfs_proc_dir_entry_t *procfs_entry;
4080         int rc = 0;
4081         ENTRY;
4082
4083         m->mdt_ldlm_client = &m->mdt_md_dev.md_lu_dev.ld_obd->obd_ldlm_client;
4084         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
4085                            "mdt_ldlm_client", m->mdt_ldlm_client);
4086
4087         procfs_entry = m->mdt_md_dev.md_lu_dev.ld_obd->obd_proc_entry;
4088
4089         conf = (typeof(conf)) {
4090                 .psc_name               = LUSTRE_MDT_NAME,
4091                 .psc_watchdog_factor    = MDT_SERVICE_WATCHDOG_FACTOR,
4092                 .psc_buf                = {
4093                         .bc_nbufs               = MDS_NBUFS,
4094                         .bc_buf_size            = MDS_BUFSIZE,
4095                         .bc_req_max_size        = MDS_MAXREQSIZE,
4096                         .bc_rep_max_size        = MDS_MAXREPSIZE,
4097                         .bc_req_portal          = MDS_REQUEST_PORTAL,
4098                         .bc_rep_portal          = MDC_REPLY_PORTAL,
4099                 },
4100                 /*
4101                  * We'd like to have a mechanism to set this on a per-device
4102                  * basis, but alas...
4103                  */
4104                 .psc_thr                = {
4105                         .tc_thr_name            = LUSTRE_MDT_NAME,
4106                         .tc_thr_factor          = MDT_THR_FACTOR,
4107                         .tc_nthrs_init          = MDT_NTHRS_INIT,
4108                         .tc_nthrs_base          = MDT_NTHRS_BASE,
4109                         .tc_nthrs_max           = MDT_NTHRS_MAX,
4110                         .tc_nthrs_user          = mds_num_threads,
4111                         .tc_cpu_affinity        = 1,
4112                         .tc_ctx_tags            = LCT_MD_THREAD,
4113                 },
4114                 .psc_cpt                = {
4115                         .cc_pattern             = mds_num_cpts,
4116                 },
4117                 .psc_ops                = {
4118                         .so_req_handler         = mdt_regular_handle,
4119                         .so_req_printer         = target_print_req,
4120                         .so_hpreq_handler       = ptlrpc_hpreq_handler,
4121                 },
4122         };
4123         m->mdt_regular_service = ptlrpc_register_service(&conf, procfs_entry);
4124         if (IS_ERR(m->mdt_regular_service)) {
4125                 rc = PTR_ERR(m->mdt_regular_service);
4126                 CERROR("failed to start regular mdt service: %d\n", rc);
4127                 m->mdt_regular_service = NULL;
4128
4129                 RETURN(rc);
4130         }
4131
4132         /*
4133          * readpage service configuration. Parameters have to be adjusted,
4134          * ideally.
4135          */
4136         memset(&conf, 0, sizeof(conf));
4137         conf = (typeof(conf)) {
4138                 .psc_name               = LUSTRE_MDT_NAME "_readpage",
4139                 .psc_watchdog_factor    = MDT_SERVICE_WATCHDOG_FACTOR,
4140                 .psc_buf                = {
4141                         .bc_nbufs               = MDS_NBUFS,
4142                         .bc_buf_size            = MDS_BUFSIZE,
4143                         .bc_req_max_size        = MDS_MAXREQSIZE,
4144                         .bc_rep_max_size        = MDS_MAXREPSIZE,
4145                         .bc_req_portal          = MDS_READPAGE_PORTAL,
4146                         .bc_rep_portal          = MDC_REPLY_PORTAL,
4147                 },
4148                 .psc_thr                = {
4149                         .tc_thr_name            = "mdt_rdpg",
4150                         .tc_thr_factor          = MDT_RDPG_THR_FACTOR,
4151                         .tc_nthrs_init          = MDT_RDPG_NTHRS_INIT,
4152                         .tc_nthrs_base          = MDT_RDPG_NTHRS_BASE,
4153                         .tc_nthrs_max           = MDT_RDPG_NTHRS_MAX,
4154                         .tc_nthrs_user          = mds_rdpg_num_threads,
4155                         .tc_cpu_affinity        = 1,
4156                         .tc_ctx_tags            = LCT_MD_THREAD,
4157                 },
4158                 .psc_cpt                = {
4159                         .cc_pattern             = mds_rdpg_num_cpts,
4160                 },
4161                 .psc_ops                = {
4162                         .so_req_handler         = mdt_readpage_handle,
4163                         .so_req_printer         = target_print_req,
4164                         .so_hpreq_handler       = NULL,
4165                 },
4166         };
4167         m->mdt_readpage_service = ptlrpc_register_service(&conf, procfs_entry);
4168         if (IS_ERR(m->mdt_readpage_service)) {
4169                 rc = PTR_ERR(m->mdt_readpage_service);
4170                 CERROR("failed to start readpage service: %d\n", rc);
4171                 m->mdt_readpage_service = NULL;
4172
4173                 GOTO(err_mdt_svc, rc);
4174         }
4175
4176         /*
4177          * setattr service configuration.
4178          *
4179          * XXX To keep the compatibility with old client(< 2.2), we need to
4180          * preserve this portal for a certain time, it should be removed
4181          * eventually. LU-617.
4182          */
4183         memset(&conf, 0, sizeof(conf));
4184         conf = (typeof(conf)) {
4185                 .psc_name               = LUSTRE_MDT_NAME "_setattr",
4186                 .psc_watchdog_factor    = MDT_SERVICE_WATCHDOG_FACTOR,
4187                 .psc_buf                = {
4188                         .bc_nbufs               = MDS_NBUFS,
4189                         .bc_buf_size            = MDS_BUFSIZE,
4190                         .bc_req_max_size        = MDS_MAXREQSIZE,
4191                         .bc_rep_max_size        = MDS_MAXREPSIZE,
4192                         .bc_req_portal          = MDS_SETATTR_PORTAL,
4193                         .bc_rep_portal          = MDC_REPLY_PORTAL,
4194                 },
4195                 .psc_thr                = {
4196                         .tc_thr_name            = "mdt_attr",
4197                         .tc_thr_factor          = MDT_SETA_THR_FACTOR,
4198                         .tc_nthrs_init          = MDT_SETA_NTHRS_INIT,
4199                         .tc_nthrs_base          = MDT_SETA_NTHRS_BASE,
4200                         .tc_nthrs_max           = MDT_SETA_NTHRS_MAX,
4201                         .tc_nthrs_user          = mds_attr_num_threads,
4202                         .tc_cpu_affinity        = 1,
4203                         .tc_ctx_tags            = LCT_MD_THREAD,
4204                 },
4205                 .psc_cpt                = {
4206                         .cc_pattern             = mds_attr_num_cpts,
4207                 },
4208                 .psc_ops                = {
4209                         .so_req_handler         = mdt_regular_handle,
4210                         .so_req_printer         = target_print_req,
4211                         .so_hpreq_handler       = NULL,
4212                 },
4213         };
4214         m->mdt_setattr_service = ptlrpc_register_service(&conf, procfs_entry);
4215         if (IS_ERR(m->mdt_setattr_service)) {
4216                 rc = PTR_ERR(m->mdt_setattr_service);
4217                 CERROR("failed to start setattr service: %d\n", rc);
4218                 m->mdt_setattr_service = NULL;
4219
4220                 GOTO(err_mdt_svc, rc);
4221         }
4222
4223         /*
4224          * sequence controller service configuration
4225          */
4226         memset(&conf, 0, sizeof(conf));
4227         conf = (typeof(conf)) {
4228                 .psc_name               = LUSTRE_MDT_NAME "_mdsc",
4229                 .psc_watchdog_factor    = MDT_SERVICE_WATCHDOG_FACTOR,
4230                 .psc_buf                = {
4231                         .bc_nbufs               = MDS_NBUFS,
4232                         .bc_buf_size            = MDS_BUFSIZE,
4233                         .bc_req_max_size        = SEQ_MAXREQSIZE,
4234                         .bc_rep_max_size        = SEQ_MAXREPSIZE,
4235                         .bc_req_portal          = SEQ_CONTROLLER_PORTAL,
4236                         .bc_rep_portal          = MDC_REPLY_PORTAL,
4237                 },
4238                 .psc_thr                = {
4239                         .tc_thr_name            = "mdt_mdsc",
4240                         .tc_nthrs_init          = MDT_OTHR_NTHRS_INIT,
4241                         .tc_nthrs_max           = MDT_OTHR_NTHRS_MAX,
4242                         .tc_ctx_tags            = LCT_MD_THREAD,
4243                 },
4244                 .psc_ops                = {
4245                         .so_req_handler         = mdt_mdsc_handle,
4246                         .so_req_printer         = target_print_req,
4247                         .so_hpreq_handler       = NULL,
4248                 },
4249         };
4250         m->mdt_mdsc_service = ptlrpc_register_service(&conf, procfs_entry);
4251         if (IS_ERR(m->mdt_mdsc_service)) {
4252                 rc = PTR_ERR(m->mdt_mdsc_service);
4253                 CERROR("failed to start seq controller service: %d\n", rc);
4254                 m->mdt_mdsc_service = NULL;
4255
4256                 GOTO(err_mdt_svc, rc);
4257         }
4258
4259         /*
4260          * metadata sequence server service configuration
4261          */
4262         memset(&conf, 0, sizeof(conf));
4263         conf = (typeof(conf)) {
4264                 .psc_name               = LUSTRE_MDT_NAME "_mdss",
4265                 .psc_watchdog_factor    = MDT_SERVICE_WATCHDOG_FACTOR,
4266                 .psc_buf                = {
4267                         .bc_nbufs               = MDS_NBUFS,
4268                         .bc_buf_size            = MDS_BUFSIZE,
4269                         .bc_req_max_size        = SEQ_MAXREQSIZE,
4270                         .bc_rep_max_size        = SEQ_MAXREPSIZE,
4271                         .bc_req_portal          = SEQ_METADATA_PORTAL,
4272                         .bc_rep_portal          = MDC_REPLY_PORTAL,
4273                 },
4274                 .psc_thr                = {
4275                         .tc_thr_name            = "mdt_mdss",
4276                         .tc_nthrs_init          = MDT_OTHR_NTHRS_INIT,
4277                         .tc_nthrs_max           = MDT_OTHR_NTHRS_MAX,
4278                         .tc_ctx_tags            = LCT_MD_THREAD | LCT_DT_THREAD
4279                 },
4280                 .psc_ops                = {
4281                         .so_req_handler         = mdt_mdss_handle,
4282                         .so_req_printer         = target_print_req,
4283                         .so_hpreq_handler       = NULL,
4284                 },
4285         };
4286         m->mdt_mdss_service = ptlrpc_register_service(&conf, procfs_entry);
4287         if (IS_ERR(m->mdt_mdss_service)) {
4288                 rc = PTR_ERR(m->mdt_mdss_service);
4289                 CERROR("failed to start metadata seq server service: %d\n", rc);
4290                 m->mdt_mdss_service = NULL;
4291
4292                 GOTO(err_mdt_svc, rc);
4293         }
4294
4295         /*
4296          * Data sequence server service configuration. We want to have really
4297          * cluster-wide sequences space. This is why we start only one sequence
4298          * controller which manages space.
4299          */
4300         memset(&conf, 0, sizeof(conf));
4301         conf = (typeof(conf)) {
4302                 .psc_name               = LUSTRE_MDT_NAME "_dtss",
4303                 .psc_watchdog_factor    = MDT_SERVICE_WATCHDOG_FACTOR,
4304                 .psc_buf                = {
4305                         .bc_nbufs               = MDS_NBUFS,
4306                         .bc_buf_size            = MDS_BUFSIZE,
4307                         .bc_req_max_size        = SEQ_MAXREQSIZE,
4308                         .bc_rep_max_size        = SEQ_MAXREPSIZE,
4309                         .bc_req_portal          = SEQ_DATA_PORTAL,
4310                         .bc_rep_portal          = OSC_REPLY_PORTAL,
4311                 },
4312                 .psc_thr                = {
4313                         .tc_thr_name            = "mdt_dtss",
4314                         .tc_nthrs_init          = MDT_OTHR_NTHRS_INIT,
4315                         .tc_nthrs_max           = MDT_OTHR_NTHRS_MAX,
4316                         .tc_ctx_tags            = LCT_MD_THREAD | LCT_DT_THREAD
4317                 },
4318                 .psc_ops                = {
4319                         .so_req_handler         = mdt_dtss_handle,
4320                         .so_req_printer         = target_print_req,
4321                         .so_hpreq_handler       = NULL,
4322                 },
4323         };
4324         m->mdt_dtss_service = ptlrpc_register_service(&conf, procfs_entry);
4325         if (IS_ERR(m->mdt_dtss_service)) {
4326                 rc = PTR_ERR(m->mdt_dtss_service);
4327                 CERROR("failed to start data seq server service: %d\n", rc);
4328                 m->mdt_dtss_service = NULL;
4329
4330                 GOTO(err_mdt_svc, rc);
4331         }
4332
4333         /* FLD service start */
4334         memset(&conf, 0, sizeof(conf));
4335         conf = (typeof(conf)) {
4336                 .psc_name            = LUSTRE_MDT_NAME "_fld",
4337                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
4338                 .psc_buf                = {
4339                         .bc_nbufs               = MDS_NBUFS,
4340                         .bc_buf_size            = MDS_BUFSIZE,
4341                         .bc_req_max_size        = FLD_MAXREQSIZE,
4342                         .bc_rep_max_size        = FLD_MAXREPSIZE,
4343                         .bc_req_portal          = FLD_REQUEST_PORTAL,
4344                         .bc_rep_portal          = MDC_REPLY_PORTAL,
4345                 },
4346                 .psc_thr                = {
4347                         .tc_thr_name            = "mdt_fld",
4348                         .tc_nthrs_init          = MDT_OTHR_NTHRS_INIT,
4349                         .tc_nthrs_max           = MDT_OTHR_NTHRS_MAX,
4350                         .tc_ctx_tags            = LCT_DT_THREAD | LCT_MD_THREAD
4351                 },
4352                 .psc_ops                = {
4353                         .so_req_handler         = mdt_fld_handle,
4354                         .so_req_printer         = target_print_req,
4355                         .so_hpreq_handler       = NULL,
4356                 },
4357         };
4358         m->mdt_fld_service = ptlrpc_register_service(&conf, procfs_entry);
4359         if (IS_ERR(m->mdt_fld_service)) {
4360                 rc = PTR_ERR(m->mdt_fld_service);
4361                 CERROR("failed to start fld service: %d\n", rc);
4362                 m->mdt_fld_service = NULL;
4363
4364                 GOTO(err_mdt_svc, rc);
4365         }
4366
4367         /*
4368          * mds-mds service configuration. Separate portal is used to allow
4369          * mds-mds requests be not blocked during recovery.
4370          */
4371         memset(&conf, 0, sizeof(conf));
4372         conf = (typeof(conf)) {
4373                 .psc_name               = LUSTRE_MDT_NAME "_mds",
4374                 .psc_watchdog_factor    = MDT_SERVICE_WATCHDOG_FACTOR,
4375                 .psc_buf                = {
4376                         .bc_nbufs               = MDS_NBUFS,
4377                         .bc_buf_size            = MDS_BUFSIZE,
4378                         .bc_req_max_size        = MDS_MAXREQSIZE,
4379                         .bc_rep_max_size        = MDS_MAXREPSIZE,
4380                         .bc_req_portal          = MDS_MDS_PORTAL,
4381                         .bc_rep_portal          = MDC_REPLY_PORTAL,
4382                 },
4383                 .psc_thr                = {
4384                         .tc_thr_name            = "mdt_mds",
4385                         .tc_nthrs_init          = MDT_OTHR_NTHRS_INIT,
4386                         .tc_nthrs_max           = MDT_OTHR_NTHRS_MAX,
4387                         .tc_ctx_tags            = LCT_MD_THREAD,
4388                 },
4389                 .psc_ops                = {
4390                         .so_req_handler         = mdt_xmds_handle,
4391                         .so_req_printer         = target_print_req,
4392                         .so_hpreq_handler       = ptlrpc_hpreq_handler,
4393                 },
4394         };
4395         m->mdt_xmds_service = ptlrpc_register_service(&conf, procfs_entry);
4396         if (IS_ERR(m->mdt_xmds_service)) {
4397                 rc = PTR_ERR(m->mdt_xmds_service);
4398                 CERROR("failed to start xmds service: %d\n", rc);
4399                 m->mdt_xmds_service = NULL;
4400
4401                 GOTO(err_mdt_svc, rc);
4402         }
4403
4404         EXIT;
4405 err_mdt_svc:
4406         if (rc)
4407                 mdt_stop_ptlrpc_service(m);
4408
4409         return rc;
4410 }
4411
4412 static void mdt_stack_fini(const struct lu_env *env,
4413                            struct mdt_device *m, struct lu_device *top)
4414 {
4415         struct obd_device       *obd = mdt2obd_dev(m);
4416         struct lustre_cfg_bufs  *bufs;
4417         struct lustre_cfg       *lcfg;
4418         struct mdt_thread_info  *info;
4419         char flags[3]="";
4420         ENTRY;
4421
4422         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4423         LASSERT(info != NULL);
4424
4425         lu_dev_del_linkage(top->ld_site, top);
4426
4427         bufs = &info->mti_u.bufs;
4428         /* process cleanup, pass mdt obd name to get obd umount flags */
4429         lustre_cfg_bufs_reset(bufs, obd->obd_name);
4430         if (obd->obd_force)
4431                 strcat(flags, "F");
4432         if (obd->obd_fail)
4433                 strcat(flags, "A");
4434         lustre_cfg_bufs_set_string(bufs, 1, flags);
4435         lcfg = lustre_cfg_new(LCFG_CLEANUP, bufs);
4436         if (!lcfg) {
4437                 CERROR("Cannot alloc lcfg!\n");
4438                 return;
4439         }
4440         LASSERT(top);
4441         top->ld_ops->ldo_process_config(env, top, lcfg);
4442         lustre_cfg_free(lcfg);
4443
4444         lu_stack_fini(env, top);
4445         m->mdt_child = NULL;
4446         m->mdt_bottom = NULL;
4447
4448         obd_disconnect(m->mdt_bottom_exp);
4449 }
4450
4451 static struct lu_device *mdt_layer_setup(struct lu_env *env,
4452                                          const char *typename,
4453                                          struct lu_device *child,
4454                                          struct lustre_cfg *cfg)
4455 {
4456         const char            *dev = lustre_cfg_string(cfg, 0);
4457         struct obd_type       *type;
4458         struct lu_device_type *ldt;
4459         struct lu_device      *d;
4460         int rc;
4461         ENTRY;
4462
4463         /* find the type */
4464         type = class_get_type(typename);
4465         if (!type) {
4466                 CERROR("Unknown type: '%s'\n", typename);
4467                 GOTO(out, rc = -ENODEV);
4468         }
4469
4470         rc = lu_env_refill((struct lu_env *)env);
4471         if (rc != 0) {
4472                 CERROR("Failure to refill session: '%d'\n", rc);
4473                 GOTO(out_type, rc);
4474         }
4475
4476         ldt = type->typ_lu;
4477         if (ldt == NULL) {
4478                 CERROR("type: '%s'\n", typename);
4479                 GOTO(out_type, rc = -EINVAL);
4480         }
4481
4482         ldt->ldt_obd_type = type;
4483         d = ldt->ldt_ops->ldto_device_alloc(env, ldt, cfg);
4484         if (IS_ERR(d)) {
4485                 CERROR("Cannot allocate device: '%s'\n", typename);
4486                 GOTO(out_type, rc = -ENODEV);
4487         }
4488
4489         LASSERT(child->ld_site);
4490         d->ld_site = child->ld_site;
4491
4492         type->typ_refcnt++;
4493         rc = ldt->ldt_ops->ldto_device_init(env, d, dev, child);
4494         if (rc) {
4495                 CERROR("can't init device '%s', rc %d\n", typename, rc);
4496                 GOTO(out_alloc, rc);
4497         }
4498         lu_device_get(d);
4499         lu_ref_add(&d->ld_reference, "lu-stack", &lu_site_init);
4500
4501         lu_dev_add_linkage(d->ld_site, d);
4502         RETURN(d);
4503 out_alloc:
4504         ldt->ldt_ops->ldto_device_free(env, d);
4505         type->typ_refcnt--;
4506 out_type:
4507         class_put_type(type);
4508 out:
4509         return ERR_PTR(rc);
4510 }
4511
4512 static int mdt_connect_to_next(const struct lu_env *env, struct mdt_device *m,
4513                                const char *next, struct obd_export **exp)
4514 {
4515         struct obd_connect_data *data = NULL;
4516         struct obd_device       *obd;
4517         int                      rc;
4518         ENTRY;
4519
4520         OBD_ALLOC_PTR(data);
4521         if (data == NULL)
4522                 GOTO(out, rc = -ENOMEM);
4523
4524         obd = class_name2obd(next);
4525         if (obd == NULL) {
4526                 CERROR("%s: can't locate next device: %s\n",
4527                        m->mdt_md_dev.md_lu_dev.ld_obd->obd_name, next);
4528                 GOTO(out, rc = -ENOTCONN);
4529         }
4530
4531         data->ocd_connect_flags = OBD_CONNECT_VERSION;
4532         data->ocd_version = LUSTRE_VERSION_CODE;
4533
4534         rc = obd_connect(NULL, exp, obd, &obd->obd_uuid, data, NULL);
4535         if (rc) {
4536                 CERROR("%s: cannot connect to next dev %s (%d)\n",
4537                        m->mdt_md_dev.md_lu_dev.ld_obd->obd_name, next, rc);
4538                 GOTO(out, rc);
4539         }
4540
4541 out:
4542         if (data)
4543                 OBD_FREE_PTR(data);
4544         RETURN(rc);
4545 }
4546
4547 static int mdt_stack_init(struct lu_env *env,
4548                           struct mdt_device *m,
4549                           struct lustre_cfg *cfg,
4550                           struct lustre_mount_info  *lmi)
4551 {
4552         struct lu_device  *d = &m->mdt_md_dev.md_lu_dev;
4553         struct lu_device  *tmp;
4554         struct md_device  *md;
4555         struct lu_device  *child_lu_dev;
4556         char              *osdname;
4557         int rc;
4558         ENTRY;
4559
4560         /* find bottom osd */
4561         OBD_ALLOC(osdname, MTI_NAME_MAXLEN);
4562         if (osdname == NULL)
4563                 RETURN(-ENOMEM);
4564
4565         snprintf(osdname, MTI_NAME_MAXLEN, "%s-osd", lustre_cfg_string(cfg, 0));
4566         rc = mdt_connect_to_next(env, m, osdname, &m->mdt_bottom_exp);
4567         OBD_FREE(osdname, MTI_NAME_MAXLEN);
4568         if (rc)
4569                 RETURN(rc);
4570
4571         tmp = m->mdt_bottom_exp->exp_obd->obd_lu_dev;
4572         LASSERT(tmp);
4573         m->mdt_bottom = lu2dt_dev(tmp);
4574
4575         /* initialize site's pointers: md_site, top device */
4576         d->ld_site = tmp->ld_site;
4577         d->ld_site->ls_top_dev = d;
4578         m->mdt_mite.ms_lu = tmp->ld_site;
4579         tmp->ld_site->ld_md_site = &m->mdt_mite;
4580         LASSERT(d->ld_site);
4581         d = tmp;
4582
4583         tmp = mdt_layer_setup(env, LUSTRE_MDD_NAME, d, cfg);
4584         if (IS_ERR(tmp)) {
4585                 GOTO(out, rc = PTR_ERR(tmp));
4586         }
4587         d = tmp;
4588         md = lu2md_dev(d);
4589
4590         tmp = mdt_layer_setup(env, LUSTRE_CMM_NAME, d, cfg);
4591         if (IS_ERR(tmp)) {
4592                 GOTO(out, rc = PTR_ERR(tmp));
4593         }
4594         d = tmp;
4595         /*set mdd upcall device*/
4596         md_upcall_dev_set(md, lu2md_dev(d));
4597
4598         md = lu2md_dev(d);
4599         /*set cmm upcall device*/
4600         md_upcall_dev_set(md, &m->mdt_md_dev);
4601
4602         m->mdt_child = lu2md_dev(d);
4603
4604         /* process setup config */
4605         tmp = &m->mdt_md_dev.md_lu_dev;
4606         rc = tmp->ld_ops->ldo_process_config(env, tmp, cfg);
4607         if (rc)
4608                 GOTO(out, rc);
4609
4610         /* initialize local objects */
4611         child_lu_dev = &m->mdt_child->md_lu_dev;
4612
4613         rc = child_lu_dev->ld_ops->ldo_prepare(env,
4614                                                &m->mdt_md_dev.md_lu_dev,
4615                                                child_lu_dev);
4616 out:
4617         /* fini from last known good lu_device */
4618         if (rc)
4619                 mdt_stack_fini(env, m, d);
4620
4621         return rc;
4622 }
4623
4624 /**
4625  * setup CONFIG_ORIG context, used to access local config log.
4626  * this may need to be rewrite as part of llog rewrite for lu-api.
4627  */
4628 static int mdt_obd_llog_setup(struct obd_device *obd,
4629                               struct lustre_sb_info *lsi)
4630 {
4631         int     rc;
4632
4633         LASSERT(obd->obd_fsops == NULL);
4634
4635         obd->obd_fsops = fsfilt_get_ops(lsi->lsi_fstype);
4636         if (IS_ERR(obd->obd_fsops))
4637                 return PTR_ERR(obd->obd_fsops);
4638
4639         rc = fsfilt_setup(obd, lsi->lsi_srv_mnt->mnt_sb);
4640         if (rc) {
4641                 fsfilt_put_ops(obd->obd_fsops);
4642                 return rc;
4643         }
4644
4645         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
4646         obd->obd_lvfs_ctxt.pwdmnt = lsi->lsi_srv_mnt;
4647         obd->obd_lvfs_ctxt.pwd = lsi->lsi_srv_mnt->mnt_root;
4648         obd->obd_lvfs_ctxt.fs = get_ds();
4649
4650         rc = llog_setup(obd, &obd->obd_olg, LLOG_CONFIG_ORIG_CTXT, obd,
4651                         0, NULL, &llog_lvfs_ops);
4652         if (rc) {
4653                 CERROR("llog_setup() failed: %d\n", rc);
4654                 fsfilt_put_ops(obd->obd_fsops);
4655         }
4656
4657         return rc;
4658 }
4659
4660 static void mdt_obd_llog_cleanup(struct obd_device *obd)
4661 {
4662         struct llog_ctxt *ctxt;
4663
4664         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
4665         if (ctxt)
4666                 llog_cleanup(ctxt);
4667
4668         if (obd->obd_fsops) {
4669                 fsfilt_put_ops(obd->obd_fsops);
4670                 obd->obd_fsops = NULL;
4671         }
4672 }
4673
4674 static void mdt_fini(const struct lu_env *env, struct mdt_device *m)
4675 {
4676         struct md_device  *next = m->mdt_child;
4677         struct lu_device  *d    = &m->mdt_md_dev.md_lu_dev;
4678         struct obd_device *obd = mdt2obd_dev(m);
4679         ENTRY;
4680
4681         target_recovery_fini(obd);
4682
4683         ping_evictor_stop();
4684
4685         mdt_stop_ptlrpc_service(m);
4686         mdt_llog_ctxt_unclone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
4687         mdt_obd_llog_cleanup(obd);
4688         obd_exports_barrier(obd);
4689         obd_zombie_barrier();
4690
4691         mdt_procfs_fini(m);
4692
4693 #ifdef HAVE_QUOTA_SUPPORT
4694         next->md_ops->mdo_quota.mqo_cleanup(env, next);
4695 #endif
4696         lut_fini(env, &m->mdt_lut);
4697         mdt_fs_cleanup(env, m);
4698         upcall_cache_cleanup(m->mdt_identity_cache);
4699         m->mdt_identity_cache = NULL;
4700
4701         if (m->mdt_namespace != NULL) {
4702                 ldlm_namespace_free(m->mdt_namespace, NULL,
4703                                     d->ld_obd->obd_force);
4704                 d->ld_obd->obd_namespace = m->mdt_namespace = NULL;
4705         }
4706
4707         cfs_free_nidlist(&m->mdt_nosquash_nids);
4708         if (m->mdt_nosquash_str) {
4709                 OBD_FREE(m->mdt_nosquash_str, m->mdt_nosquash_strlen);
4710                 m->mdt_nosquash_str = NULL;
4711                 m->mdt_nosquash_strlen = 0;
4712         }
4713
4714         mdt_seq_fini(env, m);
4715         mdt_seq_fini_cli(m);
4716         mdt_fld_fini(env, m);
4717         sptlrpc_rule_set_free(&m->mdt_sptlrpc_rset);
4718
4719         next->md_ops->mdo_init_capa_ctxt(env, next, 0, 0, 0, NULL);
4720         cfs_timer_disarm(&m->mdt_ck_timer);
4721         mdt_ck_thread_stop(m);
4722
4723         /*
4724          * Finish the stack
4725          */
4726         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
4727
4728         LASSERT(cfs_atomic_read(&d->ld_ref) == 0);
4729
4730         server_put_mount(mdt2obd_dev(m)->obd_name, NULL);
4731
4732         EXIT;
4733 }
4734
4735 static int mdt_adapt_sptlrpc_conf(struct obd_device *obd, int initial)
4736 {
4737         struct mdt_device       *m = mdt_dev(obd->obd_lu_dev);
4738         struct sptlrpc_rule_set  tmp_rset;
4739         int                      rc;
4740
4741         sptlrpc_rule_set_init(&tmp_rset);
4742         rc = sptlrpc_conf_target_get_rules(obd, &tmp_rset, initial);
4743         if (rc) {
4744                 CERROR("mdt %s: failed get sptlrpc rules: %d\n",
4745                        obd->obd_name, rc);
4746                 return rc;
4747         }
4748
4749         sptlrpc_target_update_exp_flavor(obd, &tmp_rset);
4750
4751         cfs_write_lock(&m->mdt_sptlrpc_lock);
4752         sptlrpc_rule_set_free(&m->mdt_sptlrpc_rset);
4753         m->mdt_sptlrpc_rset = tmp_rset;
4754         cfs_write_unlock(&m->mdt_sptlrpc_lock);
4755
4756         return 0;
4757 }
4758
4759 int mdt_postrecov(const struct lu_env *, struct mdt_device *);
4760
4761 static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
4762                      struct lu_device_type *ldt, struct lustre_cfg *cfg)
4763 {
4764         struct mdt_thread_info    *info;
4765         struct obd_device         *obd;
4766         const char                *dev = lustre_cfg_string(cfg, 0);
4767         const char                *num = lustre_cfg_string(cfg, 2);
4768         struct lustre_mount_info  *lmi = NULL;
4769         struct lustre_sb_info     *lsi;
4770         struct lu_site            *s;
4771         struct md_site            *mite;
4772         const char                *identity_upcall = "NONE";
4773         struct md_device          *next;
4774         int                        rc;
4775         int                        node_id;
4776         mntopt_t                   mntopts;
4777         ENTRY;
4778
4779         md_device_init(&m->mdt_md_dev, ldt);
4780         /*
4781          * Environment (env) might be missing mdt_thread_key values at that
4782          * point, if device is allocated when mdt_thread_key is in QUIESCENT
4783          * mode.
4784          *
4785          * Usually device allocation path doesn't use module key values, but
4786          * mdt has to do a lot of work here, so allocate key value.
4787          */
4788         rc = lu_env_refill((struct lu_env *)env);
4789         if (rc != 0)
4790                 RETURN(rc);
4791
4792         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4793         LASSERT(info != NULL);
4794
4795         obd = class_name2obd(dev);
4796         LASSERT(obd != NULL);
4797
4798         m->mdt_max_mdsize = MAX_MD_SIZE; /* 4 stripes */
4799         m->mdt_max_cookiesize = sizeof(struct llog_cookie);
4800
4801         m->mdt_som_conf = 0;
4802
4803         m->mdt_opts.mo_cos = MDT_COS_DEFAULT;
4804         lmi = server_get_mount(dev);
4805         if (lmi == NULL) {
4806                 CERROR("Cannot get mount info for %s!\n", dev);
4807                 RETURN(-EFAULT);
4808         } else {
4809                 lsi = s2lsi(lmi->lmi_sb);
4810                 /* CMD is supported only in IAM mode */
4811                 LASSERT(num);
4812                 node_id = simple_strtol(num, NULL, 10);
4813                 if (!(lsi->lsi_flags & LDD_F_IAM_DIR) && node_id) {
4814                         CERROR("CMD Operation not allowed in IOP mode\n");
4815                         GOTO(err_lmi, rc = -EINVAL);
4816                 }
4817
4818                 obd->u.obt.obt_magic = OBT_MAGIC;
4819         }
4820
4821         cfs_rwlock_init(&m->mdt_sptlrpc_lock);
4822         sptlrpc_rule_set_init(&m->mdt_sptlrpc_rset);
4823
4824         cfs_spin_lock_init(&m->mdt_ioepoch_lock);
4825         m->mdt_opts.mo_compat_resname = 0;
4826         m->mdt_opts.mo_mds_capa = 1;
4827         m->mdt_opts.mo_oss_capa = 1;
4828         m->mdt_capa_timeout = CAPA_TIMEOUT;
4829         m->mdt_capa_alg = CAPA_HMAC_ALG_SHA1;
4830         m->mdt_ck_timeout = CAPA_KEY_TIMEOUT;
4831         m->mdt_squash_uid = 0;
4832         m->mdt_squash_gid = 0;
4833         CFS_INIT_LIST_HEAD(&m->mdt_nosquash_nids);
4834         m->mdt_nosquash_str = NULL;
4835         m->mdt_nosquash_strlen = 0;
4836         cfs_init_rwsem(&m->mdt_squash_sem);
4837         cfs_spin_lock_init(&m->mdt_osfs_lock);
4838         m->mdt_osfs_age = cfs_time_shift_64(-1000);
4839
4840         m->mdt_md_dev.md_lu_dev.ld_ops = &mdt_lu_ops;
4841         m->mdt_md_dev.md_lu_dev.ld_obd = obd;
4842         /* set this lu_device to obd, because error handling need it */
4843         obd->obd_lu_dev = &m->mdt_md_dev.md_lu_dev;
4844
4845         /* init the stack */
4846         rc = mdt_stack_init((struct lu_env *)env, m, cfg, lmi);
4847         if (rc) {
4848                 CERROR("Can't init device stack, rc %d\n", rc);
4849                 RETURN(rc);
4850         }
4851
4852         s = m->mdt_md_dev.md_lu_dev.ld_site;
4853         mite = &m->mdt_mite;
4854
4855         /* set server index */
4856         mite->ms_node_id = node_id;
4857
4858         /* failover is the default
4859          * FIXME: we do not failout mds0/mgs, which may cause some problems.
4860          * assumed whose ms_node_id == 0 XXX
4861          * */
4862         obd->obd_replayable = 1;
4863         /* No connection accepted until configurations will finish */
4864         obd->obd_no_conn = 1;
4865
4866         if (cfg->lcfg_bufcount > 4 && LUSTRE_CFG_BUFLEN(cfg, 4) > 0) {
4867                 char *str = lustre_cfg_string(cfg, 4);
4868                 if (strchr(str, 'n')) {
4869                         CWARN("%s: recovery disabled\n", obd->obd_name);
4870                         obd->obd_replayable = 0;
4871                 }
4872         }
4873
4874         rc = lut_init(env, &m->mdt_lut, obd, m->mdt_bottom);
4875         if (rc)
4876                 GOTO(err_fini_stack, rc);
4877
4878         rc = mdt_fld_init(env, obd->obd_name, m);
4879         if (rc)
4880                 GOTO(err_lut, rc);
4881
4882         rc = mdt_seq_init(env, obd->obd_name, m);
4883         if (rc)
4884                 GOTO(err_fini_fld, rc);
4885
4886         snprintf(info->mti_u.ns_name, sizeof info->mti_u.ns_name,
4887                  LUSTRE_MDT_NAME"-%p", m);
4888         m->mdt_namespace = ldlm_namespace_new(obd, info->mti_u.ns_name,
4889                                               LDLM_NAMESPACE_SERVER,
4890                                               LDLM_NAMESPACE_GREEDY,
4891                                               LDLM_NS_TYPE_MDT);
4892         if (m->mdt_namespace == NULL)
4893                 GOTO(err_fini_seq, rc = -ENOMEM);
4894
4895         ldlm_register_intent(m->mdt_namespace, mdt_intent_policy);
4896         /* set obd_namespace for compatibility with old code */
4897         obd->obd_namespace = m->mdt_namespace;
4898
4899         cfs_timer_init(&m->mdt_ck_timer, mdt_ck_timer_callback, m);
4900
4901         rc = mdt_ck_thread_start(m);
4902         if (rc)
4903                 GOTO(err_free_ns, rc);
4904
4905         rc = mdt_fs_setup(env, m, obd, lsi);
4906         if (rc)
4907                 GOTO(err_capa, rc);
4908
4909         rc = mdt_obd_llog_setup(obd, lsi);
4910         if (rc)
4911                 GOTO(err_fs_cleanup, rc);
4912
4913         rc = mdt_llog_ctxt_clone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
4914         if (rc)
4915                 GOTO(err_llog_cleanup, rc);
4916
4917         mdt_adapt_sptlrpc_conf(obd, 1);
4918
4919         next = m->mdt_child;
4920 #ifdef HAVE_QUOTA_SUPPORT
4921         rc = next->md_ops->mdo_quota.mqo_setup(env, next, lmi->lmi_mnt);
4922         if (rc)
4923                 GOTO(err_llog_cleanup, rc);
4924 #endif
4925
4926         rc = next->md_ops->mdo_iocontrol(env, next, OBD_IOC_GET_MNTOPT, 0,
4927                                          &mntopts);
4928         if (rc)
4929                 GOTO(err_quota, rc);
4930
4931         if (mntopts & MNTOPT_USERXATTR)
4932                 m->mdt_opts.mo_user_xattr = 1;
4933         else
4934                 m->mdt_opts.mo_user_xattr = 0;
4935
4936         if (mntopts & MNTOPT_ACL)
4937                 m->mdt_opts.mo_acl = 1;
4938         else
4939                 m->mdt_opts.mo_acl = 0;
4940
4941         /* XXX: to support suppgid for ACL, we enable identity_upcall
4942          * by default, otherwise, maybe got unexpected -EACCESS. */
4943         if (m->mdt_opts.mo_acl)
4944                 identity_upcall = MDT_IDENTITY_UPCALL_PATH;
4945
4946         m->mdt_identity_cache = upcall_cache_init(obd->obd_name,identity_upcall,
4947                                                 &mdt_identity_upcall_cache_ops);
4948         if (IS_ERR(m->mdt_identity_cache)) {
4949                 rc = PTR_ERR(m->mdt_identity_cache);
4950                 m->mdt_identity_cache = NULL;
4951                 GOTO(err_quota, rc);
4952         }
4953
4954         target_recovery_init(&m->mdt_lut, mdt_recovery_handle);
4955
4956         rc = mdt_procfs_init(m, dev);
4957         if (rc) {
4958                 CERROR("Can't init MDT lprocfs, rc %d\n", rc);
4959                 GOTO(err_recovery, rc);
4960         }
4961
4962         rc = mdt_start_ptlrpc_service(m);
4963         if (rc)
4964                 GOTO(err_procfs, rc);
4965
4966         ping_evictor_start();
4967
4968         if (obd->obd_recovering == 0)
4969                 mdt_postrecov(env, m);
4970
4971         mdt_init_capa_ctxt(env, m);
4972
4973         /* Reduce the initial timeout on an MDS because it doesn't need such
4974          * a long timeout as an OST does. Adaptive timeouts will adjust this
4975          * value appropriately. */
4976         if (ldlm_timeout == LDLM_TIMEOUT_DEFAULT)
4977                 ldlm_timeout = MDS_LDLM_TIMEOUT_DEFAULT;
4978
4979         RETURN(0);
4980
4981         ping_evictor_stop();
4982         mdt_stop_ptlrpc_service(m);
4983 err_procfs:
4984         mdt_procfs_fini(m);
4985 err_recovery:
4986         target_recovery_fini(obd);
4987         upcall_cache_cleanup(m->mdt_identity_cache);
4988         m->mdt_identity_cache = NULL;
4989 err_quota:
4990 #ifdef HAVE_QUOTA_SUPPORT
4991         next->md_ops->mdo_quota.mqo_cleanup(env, next);
4992 #endif
4993 err_llog_cleanup:
4994         mdt_llog_ctxt_unclone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
4995         mdt_obd_llog_cleanup(obd);
4996 err_fs_cleanup:
4997         mdt_fs_cleanup(env, m);
4998 err_capa:
4999         cfs_timer_disarm(&m->mdt_ck_timer);
5000         mdt_ck_thread_stop(m);
5001 err_free_ns:
5002         ldlm_namespace_free(m->mdt_namespace, NULL, 0);
5003         obd->obd_namespace = m->mdt_namespace = NULL;
5004 err_fini_seq:
5005         mdt_seq_fini(env, m);
5006 err_fini_fld:
5007         mdt_fld_fini(env, m);
5008 err_lut:
5009         lut_fini(env, &m->mdt_lut);
5010 err_fini_stack:
5011         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
5012 err_lmi:
5013         if (lmi)
5014                 server_put_mount(dev, lmi->lmi_mnt);
5015         return (rc);
5016 }
5017
5018 /* For interoperability between 1.8 and 2.0. */
5019 static struct cfg_interop_param mdt_interop_param[] = {
5020         { "mdt.group_upcall",   NULL },
5021         { "mdt.quota_type",     "mdd.quota_type" },
5022         { "mdt.rootsquash",     "mdt.root_squash" },
5023         { "mdt.nosquash_nid",   "mdt.nosquash_nids" },
5024         { NULL }
5025 };
5026
5027 /* used by MGS to process specific configurations */
5028 static int mdt_process_config(const struct lu_env *env,
5029                               struct lu_device *d, struct lustre_cfg *cfg)
5030 {
5031         struct mdt_device *m = mdt_dev(d);
5032         struct md_device *md_next = m->mdt_child;
5033         struct lu_device *next = md2lu_dev(md_next);
5034         int rc = 0;
5035         ENTRY;
5036
5037         switch (cfg->lcfg_command) {
5038         case LCFG_PARAM: {
5039                 struct lprocfs_static_vars  lvars;
5040                 struct obd_device          *obd = d->ld_obd;
5041
5042                 /* For interoperability between 1.8 and 2.0. */
5043                 struct cfg_interop_param   *ptr = NULL;
5044                 struct lustre_cfg          *old_cfg = NULL;
5045                 char                       *param = NULL;
5046
5047                 param = lustre_cfg_string(cfg, 1);
5048                 if (param == NULL) {
5049                         CERROR("param is empty\n");
5050                         rc = -EINVAL;
5051                         break;
5052                 }
5053
5054                 ptr = class_find_old_param(param, mdt_interop_param);
5055                 if (ptr != NULL) {
5056                         if (ptr->new_param == NULL) {
5057                                 CWARN("For 1.8 interoperability, skip this %s."
5058                                       " It is obsolete.\n", ptr->old_param);
5059                                         break;
5060                         }
5061
5062                         CWARN("Found old param %s, changed it to %s.\n",
5063                               ptr->old_param, ptr->new_param);
5064
5065                         old_cfg = cfg;
5066                         cfg = lustre_cfg_rename(old_cfg, ptr->new_param);
5067                         if (IS_ERR(cfg)) {
5068                                 rc = PTR_ERR(cfg);
5069                                 break;
5070                         }
5071                 }
5072
5073                 lprocfs_mdt_init_vars(&lvars);
5074                 rc = class_process_proc_param(PARAM_MDT, lvars.obd_vars,
5075                                               cfg, obd);
5076                 if (rc > 0 || rc == -ENOSYS)
5077                         /* we don't understand; pass it on */
5078                         rc = next->ld_ops->ldo_process_config(env, next, cfg);
5079
5080                 if (old_cfg != NULL)
5081                         lustre_cfg_free(cfg);
5082
5083                 break;
5084         }
5085         case LCFG_ADD_MDC:
5086                 /*
5087                  * Add mdc hook to get first MDT uuid and connect it to
5088                  * ls->controller to use for seq manager.
5089                  */
5090                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
5091                 if (rc)
5092                         CERROR("Can't add mdc, rc %d\n", rc);
5093                 else
5094                         rc = mdt_seq_init_cli(env, mdt_dev(d), cfg);
5095                 break;
5096         default:
5097                 /* others are passed further */
5098                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
5099                 break;
5100         }
5101         RETURN(rc);
5102 }
5103
5104 static struct lu_object *mdt_object_alloc(const struct lu_env *env,
5105                                           const struct lu_object_header *hdr,
5106                                           struct lu_device *d)
5107 {
5108         struct mdt_object *mo;
5109
5110         ENTRY;
5111
5112         OBD_SLAB_ALLOC_PTR_GFP(mo, mdt_object_kmem, CFS_ALLOC_IO);
5113         if (mo != NULL) {
5114                 struct lu_object *o;
5115                 struct lu_object_header *h;
5116
5117                 o = &mo->mot_obj.mo_lu;
5118                 h = &mo->mot_header;
5119                 lu_object_header_init(h);
5120                 lu_object_init(o, h, d);
5121                 lu_object_add_top(h, o);
5122                 o->lo_ops = &mdt_obj_ops;
5123                 cfs_mutex_init(&mo->mot_ioepoch_mutex);
5124                 cfs_mutex_init(&mo->mot_lov_mutex);
5125                 RETURN(o);
5126         } else
5127                 RETURN(NULL);
5128 }
5129
5130 static int mdt_object_init(const struct lu_env *env, struct lu_object *o,
5131                            const struct lu_object_conf *unused)
5132 {
5133         struct mdt_device *d = mdt_dev(o->lo_dev);
5134         struct lu_device  *under;
5135         struct lu_object  *below;
5136         int                rc = 0;
5137         ENTRY;
5138
5139         CDEBUG(D_INFO, "object init, fid = "DFID"\n",
5140                PFID(lu_object_fid(o)));
5141
5142         under = &d->mdt_child->md_lu_dev;
5143         below = under->ld_ops->ldo_object_alloc(env, o->lo_header, under);
5144         if (below != NULL) {
5145                 lu_object_add(o, below);
5146         } else
5147                 rc = -ENOMEM;
5148
5149         RETURN(rc);
5150 }
5151
5152 static void mdt_object_free(const struct lu_env *env, struct lu_object *o)
5153 {
5154         struct mdt_object *mo = mdt_obj(o);
5155         struct lu_object_header *h;
5156         ENTRY;
5157
5158         h = o->lo_header;
5159         CDEBUG(D_INFO, "object free, fid = "DFID"\n",
5160                PFID(lu_object_fid(o)));
5161
5162         lu_object_fini(o);
5163         lu_object_header_fini(h);
5164         OBD_SLAB_FREE_PTR(mo, mdt_object_kmem);
5165
5166         EXIT;
5167 }
5168
5169 static int mdt_object_print(const struct lu_env *env, void *cookie,
5170                             lu_printer_t p, const struct lu_object *o)
5171 {
5172         struct mdt_object *mdto = mdt_obj((struct lu_object *)o);
5173         return (*p)(env, cookie, LUSTRE_MDT_NAME"-object@%p(ioepoch="LPU64" "
5174                     "flags="LPX64", epochcount=%d, writecount=%d)",
5175                     mdto, mdto->mot_ioepoch, mdto->mot_flags,
5176                     mdto->mot_ioepoch_count, mdto->mot_writecount);
5177 }
5178
5179 static const struct lu_device_operations mdt_lu_ops = {
5180         .ldo_object_alloc   = mdt_object_alloc,
5181         .ldo_process_config = mdt_process_config,
5182 };
5183
5184 static const struct lu_object_operations mdt_obj_ops = {
5185         .loo_object_init    = mdt_object_init,
5186         .loo_object_free    = mdt_object_free,
5187         .loo_object_print   = mdt_object_print
5188 };
5189
5190 static int mdt_obd_set_info_async(const struct lu_env *env,
5191                                   struct obd_export *exp,
5192                                   __u32 keylen, void *key,
5193                                   __u32 vallen, void *val,
5194                                   struct ptlrpc_request_set *set)
5195 {
5196         struct obd_device     *obd = exp->exp_obd;
5197         int                    rc;
5198         ENTRY;
5199
5200         LASSERT(obd);
5201
5202         if (KEY_IS(KEY_SPTLRPC_CONF)) {
5203                 rc = mdt_adapt_sptlrpc_conf(obd, 0);
5204                 RETURN(rc);
5205         }
5206
5207         RETURN(0);
5208 }
5209
5210 /* mds_connect_internal */
5211 static int mdt_connect_internal(struct obd_export *exp,
5212                                 struct mdt_device *mdt,
5213                                 struct obd_connect_data *data)
5214 {
5215         if (data != NULL) {
5216                 data->ocd_connect_flags &= MDT_CONNECT_SUPPORTED;
5217                 data->ocd_ibits_known &= MDS_INODELOCK_FULL;
5218
5219                 /* If no known bits (which should not happen, probably,
5220                    as everybody should support LOOKUP and UPDATE bits at least)
5221                    revert to compat mode with plain locks. */
5222                 if (!data->ocd_ibits_known &&
5223                     data->ocd_connect_flags & OBD_CONNECT_IBITS)
5224                         data->ocd_connect_flags &= ~OBD_CONNECT_IBITS;
5225
5226                 if (!mdt->mdt_opts.mo_acl)
5227                         data->ocd_connect_flags &= ~OBD_CONNECT_ACL;
5228
5229                 if (!mdt->mdt_opts.mo_user_xattr)
5230                         data->ocd_connect_flags &= ~OBD_CONNECT_XATTR;
5231
5232                 if (!mdt->mdt_som_conf)
5233                         data->ocd_connect_flags &= ~OBD_CONNECT_SOM;
5234
5235                 if (data->ocd_connect_flags & OBD_CONNECT_BRW_SIZE) {
5236                         data->ocd_brw_size = min(data->ocd_brw_size,
5237                                (__u32)(PTLRPC_MAX_BRW_PAGES << CFS_PAGE_SHIFT));
5238                         if (data->ocd_brw_size == 0) {
5239                                 CERROR("%s: cli %s/%p ocd_connect_flags: "LPX64
5240                                        " ocd_version: %x ocd_grant: %d "
5241                                        "ocd_index: %u ocd_brw_size is "
5242                                        "unexpectedly zero, network data "
5243                                        "corruption? Refusing connection of this"
5244                                        " client\n",
5245                                        exp->exp_obd->obd_name,
5246                                        exp->exp_client_uuid.uuid,
5247                                        exp, data->ocd_connect_flags, data->ocd_version,
5248                                        data->ocd_grant, data->ocd_index);
5249                                 return -EPROTO;
5250                         }
5251                 }
5252
5253                 cfs_spin_lock(&exp->exp_lock);
5254                 exp->exp_connect_flags = data->ocd_connect_flags;
5255                 cfs_spin_unlock(&exp->exp_lock);
5256                 data->ocd_version = LUSTRE_VERSION_CODE;
5257                 exp->exp_mdt_data.med_ibits_known = data->ocd_ibits_known;
5258         }
5259
5260 #if 0
5261         if (mdt->mdt_opts.mo_acl &&
5262             ((exp->exp_connect_flags & OBD_CONNECT_ACL) == 0)) {
5263                 CWARN("%s: MDS requires ACL support but client does not\n",
5264                       mdt->mdt_md_dev.md_lu_dev.ld_obd->obd_name);
5265                 return -EBADE;
5266         }
5267 #endif
5268
5269         if ((exp->exp_connect_flags & OBD_CONNECT_FID) == 0) {
5270                 CWARN("%s: MDS requires FID support, but client not\n",
5271                       mdt->mdt_md_dev.md_lu_dev.ld_obd->obd_name);
5272                 return -EBADE;
5273         }
5274
5275         if (mdt->mdt_som_conf && !exp_connect_som(exp) &&
5276             !(exp->exp_connect_flags & OBD_CONNECT_MDS_MDS)) {
5277                 CWARN("%s: MDS has SOM enabled, but client does not support "
5278                       "it\n", mdt->mdt_md_dev.md_lu_dev.ld_obd->obd_name);
5279                 return -EBADE;
5280         }
5281
5282         return 0;
5283 }
5284
5285 static int mdt_connect_check_sptlrpc(struct mdt_device *mdt,
5286                                      struct obd_export *exp,
5287                                      struct ptlrpc_request *req)
5288 {
5289         struct sptlrpc_flavor   flvr;
5290         int                     rc = 0;
5291
5292         if (exp->exp_flvr.sf_rpc == SPTLRPC_FLVR_INVALID) {
5293                 cfs_read_lock(&mdt->mdt_sptlrpc_lock);
5294                 sptlrpc_target_choose_flavor(&mdt->mdt_sptlrpc_rset,
5295                                              req->rq_sp_from,
5296                                              req->rq_peer.nid,
5297                                              &flvr);
5298                 cfs_read_unlock(&mdt->mdt_sptlrpc_lock);
5299
5300                 cfs_spin_lock(&exp->exp_lock);
5301
5302                 exp->exp_sp_peer = req->rq_sp_from;
5303                 exp->exp_flvr = flvr;
5304
5305                 if (exp->exp_flvr.sf_rpc != SPTLRPC_FLVR_ANY &&
5306                     exp->exp_flvr.sf_rpc != req->rq_flvr.sf_rpc) {
5307                         CERROR("unauthorized rpc flavor %x from %s, "
5308                                "expect %x\n", req->rq_flvr.sf_rpc,
5309                                libcfs_nid2str(req->rq_peer.nid),
5310                                exp->exp_flvr.sf_rpc);
5311                         rc = -EACCES;
5312                 }
5313
5314                 cfs_spin_unlock(&exp->exp_lock);
5315         } else {
5316                 if (exp->exp_sp_peer != req->rq_sp_from) {
5317                         CERROR("RPC source %s doesn't match %s\n",
5318                                sptlrpc_part2name(req->rq_sp_from),
5319                                sptlrpc_part2name(exp->exp_sp_peer));
5320                         rc = -EACCES;
5321                 } else {
5322                         rc = sptlrpc_target_export_check(exp, req);
5323                 }
5324         }
5325
5326         return rc;
5327 }
5328
5329 /* mds_connect copy */
5330 static int mdt_obd_connect(const struct lu_env *env,
5331                            struct obd_export **exp, struct obd_device *obd,
5332                            struct obd_uuid *cluuid,
5333                            struct obd_connect_data *data,
5334                            void *localdata)
5335 {
5336         struct mdt_thread_info *info;
5337         struct obd_export      *lexp;
5338         struct lustre_handle    conn = { 0 };
5339         struct mdt_device      *mdt;
5340         struct ptlrpc_request  *req;
5341         int                     rc;
5342         ENTRY;
5343
5344         LASSERT(env != NULL);
5345         if (!exp || !obd || !cluuid)
5346                 RETURN(-EINVAL);
5347
5348         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
5349         req = info->mti_pill->rc_req;
5350         mdt = mdt_dev(obd->obd_lu_dev);
5351
5352         rc = class_connect(&conn, obd, cluuid);
5353         if (rc)
5354                 RETURN(rc);
5355
5356         lexp = class_conn2export(&conn);
5357         LASSERT(lexp != NULL);
5358
5359         rc = mdt_connect_check_sptlrpc(mdt, lexp, req);
5360         if (rc)
5361                 GOTO(out, rc);
5362
5363         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_RCVG_FLAG))
5364                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
5365
5366         rc = mdt_connect_internal(lexp, mdt, data);
5367         if (rc == 0) {
5368                 struct lsd_client_data *lcd = lexp->exp_target_data.ted_lcd;
5369
5370                 LASSERT(lcd);
5371                 info->mti_exp = lexp;
5372                 memcpy(lcd->lcd_uuid, cluuid, sizeof lcd->lcd_uuid);
5373                 rc = lut_client_new(env, lexp);
5374                 if (rc == 0)
5375                         mdt_export_stats_init(obd, lexp, localdata);
5376         }
5377
5378 out:
5379         if (rc != 0) {
5380                 class_disconnect(lexp);
5381                 *exp = NULL;
5382         } else {
5383                 *exp = lexp;
5384         }
5385
5386         RETURN(rc);
5387 }
5388
5389 static int mdt_obd_reconnect(const struct lu_env *env,
5390                              struct obd_export *exp, struct obd_device *obd,
5391                              struct obd_uuid *cluuid,
5392                              struct obd_connect_data *data,
5393                              void *localdata)
5394 {
5395         struct mdt_thread_info *info;
5396         struct mdt_device      *mdt;
5397         struct ptlrpc_request  *req;
5398         int                     rc;
5399         ENTRY;
5400
5401         if (exp == NULL || obd == NULL || cluuid == NULL)
5402                 RETURN(-EINVAL);
5403
5404         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
5405         req = info->mti_pill->rc_req;
5406         mdt = mdt_dev(obd->obd_lu_dev);
5407
5408         rc = mdt_connect_check_sptlrpc(mdt, exp, req);
5409         if (rc)
5410                 RETURN(rc);
5411
5412         rc = mdt_connect_internal(exp, mdt_dev(obd->obd_lu_dev), data);
5413         if (rc == 0)
5414                 mdt_export_stats_init(obd, exp, localdata);
5415
5416         RETURN(rc);
5417 }
5418
5419 static int mdt_export_cleanup(struct obd_export *exp)
5420 {
5421         struct mdt_export_data *med = &exp->exp_mdt_data;
5422         struct obd_device      *obd = exp->exp_obd;
5423         struct mdt_device      *mdt;
5424         struct mdt_thread_info *info;
5425         struct lu_env           env;
5426         CFS_LIST_HEAD(closing_list);
5427         struct mdt_file_data *mfd, *n;
5428         int rc = 0;
5429         ENTRY;
5430
5431         cfs_spin_lock(&med->med_open_lock);
5432         while (!cfs_list_empty(&med->med_open_head)) {
5433                 cfs_list_t *tmp = med->med_open_head.next;
5434                 mfd = cfs_list_entry(tmp, struct mdt_file_data, mfd_list);
5435
5436                 /* Remove mfd handle so it can't be found again.
5437                  * We are consuming the mfd_list reference here. */
5438                 class_handle_unhash(&mfd->mfd_handle);
5439                 cfs_list_move_tail(&mfd->mfd_list, &closing_list);
5440         }
5441         cfs_spin_unlock(&med->med_open_lock);
5442         mdt = mdt_dev(obd->obd_lu_dev);
5443         LASSERT(mdt != NULL);
5444
5445         rc = lu_env_init(&env, LCT_MD_THREAD);
5446         if (rc)
5447                 RETURN(rc);
5448
5449         info = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5450         LASSERT(info != NULL);
5451         memset(info, 0, sizeof *info);
5452         info->mti_env = &env;
5453         info->mti_mdt = mdt;
5454         info->mti_exp = exp;
5455
5456         if (!cfs_list_empty(&closing_list)) {
5457                 struct md_attr *ma = &info->mti_attr;
5458                 int lmm_size;
5459                 int cookie_size;
5460
5461                 lmm_size = mdt->mdt_max_mdsize;
5462                 OBD_ALLOC_LARGE(ma->ma_lmm, lmm_size);
5463                 if (ma->ma_lmm == NULL)
5464                         GOTO(out_lmm, rc = -ENOMEM);
5465
5466                 cookie_size = mdt->mdt_max_cookiesize;
5467                 OBD_ALLOC_LARGE(ma->ma_cookie, cookie_size);
5468                 if (ma->ma_cookie == NULL)
5469                         GOTO(out_cookie, rc = -ENOMEM);
5470
5471                 /* Close any open files (which may also cause orphan unlinking). */
5472                 cfs_list_for_each_entry_safe(mfd, n, &closing_list, mfd_list) {
5473                         cfs_list_del_init(&mfd->mfd_list);
5474                         memset(&ma->ma_attr, 0, sizeof(ma->ma_attr));
5475                         ma->ma_lmm_size = lmm_size;
5476                         ma->ma_cookie_size = cookie_size;
5477                         ma->ma_need = 0;
5478                         /* It is not for setattr, just tell MDD to send
5479                          * DESTROY RPC to OSS if needed */
5480                         ma->ma_valid = MA_FLAGS;
5481                         ma->ma_attr_flags = MDS_CLOSE_CLEANUP;
5482                         /* Don't unlink orphan on failover umount, LU-184 */
5483                         if (exp->exp_flags & OBD_OPT_FAILOVER)
5484                                 ma->ma_attr_flags |= MDS_KEEP_ORPHAN;
5485                         mdt_mfd_close(info, mfd);
5486                 }
5487                 OBD_FREE_LARGE(ma->ma_cookie, cookie_size);
5488                 ma->ma_cookie = NULL;
5489 out_cookie:
5490                 OBD_FREE_LARGE(ma->ma_lmm, lmm_size);
5491                 ma->ma_lmm = NULL;
5492         }
5493 out_lmm:
5494         info->mti_mdt = NULL;
5495         /* cleanup client slot early */
5496         /* Do not erase record for recoverable client. */
5497         if (!(exp->exp_flags & OBD_OPT_FAILOVER) || exp->exp_failed)
5498                 lut_client_del(&env, exp);
5499         lu_env_fini(&env);
5500
5501         RETURN(rc);
5502 }
5503
5504 static int mdt_obd_disconnect(struct obd_export *exp)
5505 {
5506         int rc;
5507         ENTRY;
5508
5509         LASSERT(exp);
5510         class_export_get(exp);
5511
5512         rc = server_disconnect_export(exp);
5513         if (rc != 0)
5514                 CDEBUG(D_IOCTL, "server disconnect error: %d\n", rc);
5515
5516         rc = mdt_export_cleanup(exp);
5517         class_export_put(exp);
5518         RETURN(rc);
5519 }
5520
5521 /* FIXME: Can we avoid using these two interfaces? */
5522 static int mdt_init_export(struct obd_export *exp)
5523 {
5524         struct mdt_export_data *med = &exp->exp_mdt_data;
5525         int                     rc;
5526         ENTRY;
5527
5528         CFS_INIT_LIST_HEAD(&med->med_open_head);
5529         cfs_spin_lock_init(&med->med_open_lock);
5530         cfs_mutex_init(&med->med_idmap_mutex);
5531         med->med_idmap = NULL;
5532         cfs_spin_lock(&exp->exp_lock);
5533         exp->exp_connecting = 1;
5534         cfs_spin_unlock(&exp->exp_lock);
5535
5536         /* self-export doesn't need client data and ldlm initialization */
5537         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
5538                                      &exp->exp_client_uuid)))
5539                 RETURN(0);
5540
5541         rc = lut_client_alloc(exp);
5542         if (rc)
5543                 GOTO(err, rc);
5544
5545         rc = ldlm_init_export(exp);
5546         if (rc)
5547                 GOTO(err_free, rc);
5548
5549         RETURN(rc);
5550
5551 err_free:
5552         lut_client_free(exp);
5553 err:
5554         CERROR("%s: Failed to initialize export: rc = %d\n",
5555                exp->exp_obd->obd_name, rc);
5556         return rc;
5557 }
5558
5559 static int mdt_destroy_export(struct obd_export *exp)
5560 {
5561         ENTRY;
5562
5563         if (exp_connect_rmtclient(exp))
5564                 mdt_cleanup_idmap(&exp->exp_mdt_data);
5565
5566         target_destroy_export(exp);
5567         /* destroy can be called from failed obd_setup, so
5568          * checking uuid is safer than obd_self_export */
5569         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
5570                                      &exp->exp_client_uuid)))
5571                 RETURN(0);
5572
5573         ldlm_destroy_export(exp);
5574         lut_client_free(exp);
5575
5576         LASSERT(cfs_list_empty(&exp->exp_outstanding_replies));
5577         LASSERT(cfs_list_empty(&exp->exp_mdt_data.med_open_head));
5578
5579         RETURN(0);
5580 }
5581
5582 static void mdt_allow_cli(struct mdt_device *m, unsigned int flag)
5583 {
5584         if (flag & CONFIG_LOG)
5585                 cfs_set_bit(MDT_FL_CFGLOG, &m->mdt_state);
5586
5587         /* also notify active event */
5588         if (flag & CONFIG_SYNC)
5589                 cfs_set_bit(MDT_FL_SYNCED, &m->mdt_state);
5590
5591         if (cfs_test_bit(MDT_FL_CFGLOG, &m->mdt_state) &&
5592             cfs_test_bit(MDT_FL_SYNCED, &m->mdt_state)) {
5593                 struct obd_device *obd = m->mdt_md_dev.md_lu_dev.ld_obd;
5594
5595                 /* Open for clients */
5596                 if (obd->obd_no_conn) {
5597                         cfs_spin_lock(&obd->obd_dev_lock);
5598                         obd->obd_no_conn = 0;
5599                         cfs_spin_unlock(&obd->obd_dev_lock);
5600                 }
5601         }
5602 }
5603
5604 static int mdt_upcall(const struct lu_env *env, struct md_device *md,
5605                       enum md_upcall_event ev, void *data)
5606 {
5607         struct mdt_device *m = mdt_dev(&md->md_lu_dev);
5608         struct md_device  *next  = m->mdt_child;
5609         struct mdt_thread_info *mti;
5610         int rc = 0;
5611         ENTRY;
5612
5613         switch (ev) {
5614                 case MD_LOV_SYNC:
5615                         rc = next->md_ops->mdo_maxsize_get(env, next,
5616                                         &m->mdt_max_mdsize,
5617                                         &m->mdt_max_cookiesize);
5618                         CDEBUG(D_INFO, "get max mdsize %d max cookiesize %d\n",
5619                                      m->mdt_max_mdsize, m->mdt_max_cookiesize);
5620                         mdt_allow_cli(m, CONFIG_SYNC);
5621                         if (data)
5622                                 (*(__u64 *)data) =
5623                                       m->mdt_lut.lut_obd->u.obt.obt_mount_count;
5624                         break;
5625                 case MD_NO_TRANS:
5626                         mti = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
5627                         mti->mti_no_need_trans = 1;
5628                         CDEBUG(D_INFO, "disable mdt trans for this thread\n");
5629                         break;
5630                 case MD_LOV_CONFIG:
5631                         /* Check that MDT is not yet configured */
5632                         LASSERT(!cfs_test_bit(MDT_FL_CFGLOG, &m->mdt_state));
5633                         break;
5634 #ifdef HAVE_QUOTA_SUPPORT
5635                 case MD_LOV_QUOTA:
5636                         if (md->md_lu_dev.ld_obd->obd_recovering == 0 &&
5637                             likely(md->md_lu_dev.ld_obd->obd_stopping == 0))
5638                                 next->md_ops->mdo_quota.mqo_recovery(env, next);
5639                         break;
5640 #endif
5641                 default:
5642                         CERROR("invalid event\n");
5643                         rc = -EINVAL;
5644                         break;
5645         }
5646         RETURN(rc);
5647 }
5648
5649 static int mdt_obd_notify(struct obd_device *obd,
5650                           struct obd_device *watched,
5651                           enum obd_notify_event ev, void *data)
5652 {
5653         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
5654 #ifdef HAVE_QUOTA_SUPPORT
5655         struct md_device *next = mdt->mdt_child;
5656 #endif
5657         ENTRY;
5658
5659         switch (ev) {
5660         case OBD_NOTIFY_CONFIG:
5661                 mdt_allow_cli(mdt, (unsigned long)data);
5662
5663 #ifdef HAVE_QUOTA_SUPPORT
5664                /* quota_type has been processed, we can now handle
5665                 * incoming quota requests */
5666                 next->md_ops->mdo_quota.mqo_notify(NULL, next);
5667 #endif
5668                 break;
5669         default:
5670                 CDEBUG(D_INFO, "Unhandled notification %#x\n", ev);
5671         }
5672         RETURN(0);
5673 }
5674
5675 static int mdt_rpc_fid2path(struct mdt_thread_info *info, void *key,
5676                             void *val, int vallen)
5677 {
5678         struct mdt_device *mdt = mdt_dev(info->mti_exp->exp_obd->obd_lu_dev);
5679         struct getinfo_fid2path *fpout, *fpin;
5680         int rc = 0;
5681
5682         fpin = key + cfs_size_round(sizeof(KEY_FID2PATH));
5683         fpout = val;
5684
5685         if (ptlrpc_req_need_swab(info->mti_pill->rc_req))
5686                 lustre_swab_fid2path(fpin);
5687
5688         memcpy(fpout, fpin, sizeof(*fpin));
5689         if (fpout->gf_pathlen != vallen - sizeof(*fpin))
5690                 RETURN(-EINVAL);
5691
5692         rc = mdt_fid2path(info->mti_env, mdt, fpout);
5693         RETURN(rc);
5694 }
5695
5696 static int mdt_fid2path(const struct lu_env *env, struct mdt_device *mdt,
5697                         struct getinfo_fid2path *fp)
5698 {
5699         struct mdt_object *obj;
5700         int    rc;
5701         ENTRY;
5702
5703         CDEBUG(D_IOCTL, "path get "DFID" from "LPU64" #%d\n",
5704                PFID(&fp->gf_fid), fp->gf_recno, fp->gf_linkno);
5705
5706         if (!fid_is_sane(&fp->gf_fid))
5707                 RETURN(-EINVAL);
5708
5709         obj = mdt_object_find(env, mdt, &fp->gf_fid);
5710         if (obj == NULL || IS_ERR(obj)) {
5711                 CDEBUG(D_IOCTL, "no object "DFID": %ld\n", PFID(&fp->gf_fid),
5712                        PTR_ERR(obj));
5713                 RETURN(-EINVAL);
5714         }
5715
5716         rc = lu_object_exists(&obj->mot_obj.mo_lu);
5717         if (rc <= 0) {
5718                 if (rc == -1)
5719                         rc = -EREMOTE;
5720                 else
5721                         rc = -ENOENT;
5722                 mdt_object_put(env, obj);
5723                 CDEBUG(D_IOCTL, "nonlocal object "DFID": %d\n",
5724                        PFID(&fp->gf_fid), rc);
5725                 RETURN(rc);
5726         }
5727
5728         rc = mo_path(env, md_object_next(&obj->mot_obj), fp->gf_path,
5729                      fp->gf_pathlen, &fp->gf_recno, &fp->gf_linkno);
5730         mdt_object_put(env, obj);
5731
5732         RETURN(rc);
5733 }
5734
5735 static int mdt_get_info(struct mdt_thread_info *info)
5736 {
5737         struct ptlrpc_request *req = mdt_info_req(info);
5738         char *key;
5739         int keylen;
5740         __u32 *vallen;
5741         void *valout;
5742         int rc;
5743         ENTRY;
5744
5745         key = req_capsule_client_get(info->mti_pill, &RMF_GETINFO_KEY);
5746         if (key == NULL) {
5747                 CDEBUG(D_IOCTL, "No GETINFO key");
5748                 RETURN(-EFAULT);
5749         }
5750         keylen = req_capsule_get_size(info->mti_pill, &RMF_GETINFO_KEY,
5751                                       RCL_CLIENT);
5752
5753         vallen = req_capsule_client_get(info->mti_pill, &RMF_GETINFO_VALLEN);
5754         if (vallen == NULL) {
5755                 CDEBUG(D_IOCTL, "Unable to get RMF_GETINFO_VALLEN buffer");
5756                 RETURN(-EFAULT);
5757         }
5758
5759         req_capsule_set_size(info->mti_pill, &RMF_GETINFO_VAL, RCL_SERVER,
5760                              *vallen);
5761         rc = req_capsule_server_pack(info->mti_pill);
5762         valout = req_capsule_server_get(info->mti_pill, &RMF_GETINFO_VAL);
5763         if (valout == NULL) {
5764                 CDEBUG(D_IOCTL, "Unable to get get-info RPC out buffer");
5765                 RETURN(-EFAULT);
5766         }
5767
5768         if (KEY_IS(KEY_FID2PATH))
5769                 rc = mdt_rpc_fid2path(info, key, valout, *vallen);
5770         else
5771                 rc = -EINVAL;
5772
5773         lustre_msg_set_status(req->rq_repmsg, rc);
5774
5775         RETURN(rc);
5776 }
5777
5778 /* Pass the ioc down */
5779 static int mdt_ioc_child(struct lu_env *env, struct mdt_device *mdt,
5780                          unsigned int cmd, int len, void *data)
5781 {
5782         struct lu_context ioctl_session;
5783         struct md_device *next = mdt->mdt_child;
5784         int rc;
5785         ENTRY;
5786
5787         rc = lu_context_init(&ioctl_session, LCT_SESSION);
5788         if (rc)
5789                 RETURN(rc);
5790         ioctl_session.lc_thread = (struct ptlrpc_thread *)cfs_current();
5791         lu_context_enter(&ioctl_session);
5792         env->le_ses = &ioctl_session;
5793
5794         LASSERT(next->md_ops->mdo_iocontrol);
5795         rc = next->md_ops->mdo_iocontrol(env, next, cmd, len, data);
5796
5797         lu_context_exit(&ioctl_session);
5798         lu_context_fini(&ioctl_session);
5799         RETURN(rc);
5800 }
5801
5802 static int mdt_ioc_version_get(struct mdt_thread_info *mti, void *karg)
5803 {
5804         struct obd_ioctl_data *data = karg;
5805         struct lu_fid *fid = (struct lu_fid *)data->ioc_inlbuf1;
5806         __u64 version;
5807         struct mdt_object *obj;
5808         struct mdt_lock_handle  *lh;
5809         int rc;
5810         ENTRY;
5811
5812         CDEBUG(D_IOCTL, "getting version for "DFID"\n", PFID(fid));
5813         if (!fid_is_sane(fid))
5814                 RETURN(-EINVAL);
5815
5816         lh = &mti->mti_lh[MDT_LH_PARENT];
5817         mdt_lock_reg_init(lh, LCK_CR);
5818
5819         obj = mdt_object_find_lock(mti, fid, lh, MDS_INODELOCK_UPDATE);
5820         if (IS_ERR(obj))
5821                 RETURN(PTR_ERR(obj));
5822
5823         rc = mdt_object_exists(obj);
5824         if (rc < 0) {
5825                 rc = -EREMOTE;
5826                 /**
5827                  * before calling version get the correct MDS should be
5828                  * fid, this is error to find remote object here
5829                  */
5830                 CERROR("nonlocal object "DFID"\n", PFID(fid));
5831         } else if (rc == 0) {
5832                 *(__u64 *)data->ioc_inlbuf2 = ENOENT_VERSION;
5833                 rc = -ENOENT;
5834         } else {
5835                 version = dt_version_get(mti->mti_env, mdt_obj2dt(obj));
5836                *(__u64 *)data->ioc_inlbuf2 = version;
5837                 rc = 0;
5838         }
5839         mdt_object_unlock_put(mti, obj, lh, 1);
5840         RETURN(rc);
5841 }
5842
5843 /* ioctls on obd dev */
5844 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
5845                          void *karg, void *uarg)
5846 {
5847         struct lu_env      env;
5848         struct obd_device *obd = exp->exp_obd;
5849         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
5850         struct dt_device  *dt = mdt->mdt_bottom;
5851         int rc;
5852
5853         ENTRY;
5854         CDEBUG(D_IOCTL, "handling ioctl cmd %#x\n", cmd);
5855         rc = lu_env_init(&env, LCT_MD_THREAD);
5856         if (rc)
5857                 RETURN(rc);
5858
5859         switch (cmd) {
5860         case OBD_IOC_SYNC:
5861                 rc = mdt_device_sync(&env, mdt);
5862                 break;
5863         case OBD_IOC_SET_READONLY:
5864                 rc = dt->dd_ops->dt_ro(&env, dt);
5865                 break;
5866         case OBD_IOC_ABORT_RECOVERY:
5867                 CERROR("Aborting recovery for device %s\n", obd->obd_name);
5868                 target_stop_recovery_thread(obd);
5869                 rc = 0;
5870                 break;
5871         case OBD_IOC_CHANGELOG_REG:
5872         case OBD_IOC_CHANGELOG_DEREG:
5873         case OBD_IOC_CHANGELOG_CLEAR:
5874                 rc = mdt_ioc_child(&env, mdt, cmd, len, karg);
5875                 break;
5876         case OBD_IOC_START_LFSCK:
5877         case OBD_IOC_STOP_LFSCK: {
5878                 struct md_device *next = mdt->mdt_child;
5879                 struct obd_ioctl_data *data = karg;
5880
5881                 if (unlikely(data == NULL)) {
5882                         rc = -EINVAL;
5883                         break;
5884                 }
5885
5886                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd,
5887                                                  data->ioc_inllen1,
5888                                                  data->ioc_inlbuf1);
5889                 break;
5890         }
5891         case OBD_IOC_GET_OBJ_VERSION: {
5892                 struct mdt_thread_info *mti;
5893                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5894                 memset(mti, 0, sizeof *mti);
5895                 mti->mti_env = &env;
5896                 mti->mti_mdt = mdt;
5897                 mti->mti_exp = exp;
5898
5899                 rc = mdt_ioc_version_get(mti, karg);
5900                 break;
5901         }
5902         default:
5903                 CERROR("Not supported cmd = %d for device %s\n",
5904                        cmd, obd->obd_name);
5905                 rc = -EOPNOTSUPP;
5906         }
5907
5908         lu_env_fini(&env);
5909         RETURN(rc);
5910 }
5911
5912 int mdt_postrecov(const struct lu_env *env, struct mdt_device *mdt)
5913 {
5914         struct lu_device *ld = md2lu_dev(mdt->mdt_child);
5915 #ifdef HAVE_QUOTA_SUPPORT
5916         struct obd_device *obd = mdt2obd_dev(mdt);
5917         struct md_device *next = mdt->mdt_child;
5918 #endif
5919         int rc;
5920         ENTRY;
5921
5922         rc = ld->ld_ops->ldo_recovery_complete(env, ld);
5923 #ifdef HAVE_QUOTA_SUPPORT
5924         if (likely(obd->obd_stopping == 0))
5925                 next->md_ops->mdo_quota.mqo_recovery(env, next);
5926 #endif
5927         RETURN(rc);
5928 }
5929
5930 int mdt_obd_postrecov(struct obd_device *obd)
5931 {
5932         struct lu_env env;
5933         int rc;
5934
5935         rc = lu_env_init(&env, LCT_MD_THREAD);
5936         if (rc)
5937                 RETURN(rc);
5938         rc = mdt_postrecov(&env, mdt_dev(obd->obd_lu_dev));
5939         lu_env_fini(&env);
5940         return rc;
5941 }
5942
5943 /**
5944  * Send a copytool req to a client
5945  * Note this sends a request RPC from a server (MDT) to a client (MDC),
5946  * backwards of normal comms.
5947  */
5948 int mdt_hsm_copytool_send(struct obd_export *exp)
5949 {
5950         struct kuc_hdr *lh;
5951         struct hsm_action_list *hal;
5952         struct hsm_action_item *hai;
5953         int rc, len;
5954         ENTRY;
5955
5956         CWARN("%s: writing to mdc at %s\n", exp->exp_obd->obd_name,
5957               libcfs_nid2str(exp->exp_connection->c_peer.nid));
5958
5959         len = sizeof(*lh) + sizeof(*hal) + MTI_NAME_MAXLEN +
5960                 /* for mockup below */ 2 * cfs_size_round(sizeof(*hai));
5961         OBD_ALLOC(lh, len);
5962         if (lh == NULL)
5963                 RETURN(-ENOMEM);
5964
5965         lh->kuc_magic = KUC_MAGIC;
5966         lh->kuc_transport = KUC_TRANSPORT_HSM;
5967         lh->kuc_msgtype = HMT_ACTION_LIST;
5968         lh->kuc_msglen = len;
5969
5970         hal = (struct hsm_action_list *)(lh + 1);
5971         hal->hal_version = HAL_VERSION;
5972         hal->hal_archive_num = 1;
5973         obd_uuid2fsname(hal->hal_fsname, exp->exp_obd->obd_name,
5974                         MTI_NAME_MAXLEN);
5975
5976         /* mock up an action list */
5977         hal->hal_count = 2;
5978         hai = hai_zero(hal);
5979         hai->hai_action = HSMA_ARCHIVE;
5980         hai->hai_fid.f_oid = 0xA00A;
5981         hai->hai_len = sizeof(*hai);
5982         hai = hai_next(hai);
5983         hai->hai_action = HSMA_RESTORE;
5984         hai->hai_fid.f_oid = 0xB00B;
5985         hai->hai_len = sizeof(*hai);
5986
5987         /* Uses the ldlm reverse import; this rpc will be seen by
5988           the ldlm_callback_handler */
5989         rc = do_set_info_async(exp->exp_imp_reverse,
5990                                LDLM_SET_INFO, LUSTRE_OBD_VERSION,
5991                                sizeof(KEY_HSM_COPYTOOL_SEND),
5992                                KEY_HSM_COPYTOOL_SEND,
5993                                len, lh, NULL);
5994
5995         OBD_FREE(lh, len);
5996
5997         RETURN(rc);
5998 }
5999
6000 static struct obd_ops mdt_obd_device_ops = {
6001         .o_owner          = THIS_MODULE,
6002         .o_set_info_async = mdt_obd_set_info_async,
6003         .o_connect        = mdt_obd_connect,
6004         .o_reconnect      = mdt_obd_reconnect,
6005         .o_disconnect     = mdt_obd_disconnect,
6006         .o_init_export    = mdt_init_export,
6007         .o_destroy_export = mdt_destroy_export,
6008         .o_iocontrol      = mdt_iocontrol,
6009         .o_postrecov      = mdt_obd_postrecov,
6010         .o_notify         = mdt_obd_notify
6011 };
6012
6013 static struct lu_device* mdt_device_fini(const struct lu_env *env,
6014                                          struct lu_device *d)
6015 {
6016         struct mdt_device *m = mdt_dev(d);
6017         ENTRY;
6018
6019         mdt_fini(env, m);
6020         RETURN(NULL);
6021 }
6022
6023 static struct lu_device *mdt_device_free(const struct lu_env *env,
6024                                          struct lu_device *d)
6025 {
6026         struct mdt_device *m = mdt_dev(d);
6027         ENTRY;
6028
6029         md_device_fini(&m->mdt_md_dev);
6030         OBD_FREE_PTR(m);
6031         RETURN(NULL);
6032 }
6033
6034 static struct lu_device *mdt_device_alloc(const struct lu_env *env,
6035                                           struct lu_device_type *t,
6036                                           struct lustre_cfg *cfg)
6037 {
6038         struct lu_device  *l;
6039         struct mdt_device *m;
6040
6041         OBD_ALLOC_PTR(m);
6042         if (m != NULL) {
6043                 int rc;
6044
6045                 l = &m->mdt_md_dev.md_lu_dev;
6046                 rc = mdt_init0(env, m, t, cfg);
6047                 if (rc != 0) {
6048                         mdt_device_free(env, l);
6049                         l = ERR_PTR(rc);
6050                         return l;
6051                 }
6052                 md_upcall_init(&m->mdt_md_dev, mdt_upcall);
6053         } else
6054                 l = ERR_PTR(-ENOMEM);
6055         return l;
6056 }
6057
6058 /* context key constructor/destructor: mdt_key_init, mdt_key_fini */
6059 LU_KEY_INIT_FINI(mdt, struct mdt_thread_info);
6060
6061 /* context key: mdt_thread_key */
6062 LU_CONTEXT_KEY_DEFINE(mdt, LCT_MD_THREAD);
6063
6064 struct md_ucred *mdt_ucred(const struct mdt_thread_info *info)
6065 {
6066         return md_ucred(info->mti_env);
6067 }
6068
6069 /**
6070  * Enable/disable COS (Commit On Sharing).
6071  *
6072  * Set/Clear the COS flag in mdt options.
6073  *
6074  * \param mdt mdt device
6075  * \param val 0 disables COS, other values enable COS
6076  */
6077 void mdt_enable_cos(struct mdt_device *mdt, int val)
6078 {
6079         struct lu_env env;
6080         int rc;
6081
6082         mdt->mdt_opts.mo_cos = !!val;
6083         rc = lu_env_init(&env, LCT_LOCAL);
6084         if (unlikely(rc != 0)) {
6085                 CWARN("lu_env initialization failed with rc = %d,"
6086                       "cannot sync\n", rc);
6087                 return;
6088         }
6089         mdt_device_sync(&env, mdt);
6090         lu_env_fini(&env);
6091 }
6092
6093 /**
6094  * Check COS (Commit On Sharing) status.
6095  *
6096  * Return COS flag status.
6097  *
6098  * \param mdt mdt device
6099  */
6100 int mdt_cos_is_enabled(struct mdt_device *mdt)
6101 {
6102         return mdt->mdt_opts.mo_cos != 0;
6103 }
6104
6105 /* type constructor/destructor: mdt_type_init, mdt_type_fini */
6106 LU_TYPE_INIT_FINI(mdt, &mdt_thread_key);
6107
6108 static struct lu_device_type_operations mdt_device_type_ops = {
6109         .ldto_init = mdt_type_init,
6110         .ldto_fini = mdt_type_fini,
6111
6112         .ldto_start = mdt_type_start,
6113         .ldto_stop  = mdt_type_stop,
6114
6115         .ldto_device_alloc = mdt_device_alloc,
6116         .ldto_device_free  = mdt_device_free,
6117         .ldto_device_fini  = mdt_device_fini
6118 };
6119
6120 static struct lu_device_type mdt_device_type = {
6121         .ldt_tags     = LU_DEVICE_MD,
6122         .ldt_name     = LUSTRE_MDT_NAME,
6123         .ldt_ops      = &mdt_device_type_ops,
6124         .ldt_ctx_tags = LCT_MD_THREAD
6125 };
6126
6127 static int __init mdt_mod_init(void)
6128 {
6129         struct lprocfs_static_vars lvars;
6130         int rc;
6131
6132         rc = lu_kmem_init(mdt_caches);
6133         if (rc)
6134                 return rc;
6135
6136         if (mdt_num_threads != 0 && mds_num_threads == 0) {
6137                 LCONSOLE_INFO("mdt_num_threads module parameter is deprecated,"
6138                               "use mds_num_threads instead or unset both for"
6139                               "dynamic thread startup\n");
6140                 mds_num_threads = mdt_num_threads;
6141         }
6142
6143         lprocfs_mdt_init_vars(&lvars);
6144         rc = class_register_type(&mdt_obd_device_ops, NULL,
6145                                  lvars.module_vars, LUSTRE_MDT_NAME,
6146                                  &mdt_device_type);
6147
6148         if (rc)
6149                 lu_kmem_fini(mdt_caches);
6150         return rc;
6151 }
6152
6153 static void __exit mdt_mod_exit(void)
6154 {
6155         class_unregister_type(LUSTRE_MDT_NAME);
6156         lu_kmem_fini(mdt_caches);
6157 }
6158
6159
6160 #define DEF_HNDL(prefix, base, suffix, flags, opc, fn, fmt)             \
6161 [prefix ## _ ## opc - prefix ## _ ## base] = {                          \
6162         .mh_name    = #opc,                                             \
6163         .mh_fail_id = OBD_FAIL_ ## prefix ## _  ## opc ## suffix,       \
6164         .mh_opc     = prefix ## _  ## opc,                              \
6165         .mh_flags   = flags,                                            \
6166         .mh_act     = fn,                                               \
6167         .mh_fmt     = fmt                                               \
6168 }
6169
6170 #define DEF_MDT_HNDL(flags, name, fn, fmt)                                  \
6171         DEF_HNDL(MDS, GETATTR, _NET, flags, name, fn, fmt)
6172
6173 #define DEF_SEQ_HNDL(flags, name, fn, fmt)                      \
6174         DEF_HNDL(SEQ, QUERY, _NET, flags, name, fn, fmt)
6175
6176 #define DEF_FLD_HNDL(flags, name, fn, fmt)                      \
6177         DEF_HNDL(FLD, QUERY, _NET, flags, name, fn, fmt)
6178 /*
6179  * Request with a format known in advance
6180  */
6181 #define DEF_MDT_HNDL_F(flags, name, fn)                                 \
6182         DEF_HNDL(MDS, GETATTR, _NET, flags, name, fn, &RQF_MDS_ ## name)
6183
6184 #define DEF_SEQ_HNDL_F(flags, name, fn)                                 \
6185         DEF_HNDL(SEQ, QUERY, _NET, flags, name, fn, &RQF_SEQ_ ## name)
6186
6187 #define DEF_FLD_HNDL_F(flags, name, fn)                                 \
6188         DEF_HNDL(FLD, QUERY, _NET, flags, name, fn, &RQF_FLD_ ## name)
6189 /*
6190  * Request with a format we do not yet know
6191  */
6192 #define DEF_MDT_HNDL_0(flags, name, fn)                                 \
6193         DEF_HNDL(MDS, GETATTR, _NET, flags, name, fn, NULL)
6194
6195 static struct mdt_handler mdt_mds_ops[] = {
6196 DEF_MDT_HNDL_F(0,                         CONNECT,      mdt_connect),
6197 DEF_MDT_HNDL_F(0,                         DISCONNECT,   mdt_disconnect),
6198 DEF_MDT_HNDL  (0,                         SET_INFO,     mdt_set_info,
6199                                                              &RQF_OBD_SET_INFO),
6200 DEF_MDT_HNDL_F(0,                         GET_INFO,     mdt_get_info),
6201 DEF_MDT_HNDL_F(0           |HABEO_REFERO, GETSTATUS,    mdt_getstatus),
6202 DEF_MDT_HNDL_F(HABEO_CORPUS,              GETATTR,      mdt_getattr),
6203 DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, GETATTR_NAME, mdt_getattr_name),
6204 DEF_MDT_HNDL_F(HABEO_CORPUS,              GETXATTR,     mdt_getxattr),
6205 DEF_MDT_HNDL_F(0           |HABEO_REFERO, STATFS,       mdt_statfs),
6206 DEF_MDT_HNDL_F(0           |MUTABOR,      REINT,        mdt_reint),
6207 DEF_MDT_HNDL_F(HABEO_CORPUS,              CLOSE,        mdt_close),
6208 DEF_MDT_HNDL_F(HABEO_CORPUS,              DONE_WRITING, mdt_done_writing),
6209 DEF_MDT_HNDL_F(0           |HABEO_REFERO, PIN,          mdt_pin),
6210 DEF_MDT_HNDL_0(0,                         SYNC,         mdt_sync),
6211 DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, IS_SUBDIR,    mdt_is_subdir),
6212 #ifdef HAVE_QUOTA_SUPPORT
6213 DEF_MDT_HNDL_F(0,                         QUOTACHECK,   mdt_quotacheck_handle),
6214 DEF_MDT_HNDL_F(0,                         QUOTACTL,     mdt_quotactl_handle)
6215 #endif
6216 };
6217
6218 #define DEF_OBD_HNDL(flags, name, fn)                   \
6219         DEF_HNDL(OBD, PING, _NET, flags, name, fn, NULL)
6220
6221
6222 static struct mdt_handler mdt_obd_ops[] = {
6223         DEF_OBD_HNDL(0, PING,           mdt_obd_ping),
6224         DEF_OBD_HNDL(0, LOG_CANCEL,     mdt_obd_log_cancel),
6225         DEF_OBD_HNDL(0, QC_CALLBACK,    mdt_obd_qc_callback),
6226         DEF_OBD_HNDL(0, IDX_READ,       mdt_obd_idx_read)
6227 };
6228
6229 #define DEF_DLM_HNDL_0(flags, name, fn)                   \
6230         DEF_HNDL(LDLM, ENQUEUE, , flags, name, fn, NULL)
6231 #define DEF_DLM_HNDL_F(flags, name, fn)                   \
6232         DEF_HNDL(LDLM, ENQUEUE, , flags, name, fn, &RQF_LDLM_ ## name)
6233
6234 static struct mdt_handler mdt_dlm_ops[] = {
6235         DEF_DLM_HNDL_F(HABEO_CLAVIS, ENQUEUE,        mdt_enqueue),
6236         DEF_DLM_HNDL_0(HABEO_CLAVIS, CONVERT,        mdt_convert),
6237         DEF_DLM_HNDL_0(0,            BL_CALLBACK,    mdt_bl_callback),
6238         DEF_DLM_HNDL_0(0,            CP_CALLBACK,    mdt_cp_callback)
6239 };
6240
6241 #define DEF_LLOG_HNDL(flags, name, fn)                   \
6242         DEF_HNDL(LLOG, ORIGIN_HANDLE_CREATE, _NET, flags, name, fn, NULL)
6243
6244 static struct mdt_handler mdt_llog_ops[] = {
6245         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_CREATE,      mdt_llog_create),
6246         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_NEXT_BLOCK,  mdt_llog_next_block),
6247         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_READ_HEADER, mdt_llog_read_header),
6248         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_WRITE_REC,   NULL),
6249         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_CLOSE,       NULL),
6250         DEF_LLOG_HNDL(0, ORIGIN_CONNECT,            NULL),
6251         DEF_LLOG_HNDL(0, CATINFO,                   NULL),
6252         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_PREV_BLOCK,  mdt_llog_prev_block),
6253         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_DESTROY,     mdt_llog_destroy),
6254 };
6255
6256 #define DEF_SEC_CTX_HNDL(name, fn)                      \
6257         DEF_HNDL(SEC_CTX, INIT, _NET, 0, name, fn, NULL)
6258
6259 static struct mdt_handler mdt_sec_ctx_ops[] = {
6260         DEF_SEC_CTX_HNDL(INIT,          mdt_sec_ctx_handle),
6261         DEF_SEC_CTX_HNDL(INIT_CONT,     mdt_sec_ctx_handle),
6262         DEF_SEC_CTX_HNDL(FINI,          mdt_sec_ctx_handle)
6263 };
6264
6265 static struct mdt_opc_slice mdt_regular_handlers[] = {
6266         {
6267                 .mos_opc_start = MDS_GETATTR,
6268                 .mos_opc_end   = MDS_LAST_OPC,
6269                 .mos_hs        = mdt_mds_ops
6270         },
6271         {
6272                 .mos_opc_start = OBD_PING,
6273                 .mos_opc_end   = OBD_LAST_OPC,
6274                 .mos_hs        = mdt_obd_ops
6275         },
6276         {
6277                 .mos_opc_start = LDLM_ENQUEUE,
6278                 .mos_opc_end   = LDLM_LAST_OPC,
6279                 .mos_hs        = mdt_dlm_ops
6280         },
6281         {
6282                 .mos_opc_start = LLOG_ORIGIN_HANDLE_CREATE,
6283                 .mos_opc_end   = LLOG_LAST_OPC,
6284                 .mos_hs        = mdt_llog_ops
6285         },
6286         {
6287                 .mos_opc_start = SEC_CTX_INIT,
6288                 .mos_opc_end   = SEC_LAST_OPC,
6289                 .mos_hs        = mdt_sec_ctx_ops
6290         },
6291         {
6292                 .mos_hs        = NULL
6293         }
6294 };
6295
6296 static struct mdt_handler mdt_readpage_ops[] = {
6297         DEF_MDT_HNDL_F(0,                         CONNECT,  mdt_connect),
6298         DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, READPAGE, mdt_readpage),
6299 #ifdef HAVE_SPLIT_SUPPORT
6300         DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, WRITEPAGE, mdt_writepage),
6301 #endif
6302
6303         /*
6304          * XXX: this is ugly and should be fixed one day, see mdc_close() for
6305          * detailed comments. --umka
6306          */
6307         DEF_MDT_HNDL_F(HABEO_CORPUS,              CLOSE,    mdt_close),
6308         DEF_MDT_HNDL_F(HABEO_CORPUS,              DONE_WRITING,    mdt_done_writing),
6309 };
6310
6311 static struct mdt_opc_slice mdt_readpage_handlers[] = {
6312         {
6313                 .mos_opc_start = MDS_GETATTR,
6314                 .mos_opc_end   = MDS_LAST_OPC,
6315                 .mos_hs        = mdt_readpage_ops
6316         },
6317         {
6318                 .mos_opc_start = OBD_FIRST_OPC,
6319                 .mos_opc_end   = OBD_LAST_OPC,
6320                 .mos_hs        = mdt_obd_ops
6321         },
6322         {
6323                 .mos_hs        = NULL
6324         }
6325 };
6326
6327 static struct mdt_handler mdt_xmds_ops[] = {
6328         DEF_MDT_HNDL_F(0,                         CONNECT,      mdt_connect),
6329         DEF_MDT_HNDL_F(HABEO_CORPUS             , GETATTR,      mdt_getattr),
6330         DEF_MDT_HNDL_F(0 | MUTABOR              , REINT,        mdt_reint),
6331         DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, IS_SUBDIR,    mdt_is_subdir),
6332 };
6333
6334 static struct mdt_opc_slice mdt_xmds_handlers[] = {
6335         {
6336                 .mos_opc_start = MDS_GETATTR,
6337                 .mos_opc_end   = MDS_LAST_OPC,
6338                 .mos_hs        = mdt_xmds_ops
6339         },
6340         {
6341                 .mos_opc_start = OBD_PING,
6342                 .mos_opc_end   = OBD_LAST_OPC,
6343                 .mos_hs        = mdt_obd_ops
6344         },
6345         {
6346                 .mos_opc_start = SEC_CTX_INIT,
6347                 .mos_opc_end   = SEC_LAST_OPC,
6348                 .mos_hs        = mdt_sec_ctx_ops
6349         },
6350         {
6351                 .mos_hs        = NULL
6352         }
6353 };
6354
6355 static struct mdt_handler mdt_seq_ops[] = {
6356         DEF_SEQ_HNDL_F(0, QUERY, (int (*)(struct mdt_thread_info *))seq_query)
6357 };
6358
6359 static struct mdt_opc_slice mdt_seq_handlers[] = {
6360         {
6361                 .mos_opc_start = SEQ_QUERY,
6362                 .mos_opc_end   = SEQ_LAST_OPC,
6363                 .mos_hs        = mdt_seq_ops
6364         },
6365         {
6366                 .mos_hs        = NULL
6367         }
6368 };
6369
6370 static struct mdt_handler mdt_fld_ops[] = {
6371         DEF_FLD_HNDL_F(0, QUERY, (int (*)(struct mdt_thread_info *))fld_query)
6372 };
6373
6374 static struct mdt_opc_slice mdt_fld_handlers[] = {
6375         {
6376                 .mos_opc_start = FLD_QUERY,
6377                 .mos_opc_end   = FLD_LAST_OPC,
6378                 .mos_hs        = mdt_fld_ops
6379         },
6380         {
6381                 .mos_hs        = NULL
6382         }
6383 };
6384
6385 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
6386 MODULE_DESCRIPTION("Lustre Meta-data Target ("LUSTRE_MDT_NAME")");
6387 MODULE_LICENSE("GPL");
6388
6389 cfs_module(mdt, "0.2.0", mdt_mod_init, mdt_mod_exit);