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