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