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