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