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