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