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