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