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