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