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