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