Whamcloud - gitweb
LU-3494 libcfs: Add relocation function to libcfs heap
[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 (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                              MDT_LOCAL_LOCK);
1121         if (rc < 0)
1122                 GOTO(put, rc);
1123
1124         rc = mdt_object_lock(info, o2, lh2, MDS_INODELOCK_LAYOUT,
1125                              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 starts
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         spin_unlock(&exp->exp_lock);
1624
1625         rc = mdt_init_idmap(info);
1626         if (rc != 0)
1627                 GOTO(err, rc);
1628         RETURN(0);
1629 err:
1630         obd_disconnect(class_export_get(req->rq_export));
1631         return rc;
1632 }
1633
1634 int mdt_disconnect(struct mdt_thread_info *info)
1635 {
1636         int rc;
1637         ENTRY;
1638
1639         rc = target_handle_disconnect(mdt_info_req(info));
1640         if (rc)
1641                 rc = err_serious(rc);
1642         RETURN(rc);
1643 }
1644
1645 static int mdt_sendpage(struct mdt_thread_info *info,
1646                         struct lu_rdpg *rdpg, int nob)
1647 {
1648         struct ptlrpc_request   *req = mdt_info_req(info);
1649         struct obd_export       *exp = req->rq_export;
1650         struct ptlrpc_bulk_desc *desc;
1651         struct l_wait_info      *lwi = &info->mti_u.rdpg.mti_wait_info;
1652         int                      tmpcount;
1653         int                      tmpsize;
1654         int                      i;
1655         int                      rc;
1656         ENTRY;
1657
1658         desc = ptlrpc_prep_bulk_exp(req, rdpg->rp_npages, 1, BULK_PUT_SOURCE,
1659                                     MDS_BULK_PORTAL);
1660         if (desc == NULL)
1661                 RETURN(-ENOMEM);
1662
1663         if (!(exp_connect_flags(exp) & OBD_CONNECT_BRW_SIZE))
1664                 /* old client requires reply size in it's PAGE_SIZE,
1665                  * which is rdpg->rp_count */
1666                 nob = rdpg->rp_count;
1667
1668         for (i = 0, tmpcount = nob; i < rdpg->rp_npages && tmpcount > 0;
1669              i++, tmpcount -= tmpsize) {
1670                 tmpsize = min_t(int, tmpcount, PAGE_CACHE_SIZE);
1671                 ptlrpc_prep_bulk_page_pin(desc, rdpg->rp_pages[i], 0, tmpsize);
1672         }
1673
1674         LASSERT(desc->bd_nob == nob);
1675         rc = target_bulk_io(exp, desc, lwi);
1676         ptlrpc_free_bulk_pin(desc);
1677         RETURN(rc);
1678 }
1679
1680 int mdt_readpage(struct mdt_thread_info *info)
1681 {
1682         struct mdt_object *object = info->mti_object;
1683         struct lu_rdpg    *rdpg = &info->mti_u.rdpg.mti_rdpg;
1684         struct mdt_body   *reqbody;
1685         struct mdt_body   *repbody;
1686         int                rc;
1687         int                i;
1688         ENTRY;
1689
1690         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READPAGE_PACK))
1691                 RETURN(err_serious(-ENOMEM));
1692
1693         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1694         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1695         if (reqbody == NULL || repbody == NULL)
1696                 RETURN(err_serious(-EFAULT));
1697
1698         /*
1699          * prepare @rdpg before calling lower layers and transfer itself. Here
1700          * reqbody->size contains offset of where to start to read and
1701          * reqbody->nlink contains number bytes to read.
1702          */
1703         rdpg->rp_hash = reqbody->size;
1704         if (rdpg->rp_hash != reqbody->size) {
1705                 CERROR("Invalid hash: "LPX64" != "LPX64"\n",
1706                        rdpg->rp_hash, reqbody->size);
1707                 RETURN(-EFAULT);
1708         }
1709
1710         rdpg->rp_attrs = reqbody->mode;
1711         if (exp_connect_flags(info->mti_exp) & OBD_CONNECT_64BITHASH)
1712                 rdpg->rp_attrs |= LUDA_64BITHASH;
1713         rdpg->rp_count  = min_t(unsigned int, reqbody->nlink,
1714                                 exp_max_brw_size(info->mti_exp));
1715         rdpg->rp_npages = (rdpg->rp_count + PAGE_CACHE_SIZE - 1) >>
1716                           PAGE_CACHE_SHIFT;
1717         OBD_ALLOC(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1718         if (rdpg->rp_pages == NULL)
1719                 RETURN(-ENOMEM);
1720
1721         for (i = 0; i < rdpg->rp_npages; ++i) {
1722                 rdpg->rp_pages[i] = alloc_page(GFP_IOFS);
1723                 if (rdpg->rp_pages[i] == NULL)
1724                         GOTO(free_rdpg, rc = -ENOMEM);
1725         }
1726
1727         /* call lower layers to fill allocated pages with directory data */
1728         rc = mo_readpage(info->mti_env, mdt_object_child(object), rdpg);
1729         if (rc < 0)
1730                 GOTO(free_rdpg, rc);
1731
1732         /* send pages to client */
1733         rc = mdt_sendpage(info, rdpg, rc);
1734
1735         EXIT;
1736 free_rdpg:
1737
1738         for (i = 0; i < rdpg->rp_npages; i++)
1739                 if (rdpg->rp_pages[i] != NULL)
1740                         __free_page(rdpg->rp_pages[i]);
1741         OBD_FREE(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1742
1743         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE))
1744                 RETURN(0);
1745
1746         return rc;
1747 }
1748
1749 static int mdt_reint_internal(struct mdt_thread_info *info,
1750                               struct mdt_lock_handle *lhc,
1751                               __u32 op)
1752 {
1753         struct req_capsule      *pill = info->mti_pill;
1754         struct mdt_body         *repbody;
1755         int                      rc = 0, rc2;
1756         ENTRY;
1757
1758
1759         rc = mdt_reint_unpack(info, op);
1760         if (rc != 0) {
1761                 CERROR("Can't unpack reint, rc %d\n", rc);
1762                 RETURN(err_serious(rc));
1763         }
1764
1765         /* for replay (no_create) lmm is not needed, client has it already */
1766         if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1767                 req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
1768                                      info->mti_rr.rr_eadatalen);
1769
1770         /* llog cookies are always 0, the field is kept for compatibility */
1771         if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
1772                 req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER, 0);
1773
1774         rc = req_capsule_server_pack(pill);
1775         if (rc != 0) {
1776                 CERROR("Can't pack response, rc %d\n", rc);
1777                 RETURN(err_serious(rc));
1778         }
1779
1780         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_SERVER)) {
1781                 repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
1782                 LASSERT(repbody);
1783                 repbody->eadatasize = 0;
1784                 repbody->aclsize = 0;
1785         }
1786
1787         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_REINT_DELAY, 10);
1788
1789         /* for replay no cookkie / lmm need, because client have this already */
1790         if (info->mti_spec.no_create)
1791                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1792                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, 0);
1793
1794         rc = mdt_init_ucred_reint(info);
1795         if (rc)
1796                 GOTO(out_shrink, rc);
1797
1798         rc = mdt_fix_attr_ucred(info, op);
1799         if (rc != 0)
1800                 GOTO(out_ucred, rc = err_serious(rc));
1801
1802         if (mdt_check_resent(info, mdt_reconstruct, lhc)) {
1803                 rc = lustre_msg_get_status(mdt_info_req(info)->rq_repmsg);
1804                 GOTO(out_ucred, rc);
1805         }
1806         rc = mdt_reint_rec(info, lhc);
1807         EXIT;
1808 out_ucred:
1809         mdt_exit_ucred(info);
1810 out_shrink:
1811         mdt_client_compatibility(info);
1812         rc2 = mdt_fix_reply(info);
1813         if (rc == 0)
1814                 rc = rc2;
1815         return rc;
1816 }
1817
1818 static long mdt_reint_opcode(struct mdt_thread_info *info,
1819                              const struct req_format **fmt)
1820 {
1821         struct mdt_rec_reint *rec;
1822         long opc;
1823
1824         rec = req_capsule_client_get(info->mti_pill, &RMF_REC_REINT);
1825         if (rec != NULL) {
1826                 opc = rec->rr_opcode;
1827                 DEBUG_REQ(D_INODE, mdt_info_req(info), "reint opt = %ld", opc);
1828                 if (opc < REINT_MAX && fmt[opc] != NULL)
1829                         req_capsule_extend(info->mti_pill, fmt[opc]);
1830                 else {
1831                         CERROR("%s: Unsupported opcode '%ld' from client '%s': "
1832                                "rc = %d\n", mdt_obd_name(info->mti_mdt), opc,
1833                                info->mti_mdt->mdt_ldlm_client->cli_name,
1834                                -EFAULT);
1835                         opc = err_serious(-EFAULT);
1836                 }
1837         } else {
1838                 opc = err_serious(-EFAULT);
1839         }
1840         return opc;
1841 }
1842
1843 int mdt_reint(struct mdt_thread_info *info)
1844 {
1845         long opc;
1846         int  rc;
1847
1848         static const struct req_format *reint_fmts[REINT_MAX] = {
1849                 [REINT_SETATTR]  = &RQF_MDS_REINT_SETATTR,
1850                 [REINT_CREATE]   = &RQF_MDS_REINT_CREATE,
1851                 [REINT_LINK]     = &RQF_MDS_REINT_LINK,
1852                 [REINT_UNLINK]   = &RQF_MDS_REINT_UNLINK,
1853                 [REINT_RENAME]   = &RQF_MDS_REINT_RENAME,
1854                 [REINT_OPEN]     = &RQF_MDS_REINT_OPEN,
1855                 [REINT_SETXATTR] = &RQF_MDS_REINT_SETXATTR,
1856                 [REINT_RMENTRY] = &RQF_MDS_REINT_UNLINK
1857         };
1858
1859         ENTRY;
1860
1861         opc = mdt_reint_opcode(info, reint_fmts);
1862         if (opc >= 0) {
1863                 /*
1864                  * No lock possible here from client to pass it to reint code
1865                  * path.
1866                  */
1867                 rc = mdt_reint_internal(info, NULL, opc);
1868         } else {
1869                 rc = opc;
1870         }
1871
1872         info->mti_fail_id = OBD_FAIL_MDS_REINT_NET_REP;
1873         RETURN(rc);
1874 }
1875
1876 /* this should sync the whole device */
1877 static int mdt_device_sync(const struct lu_env *env, struct mdt_device *mdt)
1878 {
1879         struct dt_device *dt = mdt->mdt_bottom;
1880         int rc;
1881         ENTRY;
1882
1883         rc = dt->dd_ops->dt_sync(env, dt);
1884         RETURN(rc);
1885 }
1886
1887 /* this should sync this object */
1888 static int mdt_object_sync(struct mdt_thread_info *info)
1889 {
1890         struct md_object *next;
1891         int rc;
1892         ENTRY;
1893
1894         if (!mdt_object_exists(info->mti_object)) {
1895                 CWARN("Non existing object  "DFID"!\n",
1896                       PFID(mdt_object_fid(info->mti_object)));
1897                 RETURN(-ESTALE);
1898         }
1899         next = mdt_object_child(info->mti_object);
1900         rc = mo_object_sync(info->mti_env, next);
1901
1902         RETURN(rc);
1903 }
1904
1905 int mdt_sync(struct mdt_thread_info *info)
1906 {
1907         struct ptlrpc_request *req = mdt_info_req(info);
1908         struct req_capsule *pill = info->mti_pill;
1909         struct mdt_body *body;
1910         int rc;
1911         ENTRY;
1912
1913         /* The fid may be zero, so we req_capsule_set manually */
1914         req_capsule_set(pill, &RQF_MDS_SYNC);
1915
1916         body = req_capsule_client_get(pill, &RMF_MDT_BODY);
1917         if (body == NULL)
1918                 RETURN(err_serious(-EINVAL));
1919
1920         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SYNC_PACK))
1921                 RETURN(err_serious(-ENOMEM));
1922
1923         if (fid_seq(&body->fid1) == 0) {
1924                 /* sync the whole device */
1925                 rc = req_capsule_server_pack(pill);
1926                 if (rc == 0)
1927                         rc = mdt_device_sync(info->mti_env, info->mti_mdt);
1928                 else
1929                         rc = err_serious(rc);
1930         } else {
1931                 /* sync an object */
1932                 rc = mdt_unpack_req_pack_rep(info, HABEO_CORPUS|HABEO_REFERO);
1933                 if (rc == 0) {
1934                         rc = mdt_object_sync(info);
1935                         if (rc == 0) {
1936                                 const struct lu_fid *fid;
1937                                 struct lu_attr *la = &info->mti_attr.ma_attr;
1938
1939                                 info->mti_attr.ma_need = MA_INODE;
1940                                 info->mti_attr.ma_valid = 0;
1941                                 rc = mdt_attr_get_complex(info, info->mti_object,
1942                                                           &info->mti_attr);
1943                                 if (rc == 0) {
1944                                         body = req_capsule_server_get(pill,
1945                                                                 &RMF_MDT_BODY);
1946                                         fid = mdt_object_fid(info->mti_object);
1947                                         mdt_pack_attr2body(info, body, la, fid);
1948                                 }
1949                         }
1950                 } else
1951                         rc = err_serious(rc);
1952         }
1953         if (rc == 0)
1954                 mdt_counter_incr(req, LPROC_MDT_SYNC);
1955
1956         RETURN(rc);
1957 }
1958
1959 /*
1960  * Quotacheck handler.
1961  * in-kernel quotacheck isn't supported any more.
1962  */
1963 int mdt_quotacheck(struct mdt_thread_info *info)
1964 {
1965         struct obd_quotactl     *oqctl;
1966         int                      rc;
1967         ENTRY;
1968
1969         oqctl = req_capsule_client_get(info->mti_pill, &RMF_OBD_QUOTACTL);
1970         if (oqctl == NULL)
1971                 RETURN(err_serious(-EPROTO));
1972
1973         rc = req_capsule_server_pack(info->mti_pill);
1974         if (rc)
1975                 RETURN(err_serious(rc));
1976
1977         /* deprecated, not used any more */
1978         RETURN(-EOPNOTSUPP);
1979 }
1980
1981 /*
1982  * Handle quota control requests to consult current usage/limit, but also
1983  * to configure quota enforcement
1984  */
1985 int mdt_quotactl(struct mdt_thread_info *info)
1986 {
1987         struct obd_export       *exp  = info->mti_exp;
1988         struct req_capsule      *pill = info->mti_pill;
1989         struct obd_quotactl     *oqctl, *repoqc;
1990         int                      id, rc;
1991         struct lu_device        *qmt = info->mti_mdt->mdt_qmt_dev;
1992         ENTRY;
1993
1994         oqctl = req_capsule_client_get(pill, &RMF_OBD_QUOTACTL);
1995         if (oqctl == NULL)
1996                 RETURN(err_serious(-EPROTO));
1997
1998         rc = req_capsule_server_pack(pill);
1999         if (rc)
2000                 RETURN(err_serious(rc));
2001
2002         switch (oqctl->qc_cmd) {
2003         case Q_QUOTACHECK:
2004         case LUSTRE_Q_INVALIDATE:
2005         case LUSTRE_Q_FINVALIDATE:
2006         case Q_QUOTAON:
2007         case Q_QUOTAOFF:
2008         case Q_INITQUOTA:
2009                 /* deprecated, not used any more */
2010                 RETURN(-EOPNOTSUPP);
2011                 /* master quotactl */
2012         case Q_GETINFO:
2013         case Q_SETINFO:
2014         case Q_SETQUOTA:
2015         case Q_GETQUOTA:
2016                 if (qmt == NULL)
2017                         RETURN(-EOPNOTSUPP);
2018                 /* slave quotactl */
2019         case Q_GETOINFO:
2020         case Q_GETOQUOTA:
2021                 break;
2022         default:
2023                 CERROR("Unsupported quotactl command: %d\n", oqctl->qc_cmd);
2024                 RETURN(-EFAULT);
2025         }
2026
2027         /* map uid/gid for remote client */
2028         id = oqctl->qc_id;
2029         if (exp_connect_rmtclient(exp)) {
2030                 struct lustre_idmap_table *idmap;
2031
2032                 idmap = mdt_req2med(mdt_info_req(info))->med_idmap;
2033
2034                 if (unlikely(oqctl->qc_cmd != Q_GETQUOTA &&
2035                              oqctl->qc_cmd != Q_GETINFO))
2036                         RETURN(-EPERM);
2037
2038                 if (oqctl->qc_type == USRQUOTA)
2039                         id = lustre_idmap_lookup_uid(NULL, idmap, 0,
2040                                                      oqctl->qc_id);
2041                 else if (oqctl->qc_type == GRPQUOTA)
2042                         id = lustre_idmap_lookup_gid(NULL, idmap, 0,
2043                                                      oqctl->qc_id);
2044                 else
2045                         RETURN(-EINVAL);
2046
2047                 if (id == CFS_IDMAP_NOTFOUND) {
2048                         CDEBUG(D_QUOTA, "no mapping for id %u\n", oqctl->qc_id);
2049                         RETURN(-EACCES);
2050                 }
2051         }
2052
2053         repoqc = req_capsule_server_get(pill, &RMF_OBD_QUOTACTL);
2054         if (repoqc == NULL)
2055                 RETURN(err_serious(-EFAULT));
2056
2057         if (oqctl->qc_id != id)
2058                 swap(oqctl->qc_id, id);
2059
2060         switch (oqctl->qc_cmd) {
2061
2062         case Q_GETINFO:
2063         case Q_SETINFO:
2064         case Q_SETQUOTA:
2065         case Q_GETQUOTA:
2066                 /* forward quotactl request to QMT */
2067                 rc = qmt_hdls.qmth_quotactl(info->mti_env, qmt, oqctl);
2068                 break;
2069
2070         case Q_GETOINFO:
2071         case Q_GETOQUOTA:
2072                 /* slave quotactl */
2073                 rc = lquotactl_slv(info->mti_env, info->mti_mdt->mdt_bottom,
2074                                    oqctl);
2075                 break;
2076
2077         default:
2078                 CERROR("Unsupported quotactl command: %d\n", oqctl->qc_cmd);
2079                 RETURN(-EFAULT);
2080         }
2081
2082         if (oqctl->qc_id != id)
2083                 swap(oqctl->qc_id, id);
2084
2085         *repoqc = *oqctl;
2086         RETURN(rc);
2087 }
2088
2089 /*
2090  * OBD PING and other handlers.
2091  */
2092 int mdt_obd_ping(struct mdt_thread_info *info)
2093 {
2094         int rc;
2095         ENTRY;
2096
2097         req_capsule_set(info->mti_pill, &RQF_OBD_PING);
2098
2099         rc = target_handle_ping(mdt_info_req(info));
2100         if (rc < 0)
2101                 rc = err_serious(rc);
2102         RETURN(rc);
2103 }
2104
2105 /*
2106  * OBD_IDX_READ handler
2107  */
2108 int mdt_obd_idx_read(struct mdt_thread_info *info)
2109 {
2110         struct mdt_device       *mdt = info->mti_mdt;
2111         struct lu_rdpg          *rdpg = &info->mti_u.rdpg.mti_rdpg;
2112         struct idx_info         *req_ii, *rep_ii;
2113         int                      rc, i;
2114         ENTRY;
2115
2116         memset(rdpg, 0, sizeof(*rdpg));
2117         req_capsule_set(info->mti_pill, &RQF_OBD_IDX_READ);
2118
2119         /* extract idx_info buffer from request & reply */
2120         req_ii = req_capsule_client_get(info->mti_pill, &RMF_IDX_INFO);
2121         if (req_ii == NULL || req_ii->ii_magic != IDX_INFO_MAGIC)
2122                 RETURN(err_serious(-EPROTO));
2123
2124         rc = req_capsule_server_pack(info->mti_pill);
2125         if (rc)
2126                 RETURN(err_serious(rc));
2127
2128         rep_ii = req_capsule_server_get(info->mti_pill, &RMF_IDX_INFO);
2129         if (rep_ii == NULL)
2130                 RETURN(err_serious(-EFAULT));
2131         rep_ii->ii_magic = IDX_INFO_MAGIC;
2132
2133         /* extract hash to start with */
2134         rdpg->rp_hash = req_ii->ii_hash_start;
2135
2136         /* extract requested attributes */
2137         rdpg->rp_attrs = req_ii->ii_attrs;
2138
2139         /* check that fid packed in request is valid and supported */
2140         if (!fid_is_sane(&req_ii->ii_fid))
2141                 RETURN(-EINVAL);
2142         rep_ii->ii_fid = req_ii->ii_fid;
2143
2144         /* copy flags */
2145         rep_ii->ii_flags = req_ii->ii_flags;
2146
2147         /* compute number of pages to allocate, ii_count is the number of 4KB
2148          * containers */
2149         if (req_ii->ii_count <= 0)
2150                 GOTO(out, rc = -EFAULT);
2151         rdpg->rp_count = min_t(unsigned int, req_ii->ii_count << LU_PAGE_SHIFT,
2152                                exp_max_brw_size(info->mti_exp));
2153         rdpg->rp_npages = (rdpg->rp_count + PAGE_CACHE_SIZE - 1) >>
2154                                 PAGE_CACHE_SHIFT;
2155
2156         /* allocate pages to store the containers */
2157         OBD_ALLOC(rdpg->rp_pages, rdpg->rp_npages * sizeof(rdpg->rp_pages[0]));
2158         if (rdpg->rp_pages == NULL)
2159                 GOTO(out, rc = -ENOMEM);
2160         for (i = 0; i < rdpg->rp_npages; i++) {
2161                 rdpg->rp_pages[i] = alloc_page(GFP_IOFS);
2162                 if (rdpg->rp_pages[i] == NULL)
2163                         GOTO(out, rc = -ENOMEM);
2164         }
2165
2166         /* populate pages with key/record pairs */
2167         rc = dt_index_read(info->mti_env, mdt->mdt_bottom, rep_ii, rdpg);
2168         if (rc < 0)
2169                 GOTO(out, rc);
2170
2171         LASSERTF(rc <= rdpg->rp_count, "dt_index_read() returned more than "
2172                  "asked %d > %d\n", rc, rdpg->rp_count);
2173
2174         /* send pages to client */
2175         rc = mdt_sendpage(info, rdpg, rc);
2176
2177         GOTO(out, rc);
2178 out:
2179         if (rdpg->rp_pages) {
2180                 for (i = 0; i < rdpg->rp_npages; i++)
2181                         if (rdpg->rp_pages[i])
2182                                 __free_page(rdpg->rp_pages[i]);
2183                 OBD_FREE(rdpg->rp_pages,
2184                          rdpg->rp_npages * sizeof(rdpg->rp_pages[0]));
2185         }
2186         return rc;
2187 }
2188
2189 int mdt_obd_log_cancel(struct mdt_thread_info *info)
2190 {
2191         return err_serious(-EOPNOTSUPP);
2192 }
2193
2194 int mdt_obd_qc_callback(struct mdt_thread_info *info)
2195 {
2196         return err_serious(-EOPNOTSUPP);
2197 }
2198
2199 /*
2200  * LLOG handlers.
2201  */
2202
2203 /** clone llog ctxt from child (mdd)
2204  * This allows remote llog (replicator) access.
2205  * We can either pass all llog RPCs (eg mdt_llog_create) on to child where the
2206  * context was originally set up, or we can handle them directly.
2207  * I choose the latter, but that means I need any llog
2208  * contexts set up by child to be accessable by the mdt.  So we clone the
2209  * context into our context list here.
2210  */
2211 static int mdt_llog_ctxt_clone(const struct lu_env *env, struct mdt_device *mdt,
2212                                int idx)
2213 {
2214         struct md_device  *next = mdt->mdt_child;
2215         struct llog_ctxt *ctxt;
2216         int rc;
2217
2218         if (!llog_ctxt_null(mdt2obd_dev(mdt), idx))
2219                 return 0;
2220
2221         rc = next->md_ops->mdo_llog_ctxt_get(env, next, idx, (void **)&ctxt);
2222         if (rc || ctxt == NULL) {
2223                 return 0;
2224         }
2225
2226         rc = llog_group_set_ctxt(&mdt2obd_dev(mdt)->obd_olg, ctxt, idx);
2227         if (rc)
2228                 CERROR("Can't set mdt ctxt %d\n", rc);
2229
2230         return rc;
2231 }
2232
2233 static int mdt_llog_ctxt_unclone(const struct lu_env *env,
2234                                  struct mdt_device *mdt, int idx)
2235 {
2236         struct llog_ctxt *ctxt;
2237
2238         ctxt = llog_get_context(mdt2obd_dev(mdt), idx);
2239         if (ctxt == NULL)
2240                 return 0;
2241         /* Put once for the get we just did, and once for the clone */
2242         llog_ctxt_put(ctxt);
2243         llog_ctxt_put(ctxt);
2244         return 0;
2245 }
2246
2247 int mdt_llog_create(struct mdt_thread_info *info)
2248 {
2249         int rc;
2250
2251         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
2252         rc = llog_origin_handle_open(mdt_info_req(info));
2253         return (rc < 0 ? err_serious(rc) : rc);
2254 }
2255
2256 int mdt_llog_destroy(struct mdt_thread_info *info)
2257 {
2258         int rc;
2259
2260         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_DESTROY);
2261         rc = llog_origin_handle_destroy(mdt_info_req(info));
2262         return (rc < 0 ? err_serious(rc) : rc);
2263 }
2264
2265 int mdt_llog_read_header(struct mdt_thread_info *info)
2266 {
2267         int rc;
2268
2269         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_READ_HEADER);
2270         rc = llog_origin_handle_read_header(mdt_info_req(info));
2271         return (rc < 0 ? err_serious(rc) : rc);
2272 }
2273
2274 int mdt_llog_next_block(struct mdt_thread_info *info)
2275 {
2276         int rc;
2277
2278         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
2279         rc = llog_origin_handle_next_block(mdt_info_req(info));
2280         return (rc < 0 ? err_serious(rc) : rc);
2281 }
2282
2283 int mdt_llog_prev_block(struct mdt_thread_info *info)
2284 {
2285         int rc;
2286
2287         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_PREV_BLOCK);
2288         rc = llog_origin_handle_prev_block(mdt_info_req(info));
2289         return (rc < 0 ? err_serious(rc) : rc);
2290 }
2291
2292
2293 /*
2294  * DLM handlers.
2295  */
2296
2297 static struct ldlm_callback_suite cbs = {
2298         .lcs_completion = ldlm_server_completion_ast,
2299         .lcs_blocking   = ldlm_server_blocking_ast,
2300         .lcs_glimpse    = ldlm_server_glimpse_ast
2301 };
2302
2303 int mdt_enqueue(struct mdt_thread_info *info)
2304 {
2305         struct ptlrpc_request *req;
2306         int rc;
2307
2308         /*
2309          * info->mti_dlm_req already contains swapped and (if necessary)
2310          * converted dlm request.
2311          */
2312         LASSERT(info->mti_dlm_req != NULL);
2313
2314         req = mdt_info_req(info);
2315         rc = ldlm_handle_enqueue0(info->mti_mdt->mdt_namespace,
2316                                   req, info->mti_dlm_req, &cbs);
2317         info->mti_fail_id = OBD_FAIL_LDLM_REPLY;
2318         return rc ? err_serious(rc) : req->rq_status;
2319 }
2320
2321 int mdt_convert(struct mdt_thread_info *info)
2322 {
2323         int rc;
2324         struct ptlrpc_request *req;
2325
2326         LASSERT(info->mti_dlm_req);
2327         req = mdt_info_req(info);
2328         rc = ldlm_handle_convert0(req, info->mti_dlm_req);
2329         return rc ? err_serious(rc) : req->rq_status;
2330 }
2331
2332 int mdt_bl_callback(struct mdt_thread_info *info)
2333 {
2334         CERROR("bl callbacks should not happen on MDS\n");
2335         LBUG();
2336         return err_serious(-EOPNOTSUPP);
2337 }
2338
2339 int mdt_cp_callback(struct mdt_thread_info *info)
2340 {
2341         CERROR("cp callbacks should not happen on MDS\n");
2342         LBUG();
2343         return err_serious(-EOPNOTSUPP);
2344 }
2345
2346 /*
2347  * sec context handlers
2348  */
2349 int mdt_sec_ctx_handle(struct mdt_thread_info *info)
2350 {
2351         int rc;
2352
2353         rc = mdt_handle_idmap(info);
2354
2355         if (unlikely(rc)) {
2356                 struct ptlrpc_request *req = mdt_info_req(info);
2357                 __u32                  opc;
2358
2359                 opc = lustre_msg_get_opc(req->rq_reqmsg);
2360                 if (opc == SEC_CTX_INIT || opc == SEC_CTX_INIT_CONT)
2361                         sptlrpc_svc_ctx_invalidate(req);
2362         }
2363
2364         CFS_FAIL_TIMEOUT(OBD_FAIL_SEC_CTX_HDL_PAUSE, cfs_fail_val);
2365
2366         return rc;
2367 }
2368
2369 /*
2370  * quota request handlers
2371  */
2372 int mdt_quota_dqacq(struct mdt_thread_info *info)
2373 {
2374         struct lu_device        *qmt = info->mti_mdt->mdt_qmt_dev;
2375         int                      rc;
2376         ENTRY;
2377
2378         if (qmt == NULL)
2379                 RETURN(err_serious(-EOPNOTSUPP));
2380
2381         rc = qmt_hdls.qmth_dqacq(info->mti_env, qmt, mdt_info_req(info));
2382         RETURN(rc);
2383 }
2384
2385 static struct mdt_object *mdt_obj(struct lu_object *o)
2386 {
2387         LASSERT(lu_device_is_mdt(o->lo_dev));
2388         return container_of0(o, struct mdt_object, mot_obj);
2389 }
2390
2391 struct mdt_object *mdt_object_new(const struct lu_env *env,
2392                                   struct mdt_device *d,
2393                                   const struct lu_fid *f)
2394 {
2395         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
2396         struct lu_object *o;
2397         struct mdt_object *m;
2398         ENTRY;
2399
2400         CDEBUG(D_INFO, "Allocate object for "DFID"\n", PFID(f));
2401         o = lu_object_find(env, &d->mdt_lu_dev, f, &conf);
2402         if (unlikely(IS_ERR(o)))
2403                 m = (struct mdt_object *)o;
2404         else
2405                 m = mdt_obj(o);
2406         RETURN(m);
2407 }
2408
2409 struct mdt_object *mdt_object_find(const struct lu_env *env,
2410                                    struct mdt_device *d,
2411                                    const struct lu_fid *f)
2412 {
2413         struct lu_object *o;
2414         struct mdt_object *m;
2415         ENTRY;
2416
2417         CDEBUG(D_INFO, "Find object for "DFID"\n", PFID(f));
2418         o = lu_object_find(env, &d->mdt_lu_dev, f, NULL);
2419         if (unlikely(IS_ERR(o)))
2420                 m = (struct mdt_object *)o;
2421         else
2422                 m = mdt_obj(o);
2423
2424         RETURN(m);
2425 }
2426
2427 /**
2428  * Asyncronous commit for mdt device.
2429  *
2430  * Pass asynchonous commit call down the MDS stack.
2431  *
2432  * \param env environment
2433  * \param mdt the mdt device
2434  */
2435 static void mdt_device_commit_async(const struct lu_env *env,
2436                                     struct mdt_device *mdt)
2437 {
2438         struct dt_device *dt = mdt->mdt_bottom;
2439         int rc;
2440
2441         rc = dt->dd_ops->dt_commit_async(env, dt);
2442         if (unlikely(rc != 0))
2443                 CWARN("async commit start failed with rc = %d", rc);
2444 }
2445
2446 /**
2447  * Mark the lock as "synchonous".
2448  *
2449  * Mark the lock to deffer transaction commit to the unlock time.
2450  *
2451  * \param lock the lock to mark as "synchonous"
2452  *
2453  * \see mdt_is_lock_sync
2454  * \see mdt_save_lock
2455  */
2456 static inline void mdt_set_lock_sync(struct ldlm_lock *lock)
2457 {
2458         lock->l_ast_data = (void*)1;
2459 }
2460
2461 /**
2462  * Check whehter the lock "synchonous" or not.
2463  *
2464  * \param lock the lock to check
2465  * \retval 1 the lock is "synchonous"
2466  * \retval 0 the lock isn't "synchronous"
2467  *
2468  * \see mdt_set_lock_sync
2469  * \see mdt_save_lock
2470  */
2471 static inline int mdt_is_lock_sync(struct ldlm_lock *lock)
2472 {
2473         return lock->l_ast_data != NULL;
2474 }
2475
2476 /**
2477  * Blocking AST for mdt locks.
2478  *
2479  * Starts transaction commit if in case of COS lock conflict or
2480  * deffers such a commit to the mdt_save_lock.
2481  *
2482  * \param lock the lock which blocks a request or cancelling lock
2483  * \param desc unused
2484  * \param data unused
2485  * \param flag indicates whether this cancelling or blocking callback
2486  * \retval 0
2487  * \see ldlm_blocking_ast_nocheck
2488  */
2489 int mdt_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
2490                      void *data, int flag)
2491 {
2492         struct obd_device *obd = ldlm_lock_to_ns(lock)->ns_obd;
2493         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
2494         int rc;
2495         ENTRY;
2496
2497         if (flag == LDLM_CB_CANCELING)
2498                 RETURN(0);
2499         lock_res_and_lock(lock);
2500         if (lock->l_blocking_ast != mdt_blocking_ast) {
2501                 unlock_res_and_lock(lock);
2502                 RETURN(0);
2503         }
2504         if (mdt_cos_is_enabled(mdt) &&
2505             lock->l_req_mode & (LCK_PW | LCK_EX) &&
2506             lock->l_blocking_lock != NULL &&
2507             lock->l_client_cookie != lock->l_blocking_lock->l_client_cookie) {
2508                 mdt_set_lock_sync(lock);
2509         }
2510         rc = ldlm_blocking_ast_nocheck(lock);
2511
2512         /* There is no lock conflict if l_blocking_lock == NULL,
2513          * it indicates a blocking ast sent from ldlm_lock_decref_internal
2514          * when the last reference to a local lock was released */
2515         if (lock->l_req_mode == LCK_COS && lock->l_blocking_lock != NULL) {
2516                 struct lu_env env;
2517
2518                 rc = lu_env_init(&env, LCT_LOCAL);
2519                 if (unlikely(rc != 0))
2520                         CWARN("lu_env initialization failed with rc = %d,"
2521                               "cannot start asynchronous commit\n", rc);
2522                 else
2523                         mdt_device_commit_async(&env, mdt);
2524                 lu_env_fini(&env);
2525         }
2526         RETURN(rc);
2527 }
2528
2529 int mdt_md_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
2530                         void *data, int flag)
2531 {
2532         struct lustre_handle lockh;
2533         int               rc;
2534
2535         switch (flag) {
2536         case LDLM_CB_BLOCKING:
2537                 ldlm_lock2handle(lock, &lockh);
2538                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
2539                 if (rc < 0) {
2540                         CDEBUG(D_INODE, "ldlm_cli_cancel: %d\n", rc);
2541                         RETURN(rc);
2542                 }
2543                 break;
2544         case LDLM_CB_CANCELING:
2545                 LDLM_DEBUG(lock, "Revoke remote lock\n");
2546                 break;
2547         default:
2548                 LBUG();
2549         }
2550         RETURN(0);
2551 }
2552
2553 int mdt_remote_object_lock(struct mdt_thread_info *mti,
2554                            struct mdt_object *o, struct lustre_handle *lh,
2555                            ldlm_mode_t mode, __u64 ibits)
2556 {
2557         struct ldlm_enqueue_info *einfo = &mti->mti_einfo;
2558         ldlm_policy_data_t *policy = &mti->mti_policy;
2559         int rc = 0;
2560         ENTRY;
2561
2562         LASSERT(mdt_object_remote(o));
2563
2564         LASSERT(ibits & MDS_INODELOCK_UPDATE);
2565
2566         memset(einfo, 0, sizeof(*einfo));
2567         einfo->ei_type = LDLM_IBITS;
2568         einfo->ei_mode = mode;
2569         einfo->ei_cb_bl = mdt_md_blocking_ast;
2570         einfo->ei_cb_cp = ldlm_completion_ast;
2571
2572         memset(policy, 0, sizeof(*policy));
2573         policy->l_inodebits.bits = ibits;
2574
2575         rc = mo_object_lock(mti->mti_env, mdt_object_child(o), lh, einfo,
2576                             policy);
2577         RETURN(rc);
2578 }
2579
2580 static int mdt_object_lock0(struct mdt_thread_info *info, struct mdt_object *o,
2581                             struct mdt_lock_handle *lh, __u64 ibits,
2582                             bool nonblock, int locality)
2583 {
2584         struct ldlm_namespace *ns = info->mti_mdt->mdt_namespace;
2585         ldlm_policy_data_t *policy = &info->mti_policy;
2586         struct ldlm_res_id *res_id = &info->mti_res_id;
2587         __u64 dlmflags;
2588         int rc;
2589         ENTRY;
2590
2591         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2592         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2593         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
2594         LASSERT(lh->mlh_type != MDT_NUL_LOCK);
2595
2596         if (mdt_object_remote(o)) {
2597                 if (locality == MDT_CROSS_LOCK) {
2598                         ibits &= ~(MDS_INODELOCK_UPDATE | MDS_INODELOCK_PERM);
2599                         ibits |= MDS_INODELOCK_LOOKUP;
2600                 } else {
2601                         LASSERTF(!(ibits &
2602                                   (MDS_INODELOCK_UPDATE | MDS_INODELOCK_PERM)),
2603                                 "%s: wrong bit "LPX64" for remote obj "DFID"\n",
2604                                 mdt_obd_name(info->mti_mdt), ibits,
2605                                 PFID(mdt_object_fid(o)));
2606                         LASSERT(ibits & MDS_INODELOCK_LOOKUP);
2607                 }
2608                 /* No PDO lock on remote object */
2609                 LASSERT(lh->mlh_type != MDT_PDO_LOCK);
2610         }
2611
2612         if (lh->mlh_type == MDT_PDO_LOCK) {
2613                 /* check for exists after object is locked */
2614                 if (mdt_object_exists(o) == 0) {
2615                         /* Non-existent object shouldn't have PDO lock */
2616                         RETURN(-ESTALE);
2617                 } else {
2618                         /* Non-dir object shouldn't have PDO lock */
2619                         if (!S_ISDIR(lu_object_attr(&o->mot_obj)))
2620                                 RETURN(-ENOTDIR);
2621                 }
2622         }
2623
2624         memset(policy, 0, sizeof(*policy));
2625         fid_build_reg_res_name(mdt_object_fid(o), res_id);
2626
2627         dlmflags = LDLM_FL_ATOMIC_CB;
2628         if (nonblock)
2629                 dlmflags |= LDLM_FL_BLOCK_NOWAIT;
2630
2631         /*
2632          * Take PDO lock on whole directory and build correct @res_id for lock
2633          * on part of directory.
2634          */
2635         if (lh->mlh_pdo_hash != 0) {
2636                 LASSERT(lh->mlh_type == MDT_PDO_LOCK);
2637                 mdt_lock_pdo_mode(info, o, lh);
2638                 if (lh->mlh_pdo_mode != LCK_NL) {
2639                         /*
2640                          * Do not use LDLM_FL_LOCAL_ONLY for parallel lock, it
2641                          * is never going to be sent to client and we do not
2642                          * want it slowed down due to possible cancels.
2643                          */
2644                         policy->l_inodebits.bits = MDS_INODELOCK_UPDATE;
2645                         rc = mdt_fid_lock(ns, &lh->mlh_pdo_lh, lh->mlh_pdo_mode,
2646                                           policy, res_id, dlmflags,
2647                                           &info->mti_exp->exp_handle.h_cookie);
2648                         if (unlikely(rc))
2649                                 RETURN(rc);
2650                 }
2651
2652                 /*
2653                  * Finish res_id initializing by name hash marking part of
2654                  * directory which is taking modification.
2655                  */
2656                 res_id->name[LUSTRE_RES_ID_HSH_OFF] = lh->mlh_pdo_hash;
2657         }
2658
2659         policy->l_inodebits.bits = ibits;
2660
2661         /*
2662          * Use LDLM_FL_LOCAL_ONLY for this lock. We do not know yet if it is
2663          * going to be sent to client. If it is - mdt_intent_policy() path will
2664          * fix it up and turn FL_LOCAL flag off.
2665          */
2666         rc = mdt_fid_lock(ns, &lh->mlh_reg_lh, lh->mlh_reg_mode, policy,
2667                           res_id, LDLM_FL_LOCAL_ONLY | dlmflags,
2668                           &info->mti_exp->exp_handle.h_cookie);
2669         if (rc)
2670                 mdt_object_unlock(info, o, lh, 1);
2671         else if (unlikely(OBD_FAIL_PRECHECK(OBD_FAIL_MDS_PDO_LOCK)) &&
2672                  lh->mlh_pdo_hash != 0 &&
2673                  (lh->mlh_reg_mode == LCK_PW || lh->mlh_reg_mode == LCK_EX)) {
2674                 OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_PDO_LOCK, 15);
2675         }
2676
2677         RETURN(rc);
2678 }
2679
2680 int mdt_object_lock(struct mdt_thread_info *info, struct mdt_object *o,
2681                     struct mdt_lock_handle *lh, __u64 ibits, int locality)
2682 {
2683         return mdt_object_lock0(info, o, lh, ibits, false, locality);
2684 }
2685
2686 int mdt_object_lock_try(struct mdt_thread_info *info, struct mdt_object *o,
2687                         struct mdt_lock_handle *lh, __u64 ibits, int locality)
2688 {
2689         struct mdt_lock_handle tmp = *lh;
2690         int rc;
2691
2692         rc = mdt_object_lock0(info, o, &tmp, ibits, true, locality);
2693         if (rc == 0)
2694                 *lh = tmp;
2695
2696         return rc == 0;
2697 }
2698
2699 /**
2700  * Save a lock within request object.
2701  *
2702  * Keep the lock referenced until whether client ACK or transaction
2703  * commit happens or release the lock immediately depending on input
2704  * parameters. If COS is ON, a write lock is converted to COS lock
2705  * before saving.
2706  *
2707  * \param info thead info object
2708  * \param h lock handle
2709  * \param mode lock mode
2710  * \param decref force immediate lock releasing
2711  */
2712 static
2713 void mdt_save_lock(struct mdt_thread_info *info, struct lustre_handle *h,
2714                    ldlm_mode_t mode, int decref)
2715 {
2716         ENTRY;
2717
2718         if (lustre_handle_is_used(h)) {
2719                 if (decref || !info->mti_has_trans ||
2720                     !(mode & (LCK_PW | LCK_EX))){
2721                         mdt_fid_unlock(h, mode);
2722                 } else {
2723                         struct mdt_device *mdt = info->mti_mdt;
2724                         struct ldlm_lock *lock = ldlm_handle2lock(h);
2725                         struct ptlrpc_request *req = mdt_info_req(info);
2726                         int no_ack = 0;
2727
2728                         LASSERTF(lock != NULL, "no lock for cookie "LPX64"\n",
2729                                  h->cookie);
2730                         CDEBUG(D_HA, "request = %p reply state = %p"
2731                                " transno = "LPD64"\n",
2732                                req, req->rq_reply_state, req->rq_transno);
2733                         if (mdt_cos_is_enabled(mdt)) {
2734                                 no_ack = 1;
2735                                 ldlm_lock_downgrade(lock, LCK_COS);
2736                                 mode = LCK_COS;
2737                         }
2738                         ptlrpc_save_lock(req, h, mode, no_ack);
2739                         if (mdt_is_lock_sync(lock)) {
2740                                 CDEBUG(D_HA, "found sync-lock,"
2741                                        " async commit started\n");
2742                                 mdt_device_commit_async(info->mti_env,
2743                                                         mdt);
2744                         }
2745                         LDLM_LOCK_PUT(lock);
2746                 }
2747                 h->cookie = 0ull;
2748         }
2749
2750         EXIT;
2751 }
2752
2753 /**
2754  * Unlock mdt object.
2755  *
2756  * Immeditely release the regular lock and the PDO lock or save the
2757  * lock in reqeuest and keep them referenced until client ACK or
2758  * transaction commit.
2759  *
2760  * \param info thread info object
2761  * \param o mdt object
2762  * \param lh mdt lock handle referencing regular and PDO locks
2763  * \param decref force immediate lock releasing
2764  */
2765 void mdt_object_unlock(struct mdt_thread_info *info, struct mdt_object *o,
2766                        struct mdt_lock_handle *lh, int decref)
2767 {
2768         ENTRY;
2769
2770         mdt_save_lock(info, &lh->mlh_pdo_lh, lh->mlh_pdo_mode, decref);
2771         mdt_save_lock(info, &lh->mlh_reg_lh, lh->mlh_reg_mode, decref);
2772
2773         if (lustre_handle_is_used(&lh->mlh_rreg_lh))
2774                 ldlm_lock_decref(&lh->mlh_rreg_lh, lh->mlh_rreg_mode);
2775
2776         EXIT;
2777 }
2778
2779 struct mdt_object *mdt_object_find_lock(struct mdt_thread_info *info,
2780                                         const struct lu_fid *f,
2781                                         struct mdt_lock_handle *lh,
2782                                         __u64 ibits)
2783 {
2784         struct mdt_object *o;
2785
2786         o = mdt_object_find(info->mti_env, info->mti_mdt, f);
2787         if (!IS_ERR(o)) {
2788                 int rc;
2789
2790                 rc = mdt_object_lock(info, o, lh, ibits,
2791                                      MDT_LOCAL_LOCK);
2792                 if (rc != 0) {
2793                         mdt_object_put(info->mti_env, o);
2794                         o = ERR_PTR(rc);
2795                 }
2796         }
2797         return o;
2798 }
2799
2800 void mdt_object_unlock_put(struct mdt_thread_info * info,
2801                            struct mdt_object * o,
2802                            struct mdt_lock_handle *lh,
2803                            int decref)
2804 {
2805         mdt_object_unlock(info, o, lh, decref);
2806         mdt_object_put(info->mti_env, o);
2807 }
2808
2809 struct mdt_handler *mdt_handler_find(__u32 opc, struct mdt_opc_slice *supported)
2810 {
2811         struct mdt_opc_slice *s;
2812         struct mdt_handler   *h;
2813
2814         h = NULL;
2815         for (s = supported; s->mos_hs != NULL; s++) {
2816                 if (s->mos_opc_start <= opc && opc < s->mos_opc_end) {
2817                         h = s->mos_hs + (opc - s->mos_opc_start);
2818                         if (likely(h->mh_opc != 0))
2819                                 LASSERTF(h->mh_opc == opc,
2820                                          "opcode mismatch %d != %d\n",
2821                                          h->mh_opc, opc);
2822                         else
2823                                 h = NULL; /* unsupported opc */
2824                         break;
2825                 }
2826         }
2827         return h;
2828 }
2829
2830 static int mdt_lock_resname_compat(struct mdt_device *m,
2831                                    struct ldlm_request *req)
2832 {
2833         /* XXX something... later. */
2834         return 0;
2835 }
2836
2837 static int mdt_lock_reply_compat(struct mdt_device *m, struct ldlm_reply *rep)
2838 {
2839         /* XXX something... later. */
2840         return 0;
2841 }
2842
2843 /*
2844  * Generic code handling requests that have struct mdt_body passed in:
2845  *
2846  *  - extract mdt_body from request and save it in @info, if present;
2847  *
2848  *  - create lu_object, corresponding to the fid in mdt_body, and save it in
2849  *  @info;
2850  *
2851  *  - if HABEO_CORPUS flag is set for this request type check whether object
2852  *  actually exists on storage (lu_object_exists()).
2853  *
2854  */
2855 static int mdt_body_unpack(struct mdt_thread_info *info, __u32 flags)
2856 {
2857         const struct mdt_body    *body;
2858         struct mdt_object        *obj;
2859         const struct lu_env      *env;
2860         struct req_capsule       *pill;
2861         int                       rc;
2862         ENTRY;
2863
2864         env = info->mti_env;
2865         pill = info->mti_pill;
2866
2867         body = info->mti_body = req_capsule_client_get(pill, &RMF_MDT_BODY);
2868         if (body == NULL)
2869                 RETURN(-EFAULT);
2870
2871         if (!(body->valid & OBD_MD_FLID))
2872                 RETURN(0);
2873
2874         if (!fid_is_sane(&body->fid1)) {
2875                 CERROR("Invalid fid: "DFID"\n", PFID(&body->fid1));
2876                 RETURN(-EINVAL);
2877         }
2878
2879         /*
2880          * Do not get size or any capa fields before we check that request
2881          * contains capa actually. There are some requests which do not, for
2882          * instance MDS_IS_SUBDIR.
2883          */
2884         if (req_capsule_has_field(pill, &RMF_CAPA1, RCL_CLIENT) &&
2885             req_capsule_get_size(pill, &RMF_CAPA1, RCL_CLIENT))
2886                 mdt_set_capainfo(info, 0, &body->fid1,
2887                                  req_capsule_client_get(pill, &RMF_CAPA1));
2888
2889         obj = mdt_object_find(env, info->mti_mdt, &body->fid1);
2890         if (!IS_ERR(obj)) {
2891                 if ((flags & HABEO_CORPUS) &&
2892                     !mdt_object_exists(obj)) {
2893                         mdt_object_put(env, obj);
2894                         /* for capability renew ENOENT will be handled in
2895                          * mdt_renew_capa */
2896                         if (body->valid & OBD_MD_FLOSSCAPA)
2897                                 rc = 0;
2898                         else
2899                                 rc = -ENOENT;
2900                 } else {
2901                         info->mti_object = obj;
2902                         rc = 0;
2903                 }
2904         } else
2905                 rc = PTR_ERR(obj);
2906
2907         RETURN(rc);
2908 }
2909
2910 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags)
2911 {
2912         struct req_capsule *pill = info->mti_pill;
2913         int rc;
2914         ENTRY;
2915
2916         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_CLIENT))
2917                 rc = mdt_body_unpack(info, flags);
2918         else
2919                 rc = 0;
2920
2921         if (rc == 0 && (flags & HABEO_REFERO)) {
2922                 /* Pack reply. */
2923                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
2924                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
2925                                              info->mti_body->eadatasize);
2926                 if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
2927                         req_capsule_set_size(pill, &RMF_LOGCOOKIES,
2928                                              RCL_SERVER, 0);
2929
2930                 rc = req_capsule_server_pack(pill);
2931         }
2932         RETURN(rc);
2933 }
2934
2935 static int mdt_init_capa_ctxt(const struct lu_env *env, struct mdt_device *m)
2936 {
2937         struct md_device *next = m->mdt_child;
2938
2939         return next->md_ops->mdo_init_capa_ctxt(env, next,
2940                                                 m->mdt_opts.mo_mds_capa,
2941                                                 m->mdt_capa_timeout,
2942                                                 m->mdt_capa_alg,
2943                                                 m->mdt_capa_keys);
2944 }
2945
2946 /*
2947  * Invoke handler for this request opc. Also do necessary preprocessing
2948  * (according to handler ->mh_flags), and post-processing (setting of
2949  * ->last_{xid,committed}).
2950  */
2951 static int mdt_req_handle(struct mdt_thread_info *info,
2952                           struct mdt_handler *h, struct ptlrpc_request *req)
2953 {
2954         int   rc, serious = 0;
2955         __u32 flags;
2956
2957         ENTRY;
2958
2959         LASSERT(h->mh_act != NULL);
2960         LASSERT(h->mh_opc == lustre_msg_get_opc(req->rq_reqmsg));
2961         LASSERT(current->journal_info == NULL);
2962
2963         /*
2964          * Checking for various OBD_FAIL_$PREF_$OPC_NET codes. _Do_ not try
2965          * to put same checks into handlers like mdt_close(), mdt_reint(),
2966          * etc., without talking to mdt authors first. Checking same thing
2967          * there again is useless and returning 0 error without packing reply
2968          * is buggy! Handlers either pack reply or return error.
2969          *
2970          * We return 0 here and do not send any reply in order to emulate
2971          * network failure. Do not send any reply in case any of NET related
2972          * fail_id has occured.
2973          */
2974         if (OBD_FAIL_CHECK_ORSET(h->mh_fail_id, OBD_FAIL_ONCE))
2975                 RETURN(0);
2976
2977         rc = 0;
2978         flags = h->mh_flags;
2979         LASSERT(ergo(flags & (HABEO_CORPUS|HABEO_REFERO), h->mh_fmt != NULL));
2980
2981         if (h->mh_fmt != NULL) {
2982                 req_capsule_set(info->mti_pill, h->mh_fmt);
2983                 rc = mdt_unpack_req_pack_rep(info, flags);
2984         }
2985
2986         if (rc == 0 && flags & MUTABOR &&
2987             exp_connect_flags(req->rq_export) & OBD_CONNECT_RDONLY)
2988                 /* should it be rq_status? */
2989                 rc = -EROFS;
2990
2991         if (rc == 0 && flags & HABEO_CLAVIS) {
2992                 struct ldlm_request *dlm_req;
2993
2994                 LASSERT(h->mh_fmt != NULL);
2995
2996                 dlm_req = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
2997                 if (dlm_req != NULL) {
2998                         if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
2999                                         LDLM_IBITS &&
3000                                      dlm_req->lock_desc.l_policy_data.\
3001                                         l_inodebits.bits == 0)) {
3002                                 /*
3003                                  * Lock without inodebits makes no sense and
3004                                  * will oops later in ldlm. If client miss to
3005                                  * set such bits, do not trigger ASSERTION.
3006                                  *
3007                                  * For liblustre flock case, it maybe zero.
3008                                  */
3009                                 rc = -EPROTO;
3010                         } else {
3011                                 if (info->mti_mdt->mdt_opts.mo_compat_resname)
3012                                         rc = mdt_lock_resname_compat(
3013                                                                 info->mti_mdt,
3014                                                                 dlm_req);
3015                                 info->mti_dlm_req = dlm_req;
3016                         }
3017                 } else {
3018                         rc = -EFAULT;
3019                 }
3020         }
3021
3022         /* capability setting changed via /proc, needs reinitialize ctxt */
3023         if (info->mti_mdt && info->mti_mdt->mdt_capa_conf) {
3024                 mdt_init_capa_ctxt(info->mti_env, info->mti_mdt);
3025                 info->mti_mdt->mdt_capa_conf = 0;
3026         }
3027
3028         if (likely(rc == 0)) {
3029                 /*
3030                  * Process request, there can be two types of rc:
3031                  * 1) errors with msg unpack/pack, other failures outside the
3032                  * operation itself. This is counted as serious errors;
3033                  * 2) errors during fs operation, should be placed in rq_status
3034                  * only
3035                  */
3036                 rc = h->mh_act(info);
3037                 if (rc == 0 &&
3038                     !req->rq_no_reply && req->rq_reply_state == NULL) {
3039                         DEBUG_REQ(D_ERROR, req, "MDT \"handler\" %s did not "
3040                                   "pack reply and returned 0 error\n",
3041                                   h->mh_name);
3042                         LBUG();
3043                 }
3044                 serious = is_serious(rc);
3045                 rc = clear_serious(rc);
3046         } else
3047                 serious = 1;
3048
3049         req->rq_status = rc;
3050
3051         /*
3052          * ELDLM_* codes which > 0 should be in rq_status only as well as
3053          * all non-serious errors.
3054          */
3055         if (rc > 0 || !serious)
3056                 rc = 0;
3057
3058         LASSERT(current->journal_info == NULL);
3059
3060         if (rc == 0 && (flags & HABEO_CLAVIS) &&
3061             info->mti_mdt->mdt_opts.mo_compat_resname) {
3062                 struct ldlm_reply *dlmrep;
3063
3064                 dlmrep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3065                 if (dlmrep != NULL)
3066                         rc = mdt_lock_reply_compat(info->mti_mdt, dlmrep);
3067         }
3068
3069         /* If we're DISCONNECTing, the mdt_export_data is already freed */
3070         if (likely(rc == 0 && req->rq_export && h->mh_opc != MDS_DISCONNECT))
3071                 target_committed_to_req(req);
3072
3073         if (unlikely(req_is_replay(req) &&
3074                      lustre_msg_get_transno(req->rq_reqmsg) == 0)) {
3075                 DEBUG_REQ(D_ERROR, req, "transno is 0 during REPLAY");
3076                 LBUG();
3077         }
3078
3079         target_send_reply(req, rc, info->mti_fail_id);
3080         RETURN(0);
3081 }
3082
3083 void mdt_lock_handle_init(struct mdt_lock_handle *lh)
3084 {
3085         lh->mlh_type = MDT_NUL_LOCK;
3086         lh->mlh_reg_lh.cookie = 0ull;
3087         lh->mlh_reg_mode = LCK_MINMODE;
3088         lh->mlh_pdo_lh.cookie = 0ull;
3089         lh->mlh_pdo_mode = LCK_MINMODE;
3090         lh->mlh_rreg_lh.cookie = 0ull;
3091         lh->mlh_rreg_mode = LCK_MINMODE;
3092 }
3093
3094 void mdt_lock_handle_fini(struct mdt_lock_handle *lh)
3095 {
3096         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
3097         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
3098 }
3099
3100 /*
3101  * Initialize fields of struct mdt_thread_info. Other fields are left in
3102  * uninitialized state, because it's too expensive to zero out whole
3103  * mdt_thread_info (> 1K) on each request arrival.
3104  */
3105 void mdt_thread_info_init(struct ptlrpc_request *req,
3106                           struct mdt_thread_info *info)
3107 {
3108         int i;
3109
3110         info->mti_pill = &req->rq_pill;
3111
3112         /* lock handle */
3113         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
3114                 mdt_lock_handle_init(&info->mti_lh[i]);
3115
3116         /* mdt device: it can be NULL while CONNECT */
3117         if (req->rq_export) {
3118                 info->mti_mdt = mdt_dev(req->rq_export->exp_obd->obd_lu_dev);
3119                 info->mti_exp = req->rq_export;
3120         } else
3121                 info->mti_mdt = NULL;
3122         info->mti_env = req->rq_svc_thread->t_env;
3123         info->mti_fail_id = OBD_FAIL_MDS_ALL_REPLY_NET;
3124         info->mti_transno = lustre_msg_get_transno(req->rq_reqmsg);
3125         info->mti_mos = NULL;
3126
3127         memset(&info->mti_attr, 0, sizeof(info->mti_attr));
3128         info->mti_big_buf = LU_BUF_NULL;
3129         info->mti_body = NULL;
3130         info->mti_object = NULL;
3131         info->mti_dlm_req = NULL;
3132         info->mti_has_trans = 0;
3133         info->mti_cross_ref = 0;
3134         info->mti_opdata = 0;
3135         info->mti_big_lmm_used = 0;
3136
3137         /* To not check for split by default. */
3138         info->mti_spec.no_create = 0;
3139         info->mti_spec.sp_rm_entry = 0;
3140 }
3141
3142 void mdt_thread_info_fini(struct mdt_thread_info *info)
3143 {
3144         int i;
3145
3146         if (info->mti_object != NULL) {
3147                 mdt_object_put(info->mti_env, info->mti_object);
3148                 info->mti_object = NULL;
3149         }
3150
3151         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
3152                 mdt_lock_handle_fini(&info->mti_lh[i]);
3153         info->mti_env = NULL;
3154         info->mti_pill = NULL;
3155         info->mti_exp = NULL;
3156
3157         if (unlikely(info->mti_big_buf.lb_buf != NULL))
3158                 lu_buf_free(&info->mti_big_buf);
3159 }
3160
3161 int mdt_tgt_connect(struct tgt_session_info *tsi)
3162 {
3163         struct ptlrpc_request   *req = tgt_ses_req(tsi);
3164         struct mdt_thread_info  *mti;
3165         int                      rc;
3166
3167         ENTRY;
3168
3169         rc = tgt_connect(tsi);
3170         if (rc != 0)
3171                 RETURN(rc);
3172
3173         /* XXX: switch mdt_init_idmap() to use tgt_session_info */
3174         lu_env_refill((void *)tsi->tsi_env);
3175         mti = lu_context_key_get(&tsi->tsi_env->le_ctx, &mdt_thread_key);
3176         LASSERT(mti != NULL);
3177
3178         mdt_thread_info_init(req, mti);
3179         rc = mdt_init_idmap(mti);
3180         mdt_thread_info_fini(mti);
3181         if (rc != 0)
3182                 GOTO(err, rc);
3183         RETURN(0);
3184 err:
3185         obd_disconnect(class_export_get(req->rq_export));
3186         return rc;
3187 }
3188
3189 static int mdt_filter_recovery_request(struct ptlrpc_request *req,
3190                                        struct obd_device *obd, int *process)
3191 {
3192         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
3193         case MDS_CONNECT: /* This will never get here, but for completeness. */
3194         case OST_CONNECT: /* This will never get here, but for completeness. */
3195         case MDS_DISCONNECT:
3196         case OST_DISCONNECT:
3197         case OBD_IDX_READ:
3198                *process = 1;
3199                RETURN(0);
3200
3201         case MDS_CLOSE:
3202         case MDS_DONE_WRITING:
3203         case MDS_SYNC: /* used in unmounting */
3204         case OBD_PING:
3205         case MDS_REINT:
3206         case UPDATE_OBJ:
3207         case SEQ_QUERY:
3208         case FLD_QUERY:
3209         case LDLM_ENQUEUE:
3210                 *process = target_queue_recovery_request(req, obd);
3211                 RETURN(0);
3212
3213         default:
3214                 DEBUG_REQ(D_ERROR, req, "not permitted during recovery");
3215                 *process = -EAGAIN;
3216                 RETURN(0);
3217         }
3218 }
3219
3220 /*
3221  * Handle recovery. Return:
3222  *        +1: continue request processing;
3223  *       -ve: abort immediately with the given error code;
3224  *         0: send reply with error code in req->rq_status;
3225  */
3226 static int mdt_recovery(struct mdt_thread_info *info)
3227 {
3228         struct ptlrpc_request *req = mdt_info_req(info);
3229         struct obd_device *obd;
3230
3231         ENTRY;
3232
3233         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
3234         case MDS_CONNECT:
3235         case SEC_CTX_INIT:
3236         case SEC_CTX_INIT_CONT:
3237         case SEC_CTX_FINI:
3238                 {
3239 #if 0
3240                         int rc;
3241
3242                         rc = mdt_handle_idmap(info);
3243                         if (rc)
3244                                 RETURN(rc);
3245                         else
3246 #endif
3247                                 RETURN(+1);
3248                 }
3249         }
3250
3251         if (unlikely(!class_connected_export(req->rq_export))) {
3252                 CDEBUG(D_HA, "operation %d on unconnected MDS from %s\n",
3253                        lustre_msg_get_opc(req->rq_reqmsg),
3254                        libcfs_id2str(req->rq_peer));
3255                 /* FIXME: For CMD cleanup, when mds_B stop, the req from
3256                  * mds_A will get -ENOTCONN(especially for ping req),
3257                  * which will cause that mds_A deactive timeout, then when
3258                  * mds_A cleanup, the cleanup process will be suspended since
3259                  * deactive timeout is not zero.
3260                  */
3261                 req->rq_status = -ENOTCONN;
3262                 target_send_reply(req, -ENOTCONN, info->mti_fail_id);
3263                 RETURN(0);
3264         }
3265
3266         /* sanity check: if the xid matches, the request must be marked as a
3267          * resent or replayed */
3268         if (req_xid_is_last(req)) {
3269                 if (!(lustre_msg_get_flags(req->rq_reqmsg) &
3270                       (MSG_RESENT | MSG_REPLAY))) {
3271                         DEBUG_REQ(D_WARNING, req, "rq_xid "LPU64" matches last_xid, "
3272                                   "expected REPLAY or RESENT flag (%x)", req->rq_xid,
3273                                   lustre_msg_get_flags(req->rq_reqmsg));
3274                         LBUG();
3275                         req->rq_status = -ENOTCONN;
3276                         RETURN(-ENOTCONN);
3277                 }
3278         }
3279
3280         /* else: note the opposite is not always true; a RESENT req after a
3281          * failover will usually not match the last_xid, since it was likely
3282          * never committed. A REPLAYed request will almost never match the
3283          * last xid, however it could for a committed, but still retained,
3284          * open. */
3285
3286         obd = req->rq_export->exp_obd;
3287
3288         /* Check for aborted recovery... */
3289         if (unlikely(obd->obd_recovering)) {
3290                 int rc;
3291                 int should_process;
3292                 DEBUG_REQ(D_INFO, req, "Got new replay");
3293                 rc = mdt_filter_recovery_request(req, obd, &should_process);
3294                 if (rc != 0 || !should_process)
3295                         RETURN(rc);
3296                 else if (should_process < 0) {
3297                         req->rq_status = should_process;
3298                         rc = ptlrpc_error(req);
3299                         RETURN(rc);
3300                 }
3301         }
3302         RETURN(+1);
3303 }
3304
3305 static int mdt_msg_check_version(struct lustre_msg *msg)
3306 {
3307         int rc;
3308
3309         switch (lustre_msg_get_opc(msg)) {
3310         case MDS_CONNECT:
3311         case MDS_DISCONNECT:
3312         case OBD_PING:
3313         case SEC_CTX_INIT:
3314         case SEC_CTX_INIT_CONT:
3315         case SEC_CTX_FINI:
3316         case OBD_IDX_READ:
3317                 rc = lustre_msg_check_version(msg, LUSTRE_OBD_VERSION);
3318                 if (rc)
3319                         CERROR("bad opc %u version %08x, expecting %08x\n",
3320                                lustre_msg_get_opc(msg),
3321                                lustre_msg_get_version(msg),
3322                                LUSTRE_OBD_VERSION);
3323                 break;
3324         case MDS_GETSTATUS:
3325         case MDS_GETATTR:
3326         case MDS_GETATTR_NAME:
3327         case MDS_STATFS:
3328         case MDS_READPAGE:
3329         case MDS_WRITEPAGE:
3330         case MDS_IS_SUBDIR:
3331         case MDS_REINT:
3332         case MDS_CLOSE:
3333         case MDS_DONE_WRITING:
3334         case MDS_PIN:
3335         case MDS_SYNC:
3336         case MDS_GETXATTR:
3337         case MDS_SETXATTR:
3338         case MDS_SET_INFO:
3339         case MDS_GET_INFO:
3340         case MDS_HSM_PROGRESS:
3341         case MDS_HSM_REQUEST:
3342         case MDS_HSM_CT_REGISTER:
3343         case MDS_HSM_CT_UNREGISTER:
3344         case MDS_HSM_STATE_GET:
3345         case MDS_HSM_STATE_SET:
3346         case MDS_HSM_ACTION:
3347         case MDS_QUOTACHECK:
3348         case MDS_QUOTACTL:
3349         case UPDATE_OBJ:
3350         case MDS_SWAP_LAYOUTS:
3351         case QUOTA_DQACQ:
3352         case QUOTA_DQREL:
3353         case SEQ_QUERY:
3354         case FLD_QUERY:
3355                 rc = lustre_msg_check_version(msg, LUSTRE_MDS_VERSION);
3356                 if (rc)
3357                         CERROR("bad opc %u version %08x, expecting %08x\n",
3358                                lustre_msg_get_opc(msg),
3359                                lustre_msg_get_version(msg),
3360                                LUSTRE_MDS_VERSION);
3361                 break;
3362         case LDLM_ENQUEUE:
3363         case LDLM_CONVERT:
3364         case LDLM_BL_CALLBACK:
3365         case LDLM_CP_CALLBACK:
3366                 rc = lustre_msg_check_version(msg, LUSTRE_DLM_VERSION);
3367                 if (rc)
3368                         CERROR("bad opc %u version %08x, expecting %08x\n",
3369                                lustre_msg_get_opc(msg),
3370                                lustre_msg_get_version(msg),
3371                                LUSTRE_DLM_VERSION);
3372                 break;
3373         case OBD_LOG_CANCEL:
3374         case LLOG_ORIGIN_HANDLE_CREATE:
3375         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
3376         case LLOG_ORIGIN_HANDLE_READ_HEADER:
3377         case LLOG_ORIGIN_HANDLE_CLOSE:
3378         case LLOG_ORIGIN_HANDLE_DESTROY:
3379         case LLOG_ORIGIN_HANDLE_PREV_BLOCK:
3380         case LLOG_CATINFO:
3381                 rc = lustre_msg_check_version(msg, LUSTRE_LOG_VERSION);
3382                 if (rc)
3383                         CERROR("bad opc %u version %08x, expecting %08x\n",
3384                                lustre_msg_get_opc(msg),
3385                                lustre_msg_get_version(msg),
3386                                LUSTRE_LOG_VERSION);
3387                 break;
3388         default:
3389                 CERROR("MDS unknown opcode %d\n", lustre_msg_get_opc(msg));
3390                 rc = -ENOTSUPP;
3391         }
3392         return rc;
3393 }
3394
3395 static int mdt_handle0(struct ptlrpc_request *req,
3396                        struct mdt_thread_info *info,
3397                        struct mdt_opc_slice *supported)
3398 {
3399         struct mdt_handler *h;
3400         struct lustre_msg  *msg;
3401         int                 rc;
3402
3403         ENTRY;
3404
3405         if (OBD_FAIL_CHECK_ORSET(OBD_FAIL_MDS_ALL_REQUEST_NET, OBD_FAIL_ONCE))
3406                 RETURN(0);
3407
3408         LASSERT(current->journal_info == NULL);
3409
3410         msg = req->rq_reqmsg;
3411         rc = mdt_msg_check_version(msg);
3412         if (likely(rc == 0)) {
3413                 rc = mdt_recovery(info);
3414                 if (likely(rc == +1)) {
3415                         h = mdt_handler_find(lustre_msg_get_opc(msg),
3416                                              supported);
3417                         if (likely(h != NULL)) {
3418                                 rc = mdt_req_handle(info, h, req);
3419                         } else {
3420                                 CERROR("%s: opc unsupported: 0x%x\n",
3421                                         mdt_obd_name(info->mti_mdt),
3422                                         lustre_msg_get_opc(msg));
3423                                 req->rq_status = -ENOTSUPP;
3424                                 rc = ptlrpc_error(req);
3425                                 RETURN(rc);
3426                         }
3427                 }
3428         } else {
3429                 CDEBUG(D_INFO, "%s: drops mal-formed request: rc = %d\n",
3430                         mdt_obd_name(info->mti_mdt), rc);
3431                 req->rq_status = rc;
3432                 rc = ptlrpc_error(req);
3433         }
3434         RETURN(rc);
3435 }
3436
3437 /*
3438  * MDT handler function called by ptlrpc service thread when request comes.
3439  *
3440  * XXX common "target" functionality should be factored into separate module
3441  * shared by mdt, ost and stand-alone services like fld.
3442  */
3443 int mdt_handle_common(struct ptlrpc_request *req,
3444                       struct mdt_opc_slice *supported)
3445 {
3446         struct lu_env          *env;
3447         struct mdt_thread_info *info;
3448         int                     rc;
3449         ENTRY;
3450
3451         env = req->rq_svc_thread->t_env;
3452         /* Refill(initilize) the context(mdt_thread_info), in case it is
3453          * not initialized yet. Usually it happens during start up, after
3454          * MDS(ptlrpc threads) is start up, it gets the first CONNECT request,
3455          * before MDT_thread_info is initialized */
3456         lu_env_refill(env);
3457         LASSERT(env != NULL);
3458         LASSERT(env->le_ses != NULL);
3459         LASSERT(env->le_ctx.lc_thread == req->rq_svc_thread);
3460         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
3461         LASSERT(info != NULL);
3462
3463         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
3464         mdt_thread_info_init(req, info);
3465
3466         rc = mdt_handle0(req, info, supported);
3467
3468         mdt_thread_info_fini(info);
3469         req_capsule_fini(&req->rq_pill);
3470         RETURN(rc);
3471 }
3472
3473 /*
3474  * This is called from recovery code as handler of _all_ RPC types, FLD and SEQ
3475  * as well.
3476  */
3477 int mdt_recovery_handle(struct ptlrpc_request *req)
3478 {
3479         int rc;
3480
3481         ENTRY;
3482
3483         rc = mdt_handle_common(req, mdt_regular_handlers);
3484
3485         RETURN(rc);
3486 }
3487
3488 enum mdt_it_code {
3489         MDT_IT_OPEN,
3490         MDT_IT_OCREAT,
3491         MDT_IT_CREATE,
3492         MDT_IT_GETATTR,
3493         MDT_IT_READDIR,
3494         MDT_IT_LOOKUP,
3495         MDT_IT_UNLINK,
3496         MDT_IT_TRUNC,
3497         MDT_IT_GETXATTR,
3498         MDT_IT_LAYOUT,
3499         MDT_IT_QUOTA,
3500         MDT_IT_NR
3501 };
3502
3503 static int mdt_intent_getattr(enum mdt_it_code opcode,
3504                               struct mdt_thread_info *info,
3505                               struct ldlm_lock **,
3506                               __u64);
3507
3508 static int mdt_intent_getxattr(enum mdt_it_code opcode,
3509                                 struct mdt_thread_info *info,
3510                                 struct ldlm_lock **lockp,
3511                                 __u64 flags);
3512
3513 static int mdt_intent_layout(enum mdt_it_code opcode,
3514                              struct mdt_thread_info *info,
3515                              struct ldlm_lock **,
3516                              __u64);
3517 static int mdt_intent_reint(enum mdt_it_code opcode,
3518                             struct mdt_thread_info *info,
3519                             struct ldlm_lock **,
3520                             __u64);
3521
3522 static struct mdt_it_flavor {
3523         const struct req_format *it_fmt;
3524         __u32                    it_flags;
3525         int                    (*it_act)(enum mdt_it_code ,
3526                                          struct mdt_thread_info *,
3527                                          struct ldlm_lock **,
3528                                          __u64);
3529         long                     it_reint;
3530 } mdt_it_flavor[] = {
3531         [MDT_IT_OPEN]     = {
3532                 .it_fmt   = &RQF_LDLM_INTENT,
3533                 /*.it_flags = HABEO_REFERO,*/
3534                 .it_flags = 0,
3535                 .it_act   = mdt_intent_reint,
3536                 .it_reint = REINT_OPEN
3537         },
3538         [MDT_IT_OCREAT]   = {
3539                 .it_fmt   = &RQF_LDLM_INTENT,
3540                 .it_flags = MUTABOR,
3541                 .it_act   = mdt_intent_reint,
3542                 .it_reint = REINT_OPEN
3543         },
3544         [MDT_IT_CREATE]   = {
3545                 .it_fmt   = &RQF_LDLM_INTENT,
3546                 .it_flags = MUTABOR,
3547                 .it_act   = mdt_intent_reint,
3548                 .it_reint = REINT_CREATE
3549         },
3550         [MDT_IT_GETATTR]  = {
3551                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3552                 .it_flags = HABEO_REFERO,
3553                 .it_act   = mdt_intent_getattr
3554         },
3555         [MDT_IT_READDIR]  = {
3556                 .it_fmt   = NULL,
3557                 .it_flags = 0,
3558                 .it_act   = NULL
3559         },
3560         [MDT_IT_LOOKUP]   = {
3561                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3562                 .it_flags = HABEO_REFERO,
3563                 .it_act   = mdt_intent_getattr
3564         },
3565         [MDT_IT_UNLINK]   = {
3566                 .it_fmt   = &RQF_LDLM_INTENT_UNLINK,
3567                 .it_flags = MUTABOR,
3568                 .it_act   = NULL,
3569                 .it_reint = REINT_UNLINK
3570         },
3571         [MDT_IT_TRUNC]    = {
3572                 .it_fmt   = NULL,
3573                 .it_flags = MUTABOR,
3574                 .it_act   = NULL
3575         },
3576         [MDT_IT_GETXATTR] = {
3577                 .it_fmt   = &RQF_LDLM_INTENT_GETXATTR,
3578                 .it_flags = HABEO_CORPUS,
3579                 .it_act   = mdt_intent_getxattr
3580         },
3581         [MDT_IT_LAYOUT] = {
3582                 .it_fmt   = &RQF_LDLM_INTENT_LAYOUT,
3583                 .it_flags = 0,
3584                 .it_act   = mdt_intent_layout
3585         }
3586 };
3587
3588 int mdt_intent_lock_replace(struct mdt_thread_info *info,
3589                             struct ldlm_lock **lockp,
3590                             struct ldlm_lock *new_lock,
3591                             struct mdt_lock_handle *lh,
3592                             __u64 flags)
3593 {
3594         struct ptlrpc_request  *req = mdt_info_req(info);
3595         struct ldlm_lock       *lock = *lockp;
3596
3597         /*
3598          * Get new lock only for cases when possible resent did not find any
3599          * lock.
3600          */
3601         if (new_lock == NULL)
3602                 new_lock = ldlm_handle2lock_long(&lh->mlh_reg_lh, 0);
3603
3604         if (new_lock == NULL && (flags & LDLM_FL_INTENT_ONLY)) {
3605                 lh->mlh_reg_lh.cookie = 0;
3606                 RETURN(0);
3607         }
3608
3609         LASSERTF(new_lock != NULL,
3610                  "lockh "LPX64"\n", lh->mlh_reg_lh.cookie);
3611
3612         /*
3613          * If we've already given this lock to a client once, then we should
3614          * have no readers or writers.  Otherwise, we should have one reader
3615          * _or_ writer ref (which will be zeroed below) before returning the
3616          * lock to a client.
3617          */
3618         if (new_lock->l_export == req->rq_export) {
3619                 LASSERT(new_lock->l_readers + new_lock->l_writers == 0);
3620         } else {
3621                 LASSERT(new_lock->l_export == NULL);
3622                 LASSERT(new_lock->l_readers + new_lock->l_writers == 1);
3623         }
3624
3625         *lockp = new_lock;
3626
3627         if (new_lock->l_export == req->rq_export) {
3628                 /*
3629                  * Already gave this to the client, which means that we
3630                  * reconstructed a reply.
3631                  */
3632                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) &
3633                         MSG_RESENT);
3634                 lh->mlh_reg_lh.cookie = 0;
3635                 RETURN(ELDLM_LOCK_REPLACED);
3636         }
3637
3638         /*
3639          * Fixup the lock to be given to the client.
3640          */
3641         lock_res_and_lock(new_lock);
3642         /* Zero new_lock->l_readers and new_lock->l_writers without triggering
3643          * possible blocking AST. */
3644         while (new_lock->l_readers > 0) {
3645                 lu_ref_del(&new_lock->l_reference, "reader", new_lock);
3646                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3647                 new_lock->l_readers--;
3648         }
3649         while (new_lock->l_writers > 0) {
3650                 lu_ref_del(&new_lock->l_reference, "writer", new_lock);
3651                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3652                 new_lock->l_writers--;
3653         }
3654
3655         new_lock->l_export = class_export_lock_get(req->rq_export, new_lock);
3656         new_lock->l_blocking_ast = lock->l_blocking_ast;
3657         new_lock->l_completion_ast = lock->l_completion_ast;
3658         new_lock->l_remote_handle = lock->l_remote_handle;
3659         new_lock->l_flags &= ~LDLM_FL_LOCAL;
3660
3661         unlock_res_and_lock(new_lock);
3662
3663         cfs_hash_add(new_lock->l_export->exp_lock_hash,
3664                      &new_lock->l_remote_handle,
3665                      &new_lock->l_exp_hash);
3666
3667         LDLM_LOCK_RELEASE(new_lock);
3668         lh->mlh_reg_lh.cookie = 0;
3669
3670         RETURN(ELDLM_LOCK_REPLACED);
3671 }
3672
3673 static void mdt_intent_fixup_resent(struct mdt_thread_info *info,
3674                                     struct ldlm_lock *new_lock,
3675                                     struct ldlm_lock **old_lock,
3676                                     struct mdt_lock_handle *lh)
3677 {
3678         struct ptlrpc_request  *req = mdt_info_req(info);
3679         struct obd_export      *exp = req->rq_export;
3680         struct lustre_handle    remote_hdl;
3681         struct ldlm_request    *dlmreq;
3682         struct ldlm_lock       *lock;
3683
3684         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT))
3685                 return;
3686
3687         dlmreq = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
3688         remote_hdl = dlmreq->lock_handle[0];
3689
3690         /* In the function below, .hs_keycmp resolves to
3691          * ldlm_export_lock_keycmp() */
3692         /* coverity[overrun-buffer-val] */
3693         lock = cfs_hash_lookup(exp->exp_lock_hash, &remote_hdl);
3694         if (lock) {
3695                 if (lock != new_lock) {
3696                         lh->mlh_reg_lh.cookie = lock->l_handle.h_cookie;
3697                         lh->mlh_reg_mode = lock->l_granted_mode;
3698
3699                         LDLM_DEBUG(lock, "Restoring lock cookie");
3700                         DEBUG_REQ(D_DLMTRACE, req,
3701                                   "restoring lock cookie "LPX64,
3702                                   lh->mlh_reg_lh.cookie);
3703                         if (old_lock)
3704                                 *old_lock = LDLM_LOCK_GET(lock);
3705                         cfs_hash_put(exp->exp_lock_hash, &lock->l_exp_hash);
3706                         return;
3707                 }
3708
3709                 cfs_hash_put(exp->exp_lock_hash, &lock->l_exp_hash);
3710         }
3711
3712         /*
3713          * If the xid matches, then we know this is a resent request, and allow
3714          * it. (It's probably an OPEN, for which we don't send a lock.
3715          */
3716         if (req_xid_is_last(req))
3717                 return;
3718
3719         /*
3720          * This remote handle isn't enqueued, so we never received or processed
3721          * this request.  Clear MSG_RESENT, because it can be handled like any
3722          * normal request now.
3723          */
3724         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
3725
3726         DEBUG_REQ(D_DLMTRACE, req, "no existing lock with rhandle "LPX64,
3727                   remote_hdl.cookie);
3728 }
3729
3730 static int mdt_intent_getxattr(enum mdt_it_code opcode,
3731                                 struct mdt_thread_info *info,
3732                                 struct ldlm_lock **lockp,
3733                                 __u64 flags)
3734 {
3735         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3736         struct ldlm_reply      *ldlm_rep = NULL;
3737         int rc, grc;
3738
3739         /*
3740          * Initialize lhc->mlh_reg_lh either from a previously granted lock
3741          * (for the resend case) or a new lock. Below we will use it to
3742          * replace the original lock.
3743          */
3744         mdt_intent_fixup_resent(info, *lockp, NULL, lhc);
3745         if (!lustre_handle_is_used(&lhc->mlh_reg_lh)) {
3746                 mdt_lock_reg_init(lhc, (*lockp)->l_req_mode);
3747                 rc = mdt_object_lock(info, info->mti_object, lhc,
3748                                         MDS_INODELOCK_XATTR,
3749                                         MDT_LOCAL_LOCK);
3750                 if (rc)
3751                         return rc;
3752         }
3753
3754         grc = mdt_getxattr(info);
3755
3756         rc = mdt_intent_lock_replace(info, lockp, NULL, lhc, flags);
3757
3758         if (mdt_info_req(info)->rq_repmsg != NULL)
3759                 ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3760         if (ldlm_rep == NULL)
3761                 RETURN(err_serious(-EFAULT));
3762
3763         ldlm_rep->lock_policy_res2 = grc;
3764
3765         return rc;
3766 }
3767
3768 static int mdt_intent_getattr(enum mdt_it_code opcode,
3769                               struct mdt_thread_info *info,
3770                               struct ldlm_lock **lockp,
3771                               __u64 flags)
3772 {
3773         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3774         struct ldlm_lock       *new_lock = NULL;
3775         __u64                   child_bits;
3776         struct ldlm_reply      *ldlm_rep;
3777         struct ptlrpc_request  *req;
3778         struct mdt_body        *reqbody;
3779         struct mdt_body        *repbody;
3780         int                     rc, rc2;
3781         ENTRY;
3782
3783         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
3784         LASSERT(reqbody);
3785
3786         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
3787         LASSERT(repbody);
3788
3789         info->mti_cross_ref = !!(reqbody->valid & OBD_MD_FLCROSSREF);
3790         repbody->eadatasize = 0;
3791         repbody->aclsize = 0;
3792
3793         switch (opcode) {
3794         case MDT_IT_LOOKUP:
3795                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_PERM;
3796                 break;
3797         case MDT_IT_GETATTR:
3798                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE |
3799                              MDS_INODELOCK_PERM;
3800                 break;
3801         default:
3802                 CERROR("Unsupported intent (%d)\n", opcode);
3803                 GOTO(out_shrink, rc = -EINVAL);
3804         }
3805
3806         rc = mdt_init_ucred(info, reqbody);
3807         if (rc)
3808                 GOTO(out_shrink, rc);
3809
3810         req = info->mti_pill->rc_req;
3811         ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3812         mdt_set_disposition(info, ldlm_rep, DISP_IT_EXECD);
3813
3814         /* Get lock from request for possible resent case. */
3815         mdt_intent_fixup_resent(info, *lockp, &new_lock, lhc);
3816
3817         rc = mdt_getattr_name_lock(info, lhc, child_bits, ldlm_rep);
3818         ldlm_rep->lock_policy_res2 = clear_serious(rc);
3819
3820         if (mdt_get_disposition(ldlm_rep, DISP_LOOKUP_NEG))
3821                 ldlm_rep->lock_policy_res2 = 0;
3822         if (!mdt_get_disposition(ldlm_rep, DISP_LOOKUP_POS) ||
3823             ldlm_rep->lock_policy_res2) {
3824                 lhc->mlh_reg_lh.cookie = 0ull;
3825                 GOTO(out_ucred, rc = ELDLM_LOCK_ABORTED);
3826         }
3827
3828         rc = mdt_intent_lock_replace(info, lockp, new_lock, lhc, flags);
3829         EXIT;
3830 out_ucred:
3831         mdt_exit_ucred(info);
3832 out_shrink:
3833         mdt_client_compatibility(info);
3834         rc2 = mdt_fix_reply(info);
3835         if (rc == 0)
3836                 rc = rc2;
3837         return rc;
3838 }
3839
3840 static int mdt_intent_layout(enum mdt_it_code opcode,
3841                              struct mdt_thread_info *info,
3842                              struct ldlm_lock **lockp,
3843                              __u64 flags)
3844 {
3845         struct layout_intent *layout;
3846         struct lu_fid *fid;
3847         struct mdt_object *obj = NULL;
3848         struct md_object *child = NULL;
3849         int rc;
3850         ENTRY;
3851
3852         if (opcode != MDT_IT_LAYOUT) {
3853                 CERROR("%s: Unknown intent (%d)\n", mdt_obd_name(info->mti_mdt),
3854                         opcode);
3855                 RETURN(-EINVAL);
3856         }
3857
3858         fid = &info->mti_tmp_fid2;
3859         fid_extract_from_res_name(fid, &(*lockp)->l_resource->lr_name);
3860
3861         obj = mdt_object_find(info->mti_env, info->mti_mdt, fid);
3862         if (IS_ERR(obj))
3863                 RETURN(PTR_ERR(obj));
3864
3865         if (mdt_object_exists(obj) && !mdt_object_remote(obj)) {
3866                 child = mdt_object_child(obj);
3867
3868                 /* get the length of lsm */
3869                 rc = mo_xattr_get(info->mti_env, child, &LU_BUF_NULL,
3870                                   XATTR_NAME_LOV);
3871
3872                 if (rc > info->mti_mdt->mdt_max_mdsize)
3873                         info->mti_mdt->mdt_max_mdsize = rc;
3874         }
3875
3876         mdt_object_put(info->mti_env, obj);
3877
3878         (*lockp)->l_lvb_type = LVB_T_LAYOUT;
3879         req_capsule_set_size(info->mti_pill, &RMF_DLM_LVB, RCL_SERVER,
3880                         ldlm_lvbo_size(*lockp));
3881         rc = req_capsule_server_pack(info->mti_pill);
3882         if (rc != 0)
3883                 RETURN(-EINVAL);
3884
3885         layout = req_capsule_client_get(info->mti_pill, &RMF_LAYOUT_INTENT);
3886         LASSERT(layout != NULL);
3887         if (layout->li_opc == LAYOUT_INTENT_ACCESS)
3888                 /* return to normal ldlm handling */
3889                 RETURN(0);
3890
3891         CERROR("%s: Unsupported layout intent (%d)\n",
3892                 mdt_obd_name(info->mti_mdt), layout->li_opc);
3893         RETURN(-EINVAL);
3894 }
3895
3896 static int mdt_intent_reint(enum mdt_it_code opcode,
3897                             struct mdt_thread_info *info,
3898                             struct ldlm_lock **lockp,
3899                             __u64 flags)
3900 {
3901         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3902         struct ldlm_reply      *rep = NULL;
3903         long                    opc;
3904         int                     rc;
3905
3906         static const struct req_format *intent_fmts[REINT_MAX] = {
3907                 [REINT_CREATE]  = &RQF_LDLM_INTENT_CREATE,
3908                 [REINT_OPEN]    = &RQF_LDLM_INTENT_OPEN
3909         };
3910
3911         ENTRY;
3912
3913         opc = mdt_reint_opcode(info, intent_fmts);
3914         if (opc < 0)
3915                 RETURN(opc);
3916
3917         if (mdt_it_flavor[opcode].it_reint != opc) {
3918                 CERROR("Reint code %ld doesn't match intent: %d\n",
3919                        opc, opcode);
3920                 RETURN(err_serious(-EPROTO));
3921         }
3922
3923         /* Get lock from request for possible resent case. */
3924         mdt_intent_fixup_resent(info, *lockp, NULL, lhc);
3925
3926         rc = mdt_reint_internal(info, lhc, opc);
3927
3928         /* Check whether the reply has been packed successfully. */
3929         if (mdt_info_req(info)->rq_repmsg != NULL)
3930                 rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3931         if (rep == NULL)
3932                 RETURN(err_serious(-EFAULT));
3933
3934         /* MDC expects this in any case */
3935         if (rc != 0)
3936                 mdt_set_disposition(info, rep, DISP_LOOKUP_EXECD);
3937
3938         /* the open lock or the lock for cross-ref object should be
3939          * returned to the client */
3940         if (rc == -EREMOTE || mdt_get_disposition(rep, DISP_OPEN_LOCK)) {
3941                 LASSERT(lustre_handle_is_used(&lhc->mlh_reg_lh));
3942                 rep->lock_policy_res2 = 0;
3943                 rc = mdt_intent_lock_replace(info, lockp, NULL, lhc, flags);
3944                 RETURN(rc);
3945         }
3946
3947         rep->lock_policy_res2 = clear_serious(rc);
3948
3949         if (rep->lock_policy_res2 == -ENOENT &&
3950             mdt_get_disposition(rep, DISP_LOOKUP_NEG))
3951                 rep->lock_policy_res2 = 0;
3952
3953         if (rc == -ENOTCONN || rc == -ENODEV ||
3954             rc == -EOVERFLOW) { /**< if VBR failure then return error */
3955                 /*
3956                  * If it is the disconnect error (ENODEV & ENOCONN), the error
3957                  * will be returned by rq_status, and client at ptlrpc layer
3958                  * will detect this, then disconnect, reconnect the import
3959                  * immediately, instead of impacting the following the rpc.
3960                  */
3961                 lhc->mlh_reg_lh.cookie = 0ull;
3962                 RETURN(rc);
3963         } else {
3964                 /*
3965                  * For other cases, the error will be returned by intent.
3966                  * and client will retrieve the result from intent.
3967                  */
3968                  /*
3969                   * FIXME: when open lock is finished, that should be
3970                   * checked here.
3971                   */
3972                 if (lustre_handle_is_used(&lhc->mlh_reg_lh)) {
3973                         LASSERTF(rc == 0, "Error occurred but lock handle "
3974                                  "is still in use, rc = %d\n", rc);
3975                         rep->lock_policy_res2 = 0;
3976                         rc = mdt_intent_lock_replace(info, lockp, NULL, lhc, flags);
3977                         RETURN(rc);
3978                 } else {
3979                         lhc->mlh_reg_lh.cookie = 0ull;
3980                         RETURN(ELDLM_LOCK_ABORTED);
3981                 }
3982         }
3983 }
3984
3985 static int mdt_intent_code(long itcode)
3986 {
3987         int rc;
3988
3989         switch(itcode) {
3990         case IT_OPEN:
3991                 rc = MDT_IT_OPEN;
3992                 break;
3993         case IT_OPEN|IT_CREAT:
3994                 rc = MDT_IT_OCREAT;
3995                 break;
3996         case IT_CREAT:
3997                 rc = MDT_IT_CREATE;
3998                 break;
3999         case IT_READDIR:
4000                 rc = MDT_IT_READDIR;
4001                 break;
4002         case IT_GETATTR:
4003                 rc = MDT_IT_GETATTR;
4004                 break;
4005         case IT_LOOKUP:
4006                 rc = MDT_IT_LOOKUP;
4007                 break;
4008         case IT_UNLINK:
4009                 rc = MDT_IT_UNLINK;
4010                 break;
4011         case IT_TRUNC:
4012                 rc = MDT_IT_TRUNC;
4013                 break;
4014         case IT_GETXATTR:
4015                 rc = MDT_IT_GETXATTR;
4016                 break;
4017         case IT_LAYOUT:
4018                 rc = MDT_IT_LAYOUT;
4019                 break;
4020         case IT_QUOTA_DQACQ:
4021         case IT_QUOTA_CONN:
4022                 rc = MDT_IT_QUOTA;
4023                 break;
4024         default:
4025                 CERROR("Unknown intent opcode: %ld\n", itcode);
4026                 rc = -EINVAL;
4027                 break;
4028         }
4029         return rc;
4030 }
4031
4032 static int mdt_intent_opc(long itopc, struct mdt_thread_info *info,
4033                           struct ldlm_lock **lockp, __u64 flags)
4034 {
4035         struct req_capsule   *pill;
4036         struct mdt_it_flavor *flv;
4037         int opc;
4038         int rc;
4039         ENTRY;
4040
4041         opc = mdt_intent_code(itopc);
4042         if (opc < 0)
4043                 RETURN(-EINVAL);
4044
4045         pill = info->mti_pill;
4046
4047         if (opc == MDT_IT_QUOTA) {
4048                 struct lu_device *qmt = info->mti_mdt->mdt_qmt_dev;
4049
4050                 if (qmt == NULL)
4051                         RETURN(-EOPNOTSUPP);
4052
4053                 (*lockp)->l_lvb_type = LVB_T_LQUOTA;
4054                 /* pass the request to quota master */
4055                 rc = qmt_hdls.qmth_intent_policy(info->mti_env, qmt,
4056                                                  mdt_info_req(info), lockp,
4057                                                  flags);
4058                 RETURN(rc);
4059         }
4060
4061         flv  = &mdt_it_flavor[opc];
4062         if (flv->it_fmt != NULL)
4063                 req_capsule_extend(pill, flv->it_fmt);
4064
4065         rc = mdt_unpack_req_pack_rep(info, flv->it_flags);
4066         if (rc == 0) {
4067                 struct ptlrpc_request *req = mdt_info_req(info);
4068                 if (flv->it_flags & MUTABOR &&
4069                     exp_connect_flags(req->rq_export) & OBD_CONNECT_RDONLY)
4070                         RETURN(-EROFS);
4071         }
4072         if (rc == 0 && flv->it_act != NULL) {
4073                 struct ldlm_reply *rep;
4074
4075                 /* execute policy */
4076                 rc = flv->it_act(opc, info, lockp, flags);
4077
4078                 /* Check whether the reply has been packed successfully. */
4079                 if (mdt_info_req(info)->rq_repmsg != NULL) {
4080                         rep = req_capsule_server_get(info->mti_pill,
4081                                                      &RMF_DLM_REP);
4082                         rep->lock_policy_res2 =
4083                                 ptlrpc_status_hton(rep->lock_policy_res2);
4084                 }
4085         } else {
4086                 rc = -EOPNOTSUPP;
4087         }
4088         RETURN(rc);
4089 }
4090
4091 static int mdt_intent_policy(struct ldlm_namespace *ns,
4092                              struct ldlm_lock **lockp, void *req_cookie,
4093                              ldlm_mode_t mode, __u64 flags, void *data)
4094 {
4095         struct mdt_thread_info *info;
4096         struct ptlrpc_request  *req  =  req_cookie;
4097         struct ldlm_intent     *it;
4098         struct req_capsule     *pill;
4099         int rc;
4100
4101         ENTRY;
4102
4103         LASSERT(req != NULL);
4104
4105         info = lu_context_key_get(&req->rq_svc_thread->t_env->le_ctx,
4106                                   &mdt_thread_key);
4107         LASSERT(info != NULL);
4108         pill = info->mti_pill;
4109         LASSERT(pill->rc_req == req);
4110
4111         if (req->rq_reqmsg->lm_bufcount > DLM_INTENT_IT_OFF) {
4112                 req_capsule_extend(pill, &RQF_LDLM_INTENT_BASIC);
4113                 it = req_capsule_client_get(pill, &RMF_LDLM_INTENT);
4114                 if (it != NULL) {
4115                         rc = mdt_intent_opc(it->opc, info, lockp, flags);
4116                         if (rc == 0)
4117                                 rc = ELDLM_OK;
4118
4119                         /* Lock without inodebits makes no sense and will oops
4120                          * later in ldlm. Let's check it now to see if we have
4121                          * ibits corrupted somewhere in mdt_intent_opc().
4122                          * The case for client miss to set ibits has been
4123                          * processed by others. */
4124                         LASSERT(ergo(info->mti_dlm_req->lock_desc.l_resource.\
4125                                         lr_type == LDLM_IBITS,
4126                                      info->mti_dlm_req->lock_desc.\
4127                                         l_policy_data.l_inodebits.bits != 0));
4128                 } else
4129                         rc = err_serious(-EFAULT);
4130         } else {
4131                 /* No intent was provided */
4132                 LASSERT(pill->rc_fmt == &RQF_LDLM_ENQUEUE);
4133                 req_capsule_set_size(pill, &RMF_DLM_LVB, RCL_SERVER, 0);
4134                 rc = req_capsule_server_pack(pill);
4135                 if (rc)
4136                         rc = err_serious(rc);
4137         }
4138         RETURN(rc);
4139 }
4140
4141 static int mdt_seq_fini(const struct lu_env *env,
4142                         struct mdt_device *m)
4143 {
4144         return seq_site_fini(env, mdt_seq_site(m));
4145 }
4146
4147 static int mdt_seq_init(const struct lu_env *env,
4148                         const char *uuid,
4149                         struct mdt_device *m)
4150 {
4151         struct seq_server_site *ss;
4152         char *prefix;
4153         int rc;
4154         ENTRY;
4155
4156         ss = mdt_seq_site(m);
4157
4158         /*
4159          * This is sequence-controller node. Init seq-controller server on local
4160          * MDT.
4161          */
4162         if (ss->ss_node_id == 0) {
4163                 LASSERT(ss->ss_control_seq == NULL);
4164
4165                 OBD_ALLOC_PTR(ss->ss_control_seq);
4166                 if (ss->ss_control_seq == NULL)
4167                         RETURN(-ENOMEM);
4168
4169                 rc = seq_server_init(ss->ss_control_seq,
4170                                      m->mdt_bottom, uuid,
4171                                      LUSTRE_SEQ_CONTROLLER,
4172                                      ss,
4173                                      env);
4174
4175                 if (rc)
4176                         GOTO(out_seq_fini, rc);
4177
4178                 OBD_ALLOC_PTR(ss->ss_client_seq);
4179                 if (ss->ss_client_seq == NULL)
4180                         GOTO(out_seq_fini, rc = -ENOMEM);
4181
4182                 OBD_ALLOC(prefix, MAX_OBD_NAME + 5);
4183                 if (prefix == NULL) {
4184                         OBD_FREE_PTR(ss->ss_client_seq);
4185                         GOTO(out_seq_fini, rc = -ENOMEM);
4186                 }
4187
4188                 snprintf(prefix, MAX_OBD_NAME + 5, "ctl-%s",
4189                          uuid);
4190
4191                 /*
4192                  * Init seq-controller client after seq-controller server is
4193                  * ready. Pass ss->ss_control_seq to it for direct talking.
4194                  */
4195                 rc = seq_client_init(ss->ss_client_seq, NULL,
4196                                      LUSTRE_SEQ_METADATA, prefix,
4197                                      ss->ss_control_seq);
4198                 OBD_FREE(prefix, MAX_OBD_NAME + 5);
4199
4200                 if (rc)
4201                         GOTO(out_seq_fini, rc);
4202         }
4203
4204         /* Init seq-server on local MDT */
4205         LASSERT(ss->ss_server_seq == NULL);
4206
4207         OBD_ALLOC_PTR(ss->ss_server_seq);
4208         if (ss->ss_server_seq == NULL)
4209                 GOTO(out_seq_fini, rc = -ENOMEM);
4210
4211         rc = seq_server_init(ss->ss_server_seq,
4212                              m->mdt_bottom, uuid,
4213                              LUSTRE_SEQ_SERVER,
4214                              ss,
4215                              env);
4216         if (rc)
4217                 GOTO(out_seq_fini, rc = -ENOMEM);
4218
4219         /* Assign seq-controller client to local seq-server. */
4220         if (ss->ss_node_id == 0) {
4221                 LASSERT(ss->ss_client_seq != NULL);
4222
4223                 rc = seq_server_set_cli(ss->ss_server_seq,
4224                                         ss->ss_client_seq,
4225                                         env);
4226         }
4227
4228         EXIT;
4229 out_seq_fini:
4230         if (rc)
4231                 mdt_seq_fini(env, m);
4232
4233         return rc;
4234 }
4235
4236 /*
4237  * FLD wrappers
4238  */
4239 static int mdt_fld_fini(const struct lu_env *env,
4240                         struct mdt_device *m)
4241 {
4242         struct seq_server_site *ss = mdt_seq_site(m);
4243         ENTRY;
4244
4245         if (ss && ss->ss_server_fld) {
4246                 fld_server_fini(env, ss->ss_server_fld);
4247                 OBD_FREE_PTR(ss->ss_server_fld);
4248                 ss->ss_server_fld = NULL;
4249         }
4250
4251         RETURN(0);
4252 }
4253
4254 static int mdt_fld_init(const struct lu_env *env,
4255                         const char *uuid,
4256                         struct mdt_device *m)
4257 {
4258         struct seq_server_site *ss;
4259         int rc;
4260         ENTRY;
4261
4262         ss = mdt_seq_site(m);
4263
4264         OBD_ALLOC_PTR(ss->ss_server_fld);
4265         if (ss->ss_server_fld == NULL)
4266                 RETURN(rc = -ENOMEM);
4267
4268         rc = fld_server_init(env, ss->ss_server_fld, m->mdt_bottom, uuid,
4269                              ss->ss_node_id, LU_SEQ_RANGE_MDT);
4270         if (rc) {
4271                 OBD_FREE_PTR(ss->ss_server_fld);
4272                 ss->ss_server_fld = NULL;
4273                 RETURN(rc);
4274         }
4275
4276         RETURN(0);
4277 }
4278
4279 static void mdt_stack_pre_fini(const struct lu_env *env,
4280                            struct mdt_device *m, struct lu_device *top)
4281 {
4282         struct obd_device       *obd;
4283         struct lustre_cfg_bufs  *bufs;
4284         struct lustre_cfg       *lcfg;
4285         struct mdt_thread_info  *info;
4286         ENTRY;
4287
4288         LASSERT(top);
4289
4290         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4291         LASSERT(info != NULL);
4292
4293         bufs = &info->mti_u.bufs;
4294
4295         LASSERT(m->mdt_child_exp);
4296         LASSERT(m->mdt_child_exp->exp_obd);
4297         obd = m->mdt_child_exp->exp_obd;
4298
4299         /* process cleanup, pass mdt obd name to get obd umount flags */
4300         /* XXX: this is needed because all layers are referenced by
4301          * objects (some of them are pinned by osd, for example *
4302          * the proper solution should be a model where object used
4303          * by osd only doesn't have mdt/mdd slices -bzzz */
4304         lustre_cfg_bufs_reset(bufs, mdt_obd_name(m));
4305         lustre_cfg_bufs_set_string(bufs, 1, NULL);
4306         lcfg = lustre_cfg_new(LCFG_PRE_CLEANUP, bufs);
4307         if (!lcfg) {
4308                 CERROR("%s:Cannot alloc lcfg!\n", mdt_obd_name(m));
4309                 return;
4310         }
4311         top->ld_ops->ldo_process_config(env, top, lcfg);
4312         lustre_cfg_free(lcfg);
4313         EXIT;
4314 }
4315
4316 static void mdt_stack_fini(const struct lu_env *env,
4317                            struct mdt_device *m, struct lu_device *top)
4318 {
4319         struct obd_device       *obd = mdt2obd_dev(m);
4320         struct lustre_cfg_bufs  *bufs;
4321         struct lustre_cfg       *lcfg;
4322         struct mdt_thread_info  *info;
4323         char                     flags[3] = "";
4324         ENTRY;
4325
4326         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4327         LASSERT(info != NULL);
4328
4329         lu_dev_del_linkage(top->ld_site, top);
4330
4331         lu_site_purge(env, top->ld_site, -1);
4332
4333         bufs = &info->mti_u.bufs;
4334         /* process cleanup, pass mdt obd name to get obd umount flags */
4335         /* another purpose is to let all layers to release their objects */
4336         lustre_cfg_bufs_reset(bufs, mdt_obd_name(m));
4337         if (obd->obd_force)
4338                 strcat(flags, "F");
4339         if (obd->obd_fail)
4340                 strcat(flags, "A");
4341         lustre_cfg_bufs_set_string(bufs, 1, flags);
4342         lcfg = lustre_cfg_new(LCFG_CLEANUP, bufs);
4343         if (!lcfg) {
4344                 CERROR("Cannot alloc lcfg!\n");
4345                 return;
4346         }
4347         LASSERT(top);
4348         top->ld_ops->ldo_process_config(env, top, lcfg);
4349         lustre_cfg_free(lcfg);
4350
4351         lu_site_purge(env, top->ld_site, -1);
4352
4353         m->mdt_child = NULL;
4354         m->mdt_bottom = NULL;
4355
4356         obd_disconnect(m->mdt_child_exp);
4357         m->mdt_child_exp = NULL;
4358
4359         obd_disconnect(m->mdt_bottom_exp);
4360         m->mdt_child_exp = NULL;
4361 }
4362
4363 static int mdt_connect_to_next(const struct lu_env *env, struct mdt_device *m,
4364                                const char *next, struct obd_export **exp)
4365 {
4366         struct obd_connect_data *data = NULL;
4367         struct obd_device       *obd;
4368         int                      rc;
4369         ENTRY;
4370
4371         OBD_ALLOC_PTR(data);
4372         if (data == NULL)
4373                 GOTO(out, rc = -ENOMEM);
4374
4375         obd = class_name2obd(next);
4376         if (obd == NULL) {
4377                 CERROR("%s: can't locate next device: %s\n",
4378                        mdt_obd_name(m), next);
4379                 GOTO(out, rc = -ENOTCONN);
4380         }
4381
4382         data->ocd_connect_flags = OBD_CONNECT_VERSION;
4383         data->ocd_version = LUSTRE_VERSION_CODE;
4384
4385         rc = obd_connect(NULL, exp, obd, &obd->obd_uuid, data, NULL);
4386         if (rc) {
4387                 CERROR("%s: cannot connect to next dev %s (%d)\n",
4388                        mdt_obd_name(m), next, rc);
4389                 GOTO(out, rc);
4390         }
4391
4392 out:
4393         if (data)
4394                 OBD_FREE_PTR(data);
4395         RETURN(rc);
4396 }
4397
4398 static int mdt_stack_init(const struct lu_env *env, struct mdt_device *mdt,
4399                           struct lustre_cfg *cfg)
4400 {
4401         char                   *dev = lustre_cfg_string(cfg, 0);
4402         int                     rc, name_size, uuid_size;
4403         char                   *name, *uuid, *p;
4404         struct lustre_cfg_bufs *bufs;
4405         struct lustre_cfg      *lcfg;
4406         struct obd_device      *obd;
4407         struct lustre_profile  *lprof;
4408         struct lu_site         *site;
4409         ENTRY;
4410
4411         /* in 1.8 we had the only device in the stack - MDS.
4412          * 2.0 introduces MDT, MDD, OSD; MDT starts others internally.
4413          * in 2.3 OSD is instantiated by obd_mount.c, so we need
4414          * to generate names and setup MDT, MDD. MDT will be using
4415          * generated name to connect to MDD. for MDD the next device
4416          * will be LOD with name taken from so called "profile" which
4417          * is generated by mount_option line
4418          *
4419          * 1.8 MGS generates config. commands like this:
4420          *   #06 (104)mount_option 0:  1:lustre-MDT0000  2:lustre-mdtlov
4421          *   #08 (120)setup   0:lustre-MDT0000  1:dev 2:type 3:lustre-MDT0000
4422          * 2.0 MGS generates config. commands like this:
4423          *   #07 (112)mount_option 0:  1:lustre-MDT0000  2:lustre-MDT0000-mdtlov
4424          *   #08 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
4425          *                    3:lustre-MDT0000-mdtlov  4:f
4426          *
4427          * we generate MDD name from MDT one, just replacing T with D
4428          *
4429          * after all the preparations, the logical equivalent will be
4430          *   #01 (160)setup   0:lustre-MDD0000  1:lustre-MDD0000_UUID  2:0
4431          *                    3:lustre-MDT0000-mdtlov  4:f
4432          *   #02 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
4433          *                    3:lustre-MDD0000  4:f
4434          *
4435          *  notice we build the stack from down to top: MDD first, then MDT */
4436
4437         name_size = MAX_OBD_NAME;
4438         uuid_size = MAX_OBD_NAME;
4439
4440         OBD_ALLOC(name, name_size);
4441         OBD_ALLOC(uuid, uuid_size);
4442         if (name == NULL || uuid == NULL)
4443                 GOTO(cleanup_mem, rc = -ENOMEM);
4444
4445         OBD_ALLOC_PTR(bufs);
4446         if (!bufs)
4447                 GOTO(cleanup_mem, rc = -ENOMEM);
4448
4449         strcpy(name, dev);
4450         p = strstr(name, "-MDT");
4451         if (p == NULL)
4452                 GOTO(cleanup_mem, rc = -ENOMEM);
4453         p[3] = 'D';
4454
4455         snprintf(uuid, MAX_OBD_NAME, "%s_UUID", name);
4456
4457         lprof = class_get_profile(lustre_cfg_string(cfg, 0));
4458         if (lprof == NULL || lprof->lp_dt == NULL) {
4459                 CERROR("can't find the profile: %s\n",
4460                        lustre_cfg_string(cfg, 0));
4461                 GOTO(cleanup_mem, rc = -EINVAL);
4462         }
4463
4464         lustre_cfg_bufs_reset(bufs, name);
4465         lustre_cfg_bufs_set_string(bufs, 1, LUSTRE_MDD_NAME);
4466         lustre_cfg_bufs_set_string(bufs, 2, uuid);
4467         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
4468
4469         lcfg = lustre_cfg_new(LCFG_ATTACH, bufs);
4470         if (!lcfg)
4471                 GOTO(free_bufs, rc = -ENOMEM);
4472
4473         rc = class_attach(lcfg);
4474         if (rc)
4475                 GOTO(lcfg_cleanup, rc);
4476
4477         obd = class_name2obd(name);
4478         if (!obd) {
4479                 CERROR("Can not find obd %s (%s in config)\n",
4480                        MDD_OBD_NAME, lustre_cfg_string(cfg, 0));
4481                 GOTO(class_detach, rc = -EINVAL);
4482         }
4483
4484         lustre_cfg_free(lcfg);
4485
4486         lustre_cfg_bufs_reset(bufs, name);
4487         lustre_cfg_bufs_set_string(bufs, 1, uuid);
4488         lustre_cfg_bufs_set_string(bufs, 2, dev);
4489         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
4490
4491         lcfg = lustre_cfg_new(LCFG_SETUP, bufs);
4492
4493         rc = class_setup(obd, lcfg);
4494         if (rc)
4495                 GOTO(class_detach, rc);
4496
4497         /* connect to MDD we just setup */
4498         rc = mdt_connect_to_next(env, mdt, name, &mdt->mdt_child_exp);
4499         if (rc)
4500                 RETURN(rc);
4501
4502         site = mdt->mdt_child_exp->exp_obd->obd_lu_dev->ld_site;
4503         LASSERT(site);
4504         LASSERT(mdt_lu_site(mdt) == NULL);
4505         mdt->mdt_lu_dev.ld_site = site;
4506         site->ls_top_dev = &mdt->mdt_lu_dev;
4507         mdt->mdt_child = lu2md_dev(mdt->mdt_child_exp->exp_obd->obd_lu_dev);
4508
4509
4510         /* now connect to bottom OSD */
4511         snprintf(name, MAX_OBD_NAME, "%s-osd", dev);
4512         rc = mdt_connect_to_next(env, mdt, name, &mdt->mdt_bottom_exp);
4513         if (rc)
4514                 RETURN(rc);
4515         mdt->mdt_bottom =
4516                 lu2dt_dev(mdt->mdt_bottom_exp->exp_obd->obd_lu_dev);
4517
4518
4519         rc = lu_env_refill((struct lu_env *)env);
4520         if (rc != 0)
4521                 CERROR("Failure to refill session: '%d'\n", rc);
4522
4523         lu_dev_add_linkage(site, &mdt->mdt_lu_dev);
4524
4525         EXIT;
4526 class_detach:
4527         if (rc)
4528                 class_detach(obd, lcfg);
4529 lcfg_cleanup:
4530         lustre_cfg_free(lcfg);
4531 free_bufs:
4532         OBD_FREE_PTR(bufs);
4533 cleanup_mem:
4534         if (name)
4535                 OBD_FREE(name, name_size);
4536         if (uuid)
4537                 OBD_FREE(uuid, uuid_size);
4538         RETURN(rc);
4539 }
4540
4541 /* setup quota master target on MDT0 */
4542 static int mdt_quota_init(const struct lu_env *env, struct mdt_device *mdt,
4543                           struct lustre_cfg *cfg)
4544 {
4545         struct obd_device       *obd;
4546         char                    *dev = lustre_cfg_string(cfg, 0);
4547         char                    *qmtname, *uuid, *p;
4548         struct lustre_cfg_bufs  *bufs;
4549         struct lustre_cfg       *lcfg;
4550         struct lustre_profile   *lprof;
4551         struct obd_connect_data *data;
4552         int                      rc;
4553         ENTRY;
4554
4555         LASSERT(mdt->mdt_qmt_exp == NULL);
4556         LASSERT(mdt->mdt_qmt_dev == NULL);
4557
4558         /* quota master is on MDT0 only for now */
4559         if (mdt->mdt_seq_site.ss_node_id != 0)
4560                 RETURN(0);
4561
4562         /* MGS generates config commands which look as follows:
4563          *   #01 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
4564          *                    3:lustre-MDT0000-mdtlov  4:f
4565          *
4566          * We generate the QMT name from the MDT one, just replacing MD with QM
4567          * after all the preparations, the logical equivalent will be:
4568          *   #01 (160)setup   0:lustre-QMT0000  1:lustre-QMT0000_UUID  2:0
4569          *                    3:lustre-MDT0000-osd  4:f */
4570         OBD_ALLOC(qmtname, MAX_OBD_NAME);
4571         OBD_ALLOC(uuid, UUID_MAX);
4572         OBD_ALLOC_PTR(bufs);
4573         OBD_ALLOC_PTR(data);
4574         if (qmtname == NULL || uuid == NULL || bufs == NULL || data == NULL)
4575                 GOTO(cleanup_mem, rc = -ENOMEM);
4576
4577         strcpy(qmtname, dev);
4578         p = strstr(qmtname, "-MDT");
4579         if (p == NULL)
4580                 GOTO(cleanup_mem, rc = -ENOMEM);
4581         /* replace MD with QM */
4582         p[1] = 'Q';
4583         p[2] = 'M';
4584
4585         snprintf(uuid, UUID_MAX, "%s_UUID", qmtname);
4586
4587         lprof = class_get_profile(lustre_cfg_string(cfg, 0));
4588         if (lprof == NULL || lprof->lp_dt == NULL) {
4589                 CERROR("can't find profile for %s\n",
4590                        lustre_cfg_string(cfg, 0));
4591                 GOTO(cleanup_mem, rc = -EINVAL);
4592         }
4593
4594         lustre_cfg_bufs_reset(bufs, qmtname);
4595         lustre_cfg_bufs_set_string(bufs, 1, LUSTRE_QMT_NAME);
4596         lustre_cfg_bufs_set_string(bufs, 2, uuid);
4597         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
4598
4599         lcfg = lustre_cfg_new(LCFG_ATTACH, bufs);
4600         if (!lcfg)
4601                 GOTO(cleanup_mem, rc = -ENOMEM);
4602
4603         rc = class_attach(lcfg);
4604         if (rc)
4605                 GOTO(lcfg_cleanup, rc);
4606
4607         obd = class_name2obd(qmtname);
4608         if (!obd) {
4609                 CERROR("Can not find obd %s (%s in config)\n", qmtname,
4610                        lustre_cfg_string(cfg, 0));
4611                 GOTO(class_detach, rc = -EINVAL);
4612         }
4613
4614         lustre_cfg_free(lcfg);
4615
4616         lustre_cfg_bufs_reset(bufs, qmtname);
4617         lustre_cfg_bufs_set_string(bufs, 1, uuid);
4618         lustre_cfg_bufs_set_string(bufs, 2, dev);
4619
4620         /* for quota, the next device should be the OSD device */
4621         lustre_cfg_bufs_set_string(bufs, 3,
4622                                    mdt->mdt_bottom->dd_lu_dev.ld_obd->obd_name);
4623
4624         lcfg = lustre_cfg_new(LCFG_SETUP, bufs);
4625
4626         rc = class_setup(obd, lcfg);
4627         if (rc)
4628                 GOTO(class_detach, rc);
4629
4630         mdt->mdt_qmt_dev = obd->obd_lu_dev;
4631
4632         /* configure local quota objects */
4633         rc = mdt->mdt_qmt_dev->ld_ops->ldo_prepare(env,
4634                                                    &mdt->mdt_lu_dev,
4635                                                    mdt->mdt_qmt_dev);
4636         if (rc)
4637                 GOTO(class_cleanup, rc);
4638
4639         /* connect to quota master target */
4640         data->ocd_connect_flags = OBD_CONNECT_VERSION;
4641         data->ocd_version = LUSTRE_VERSION_CODE;
4642         rc = obd_connect(NULL, &mdt->mdt_qmt_exp, obd, &obd->obd_uuid,
4643                          data, NULL);
4644         if (rc) {
4645                 CERROR("cannot connect to quota master device %s (%d)\n",
4646                        qmtname, rc);
4647                 GOTO(class_cleanup, rc);
4648         }
4649
4650         EXIT;
4651 class_cleanup:
4652         if (rc) {
4653                 class_manual_cleanup(obd);
4654                 mdt->mdt_qmt_dev = NULL;
4655         }
4656 class_detach:
4657         if (rc)
4658                 class_detach(obd, lcfg);
4659 lcfg_cleanup:
4660         lustre_cfg_free(lcfg);
4661 cleanup_mem:
4662         if (bufs)
4663                 OBD_FREE_PTR(bufs);
4664         if (qmtname)
4665                 OBD_FREE(qmtname, MAX_OBD_NAME);
4666         if (uuid)
4667                 OBD_FREE(uuid, UUID_MAX);
4668         if (data)
4669                 OBD_FREE_PTR(data);
4670         return rc;
4671 }
4672
4673 /* Shutdown quota master target associated with mdt */
4674 static void mdt_quota_fini(const struct lu_env *env, struct mdt_device *mdt)
4675 {
4676         ENTRY;
4677
4678         if (mdt->mdt_qmt_exp == NULL)
4679                 RETURN_EXIT;
4680         LASSERT(mdt->mdt_qmt_dev != NULL);
4681
4682         /* the qmt automatically shuts down when the mdt disconnects */
4683         obd_disconnect(mdt->mdt_qmt_exp);
4684         mdt->mdt_qmt_exp = NULL;
4685         mdt->mdt_qmt_dev = NULL;
4686         EXIT;
4687 }
4688
4689 static struct tgt_handler mdt_tgt_handlers[] = {
4690 TGT_RPC_HANDLER(MDS_FIRST_OPC,
4691                 0,                      MDS_CONNECT,    mdt_tgt_connect,
4692                 &RQF_CONNECT, LUSTRE_OBD_VERSION),
4693 TGT_RPC_HANDLER(MDS_FIRST_OPC,
4694                 0,                      MDS_DISCONNECT, tgt_disconnect,
4695                 &RQF_MDS_DISCONNECT, LUSTRE_OBD_VERSION),
4696 };
4697
4698 static struct tgt_opc_slice mdt_common_slice[] = {
4699         {
4700                 .tos_opc_start  = MDS_FIRST_OPC,
4701                 .tos_opc_end    = MDS_LAST_OPC,
4702                 .tos_hs         = mdt_tgt_handlers
4703         },
4704         {
4705                 .tos_opc_start  = OBD_FIRST_OPC,
4706                 .tos_opc_end    = OBD_LAST_OPC,
4707                 .tos_hs         = tgt_obd_handlers
4708         },
4709         {
4710                 .tos_opc_start  = LDLM_FIRST_OPC,
4711                 .tos_opc_end    = LDLM_LAST_OPC,
4712                 .tos_hs         = tgt_dlm_handlers
4713         },
4714         {
4715                 .tos_opc_start  = SEC_FIRST_OPC,
4716                 .tos_opc_end    = SEC_LAST_OPC,
4717                 .tos_hs         = tgt_sec_ctx_handlers
4718         },
4719         {
4720                 .tos_opc_start  = UPDATE_OBJ,
4721                 .tos_opc_end    = UPDATE_LAST_OPC,
4722                 .tos_hs         = tgt_out_handlers
4723         },
4724         {
4725                 .tos_opc_start  = FLD_FIRST_OPC,
4726                 .tos_opc_end    = FLD_LAST_OPC,
4727                 .tos_hs         = fld_handlers
4728         },
4729         {
4730                 .tos_opc_start  = SEQ_FIRST_OPC,
4731                 .tos_opc_end    = SEQ_LAST_OPC,
4732                 .tos_hs         = seq_handlers
4733         },
4734         {
4735                 .tos_hs         = NULL
4736         }
4737 };
4738
4739 static void mdt_fini(const struct lu_env *env, struct mdt_device *m)
4740 {
4741         struct md_device  *next = m->mdt_child;
4742         struct lu_device  *d    = &m->mdt_lu_dev;
4743         struct obd_device *obd = mdt2obd_dev(m);
4744         ENTRY;
4745
4746         target_recovery_fini(obd);
4747
4748         ping_evictor_stop();
4749
4750         mdt_stack_pre_fini(env, m, md2lu_dev(m->mdt_child));
4751
4752         if (m->mdt_opts.mo_coordinator)
4753                 mdt_hsm_cdt_stop(m);
4754
4755         mdt_hsm_cdt_fini(m);
4756
4757         mdt_llog_ctxt_unclone(env, m, LLOG_AGENT_ORIG_CTXT);
4758         mdt_llog_ctxt_unclone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
4759         obd_exports_barrier(obd);
4760         obd_zombie_barrier();
4761
4762         mdt_procfs_fini(m);
4763
4764         tgt_fini(env, &m->mdt_lut);
4765         mdt_fs_cleanup(env, m);
4766         upcall_cache_cleanup(m->mdt_identity_cache);
4767         m->mdt_identity_cache = NULL;
4768
4769         if (m->mdt_namespace != NULL) {
4770                 ldlm_namespace_free(m->mdt_namespace, NULL,
4771                                     d->ld_obd->obd_force);
4772                 d->ld_obd->obd_namespace = m->mdt_namespace = NULL;
4773         }
4774
4775         mdt_quota_fini(env, m);
4776
4777         cfs_free_nidlist(&m->mdt_nosquash_nids);
4778         if (m->mdt_nosquash_str) {
4779                 OBD_FREE(m->mdt_nosquash_str, m->mdt_nosquash_strlen);
4780                 m->mdt_nosquash_str = NULL;
4781                 m->mdt_nosquash_strlen = 0;
4782         }
4783
4784         next->md_ops->mdo_iocontrol(env, next, OBD_IOC_PAUSE_LFSCK, 0, NULL);
4785
4786         mdt_seq_fini(env, m);
4787         mdt_fld_fini(env, m);
4788         sptlrpc_rule_set_free(&m->mdt_sptlrpc_rset);
4789
4790         next->md_ops->mdo_init_capa_ctxt(env, next, 0, 0, 0, NULL);
4791         cfs_timer_disarm(&m->mdt_ck_timer);
4792         mdt_ck_thread_stop(m);
4793
4794         /*
4795          * Finish the stack
4796          */
4797         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
4798
4799         LASSERT(cfs_atomic_read(&d->ld_ref) == 0);
4800
4801         server_put_mount(mdt_obd_name(m), NULL);
4802
4803         EXIT;
4804 }
4805
4806 static int mdt_adapt_sptlrpc_conf(struct obd_device *obd, int initial)
4807 {
4808         struct mdt_device       *m = mdt_dev(obd->obd_lu_dev);
4809         struct sptlrpc_rule_set  tmp_rset;
4810         int                      rc;
4811
4812         sptlrpc_rule_set_init(&tmp_rset);
4813         rc = sptlrpc_conf_target_get_rules(obd, &tmp_rset, initial);
4814         if (rc) {
4815                 CERROR("mdt %s: failed get sptlrpc rules: %d\n",
4816                        mdt_obd_name(m), rc);
4817                 return rc;
4818         }
4819
4820         sptlrpc_target_update_exp_flavor(obd, &tmp_rset);
4821
4822         write_lock(&m->mdt_sptlrpc_lock);
4823         sptlrpc_rule_set_free(&m->mdt_sptlrpc_rset);
4824         m->mdt_sptlrpc_rset = tmp_rset;
4825         write_unlock(&m->mdt_sptlrpc_lock);
4826
4827         return 0;
4828 }
4829
4830 int mdt_postrecov(const struct lu_env *, struct mdt_device *);
4831
4832 static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
4833                      struct lu_device_type *ldt, struct lustre_cfg *cfg)
4834 {
4835         struct mdt_thread_info    *info;
4836         struct obd_device         *obd;
4837         const char                *dev = lustre_cfg_string(cfg, 0);
4838         const char                *num = lustre_cfg_string(cfg, 2);
4839         struct lustre_mount_info  *lmi = NULL;
4840         struct lustre_sb_info     *lsi;
4841         struct lu_site            *s;
4842         struct seq_server_site    *ss_site;
4843         const char                *identity_upcall = "NONE";
4844         struct md_device          *next;
4845         int                        rc;
4846         long                       node_id;
4847         mntopt_t                   mntopts;
4848         ENTRY;
4849
4850         lu_device_init(&m->mdt_lu_dev, ldt);
4851         /*
4852          * Environment (env) might be missing mdt_thread_key values at that
4853          * point, if device is allocated when mdt_thread_key is in QUIESCENT
4854          * mode.
4855          *
4856          * Usually device allocation path doesn't use module key values, but
4857          * mdt has to do a lot of work here, so allocate key value.
4858          */
4859         rc = lu_env_refill((struct lu_env *)env);
4860         if (rc != 0)
4861                 RETURN(rc);
4862
4863         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4864         LASSERT(info != NULL);
4865
4866         obd = class_name2obd(dev);
4867         LASSERT(obd != NULL);
4868
4869         m->mdt_max_mdsize = MAX_MD_SIZE; /* 4 stripes */
4870
4871         m->mdt_som_conf = 0;
4872
4873         m->mdt_opts.mo_cos = MDT_COS_DEFAULT;
4874
4875         /* default is coordinator off, it is started through conf_param
4876          * or /proc */
4877         m->mdt_opts.mo_coordinator = 0;
4878
4879         lmi = server_get_mount(dev);
4880         if (lmi == NULL) {
4881                 CERROR("Cannot get mount info for %s!\n", dev);
4882                 RETURN(-EFAULT);
4883         } else {
4884                 lsi = s2lsi(lmi->lmi_sb);
4885                 /* CMD is supported only in IAM mode */
4886                 LASSERT(num);
4887                 node_id = simple_strtol(num, NULL, 10);
4888                 obd->u.obt.obt_magic = OBT_MAGIC;
4889         }
4890
4891         rwlock_init(&m->mdt_sptlrpc_lock);
4892         sptlrpc_rule_set_init(&m->mdt_sptlrpc_rset);
4893
4894         spin_lock_init(&m->mdt_ioepoch_lock);
4895         m->mdt_opts.mo_compat_resname = 0;
4896         m->mdt_opts.mo_mds_capa = 1;
4897         m->mdt_opts.mo_oss_capa = 1;
4898         m->mdt_capa_timeout = CAPA_TIMEOUT;
4899         m->mdt_capa_alg = CAPA_HMAC_ALG_SHA1;
4900         m->mdt_ck_timeout = CAPA_KEY_TIMEOUT;
4901         m->mdt_squash_uid = 0;
4902         m->mdt_squash_gid = 0;
4903         CFS_INIT_LIST_HEAD(&m->mdt_nosquash_nids);
4904         m->mdt_nosquash_str = NULL;
4905         m->mdt_nosquash_strlen = 0;
4906         init_rwsem(&m->mdt_squash_sem);
4907         spin_lock_init(&m->mdt_osfs_lock);
4908         m->mdt_osfs_age = cfs_time_shift_64(-1000);
4909         m->mdt_enable_remote_dir = 0;
4910         m->mdt_enable_remote_dir_gid = 0;
4911
4912         m->mdt_lu_dev.ld_ops = &mdt_lu_ops;
4913         m->mdt_lu_dev.ld_obd = obd;
4914         /* Set this lu_device to obd for error handling purposes. */
4915         obd->obd_lu_dev = &m->mdt_lu_dev;
4916
4917         /* init the stack */
4918         rc = mdt_stack_init((struct lu_env *)env, m, cfg);
4919         if (rc) {
4920                 CERROR("%s: Can't init device stack, rc %d\n",
4921                        mdt_obd_name(m), rc);
4922                 GOTO(err_lmi, rc);
4923         }
4924
4925         s = mdt_lu_site(m);
4926         ss_site = mdt_seq_site(m);
4927         s->ld_seq_site = ss_site;
4928         ss_site->ss_lu = s;
4929
4930         /* set server index */
4931         ss_site->ss_node_id = node_id;
4932
4933         /* failover is the default
4934          * FIXME: we do not failout mds0/mgs, which may cause some problems.
4935          * assumed whose ss_node_id == 0 XXX
4936          * */
4937         obd->obd_replayable = 1;
4938         /* No connection accepted until configurations will finish */
4939         obd->obd_no_conn = 1;
4940
4941         if (cfg->lcfg_bufcount > 4 && LUSTRE_CFG_BUFLEN(cfg, 4) > 0) {
4942                 char *str = lustre_cfg_string(cfg, 4);
4943                 if (strchr(str, 'n')) {
4944                         CWARN("%s: recovery disabled\n", mdt_obd_name(m));
4945                         obd->obd_replayable = 0;
4946                 }
4947         }
4948
4949         rc = mdt_fld_init(env, mdt_obd_name(m), m);
4950         if (rc)
4951                 GOTO(err_fini_stack, rc);
4952
4953         rc = mdt_seq_init(env, mdt_obd_name(m), m);
4954         if (rc)
4955                 GOTO(err_fini_fld, rc);
4956
4957         snprintf(info->mti_u.ns_name, sizeof(info->mti_u.ns_name), "%s-%s",
4958                  LUSTRE_MDT_NAME, obd->obd_uuid.uuid);
4959         m->mdt_namespace = ldlm_namespace_new(obd, info->mti_u.ns_name,
4960                                               LDLM_NAMESPACE_SERVER,
4961                                               LDLM_NAMESPACE_GREEDY,
4962                                               LDLM_NS_TYPE_MDT);
4963         if (m->mdt_namespace == NULL)
4964                 GOTO(err_fini_seq, rc = -ENOMEM);
4965
4966         m->mdt_namespace->ns_lvbp = m;
4967         m->mdt_namespace->ns_lvbo = &mdt_lvbo;
4968
4969         ldlm_register_intent(m->mdt_namespace, mdt_intent_policy);
4970         /* set obd_namespace for compatibility with old code */
4971         obd->obd_namespace = m->mdt_namespace;
4972
4973         cfs_timer_init(&m->mdt_ck_timer, mdt_ck_timer_callback, m);
4974
4975         rc = mdt_hsm_cdt_init(m);
4976         if (rc != 0) {
4977                 CERROR("%s: error initializing coordinator, rc %d\n",
4978                        mdt_obd_name(m), rc);
4979                 GOTO(err_free_ns, rc);
4980         }
4981
4982         rc = mdt_ck_thread_start(m);
4983         if (rc)
4984                 GOTO(err_free_hsm, rc);
4985
4986         rc = tgt_init(env, &m->mdt_lut, obd, m->mdt_bottom, mdt_common_slice,
4987                       OBD_FAIL_MDS_ALL_REQUEST_NET,
4988                       OBD_FAIL_MDS_ALL_REPLY_NET);
4989         if (rc)
4990                 GOTO(err_capa, rc);
4991
4992         rc = mdt_fs_setup(env, m, obd, lsi);
4993         if (rc)
4994                 GOTO(err_tgt, rc);
4995
4996         mdt_adapt_sptlrpc_conf(obd, 1);
4997
4998         next = m->mdt_child;
4999         rc = next->md_ops->mdo_iocontrol(env, next, OBD_IOC_GET_MNTOPT, 0,
5000                                          &mntopts);
5001         if (rc)
5002                 GOTO(err_fs_cleanup, rc);
5003
5004         if (mntopts & MNTOPT_USERXATTR)
5005                 m->mdt_opts.mo_user_xattr = 1;
5006         else
5007                 m->mdt_opts.mo_user_xattr = 0;
5008
5009         rc = next->md_ops->mdo_maxeasize_get(env, next, &m->mdt_max_ea_size);
5010         if (rc)
5011                 GOTO(err_fs_cleanup, rc);
5012
5013         if (mntopts & MNTOPT_ACL)
5014                 m->mdt_opts.mo_acl = 1;
5015         else
5016                 m->mdt_opts.mo_acl = 0;
5017
5018         /* XXX: to support suppgid for ACL, we enable identity_upcall
5019          * by default, otherwise, maybe got unexpected -EACCESS. */
5020         if (m->mdt_opts.mo_acl)
5021                 identity_upcall = MDT_IDENTITY_UPCALL_PATH;
5022
5023         m->mdt_identity_cache = upcall_cache_init(mdt_obd_name(m),
5024                                                 identity_upcall,
5025                                                 &mdt_identity_upcall_cache_ops);
5026         if (IS_ERR(m->mdt_identity_cache)) {
5027                 rc = PTR_ERR(m->mdt_identity_cache);
5028                 m->mdt_identity_cache = NULL;
5029                 GOTO(err_fs_cleanup, rc);
5030         }
5031
5032         rc = mdt_procfs_init(m, dev);
5033         if (rc) {
5034                 CERROR("Can't init MDT lprocfs, rc %d\n", rc);
5035                 GOTO(err_recovery, rc);
5036         }
5037
5038         rc = mdt_quota_init(env, m, cfg);
5039         if (rc)
5040                 GOTO(err_procfs, rc);
5041
5042         m->mdt_ldlm_client = &mdt2obd_dev(m)->obd_ldlm_client;
5043         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
5044                            "mdt_ldlm_client", m->mdt_ldlm_client);
5045
5046         ping_evictor_start();
5047
5048         /* recovery will be started upon mdt_prepare()
5049          * when the whole stack is complete and ready
5050          * to serve the requests */
5051
5052         mdt_init_capa_ctxt(env, m);
5053
5054         /* Reduce the initial timeout on an MDS because it doesn't need such
5055          * a long timeout as an OST does. Adaptive timeouts will adjust this
5056          * value appropriately. */
5057         if (ldlm_timeout == LDLM_TIMEOUT_DEFAULT)
5058                 ldlm_timeout = MDS_LDLM_TIMEOUT_DEFAULT;
5059
5060         RETURN(0);
5061 err_procfs:
5062         mdt_procfs_fini(m);
5063 err_recovery:
5064         target_recovery_fini(obd);
5065         upcall_cache_cleanup(m->mdt_identity_cache);
5066         m->mdt_identity_cache = NULL;
5067 err_fs_cleanup:
5068         mdt_fs_cleanup(env, m);
5069 err_tgt:
5070         tgt_fini(env, &m->mdt_lut);
5071 err_capa:
5072         cfs_timer_disarm(&m->mdt_ck_timer);
5073         mdt_ck_thread_stop(m);
5074 err_free_hsm:
5075         mdt_hsm_cdt_fini(m);
5076 err_free_ns:
5077         ldlm_namespace_free(m->mdt_namespace, NULL, 0);
5078         obd->obd_namespace = m->mdt_namespace = NULL;
5079 err_fini_seq:
5080         mdt_seq_fini(env, m);
5081 err_fini_fld:
5082         mdt_fld_fini(env, m);
5083 err_fini_stack:
5084         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
5085 err_lmi:
5086         if (lmi)
5087                 server_put_mount(dev, lmi->lmi_mnt);
5088         return(rc);
5089 }
5090
5091 /* For interoperability, the left element is old parameter, the right one
5092  * is the new version of the parameter, if some parameter is deprecated,
5093  * the new version should be set as NULL. */
5094 static struct cfg_interop_param mdt_interop_param[] = {
5095         { "mdt.group_upcall",   NULL },
5096         { "mdt.quota_type",     NULL },
5097         { "mdd.quota_type",     NULL },
5098         { "mdt.rootsquash",     "mdt.root_squash" },
5099         { "mdt.nosquash_nid",   "mdt.nosquash_nids" },
5100         { NULL }
5101 };
5102
5103 /* used by MGS to process specific configurations */
5104 static int mdt_process_config(const struct lu_env *env,
5105                               struct lu_device *d, struct lustre_cfg *cfg)
5106 {
5107         struct mdt_device *m = mdt_dev(d);
5108         struct md_device *md_next = m->mdt_child;
5109         struct lu_device *next = md2lu_dev(md_next);
5110         int rc;
5111         ENTRY;
5112
5113         switch (cfg->lcfg_command) {
5114         case LCFG_PARAM: {
5115                 struct lprocfs_static_vars  lvars;
5116                 struct obd_device          *obd = d->ld_obd;
5117
5118                 /* For interoperability */
5119                 struct cfg_interop_param   *ptr = NULL;
5120                 struct lustre_cfg          *old_cfg = NULL;
5121                 char                       *param = NULL;
5122
5123                 param = lustre_cfg_string(cfg, 1);
5124                 if (param == NULL) {
5125                         CERROR("param is empty\n");
5126                         rc = -EINVAL;
5127                         break;
5128                 }
5129
5130                 ptr = class_find_old_param(param, mdt_interop_param);
5131                 if (ptr != NULL) {
5132                         if (ptr->new_param == NULL) {
5133                                 rc = 0;
5134                                 CWARN("For interoperability, skip this %s."
5135                                       " It is obsolete.\n", ptr->old_param);
5136                                 break;
5137                         }
5138
5139                         CWARN("Found old param %s, changed it to %s.\n",
5140                               ptr->old_param, ptr->new_param);
5141
5142                         old_cfg = cfg;
5143                         cfg = lustre_cfg_rename(old_cfg, ptr->new_param);
5144                         if (IS_ERR(cfg)) {
5145                                 rc = PTR_ERR(cfg);
5146                                 break;
5147                         }
5148                 }
5149
5150                 lprocfs_mdt_init_vars(&lvars);
5151                 rc = class_process_proc_param(PARAM_MDT, lvars.obd_vars,
5152                                               cfg, obd);
5153                 if (rc > 0 || rc == -ENOSYS)
5154                         /* we don't understand; pass it on */
5155                         rc = next->ld_ops->ldo_process_config(env, next, cfg);
5156
5157                 if (old_cfg != NULL)
5158                         lustre_cfg_free(cfg);
5159
5160                 break;
5161         }
5162         default:
5163                 /* others are passed further */
5164                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
5165                 break;
5166         }
5167         RETURN(rc);
5168 }
5169
5170 static struct lu_object *mdt_object_alloc(const struct lu_env *env,
5171                                           const struct lu_object_header *hdr,
5172                                           struct lu_device *d)
5173 {
5174         struct mdt_object *mo;
5175
5176         ENTRY;
5177
5178         OBD_SLAB_ALLOC_PTR_GFP(mo, mdt_object_kmem, __GFP_IO);
5179         if (mo != NULL) {
5180                 struct lu_object *o;
5181                 struct lu_object_header *h;
5182
5183                 o = &mo->mot_obj;
5184                 h = &mo->mot_header;
5185                 lu_object_header_init(h);
5186                 lu_object_init(o, h, d);
5187                 lu_object_add_top(h, o);
5188                 o->lo_ops = &mdt_obj_ops;
5189                 mutex_init(&mo->mot_ioepoch_mutex);
5190                 mutex_init(&mo->mot_lov_mutex);
5191                 init_rwsem(&mo->mot_open_sem);
5192                 init_rwsem(&mo->mot_xattr_sem);
5193                 RETURN(o);
5194         }
5195         RETURN(NULL);
5196 }
5197
5198 static int mdt_object_init(const struct lu_env *env, struct lu_object *o,
5199                            const struct lu_object_conf *unused)
5200 {
5201         struct mdt_device *d = mdt_dev(o->lo_dev);
5202         struct lu_device  *under;
5203         struct lu_object  *below;
5204         int                rc = 0;
5205         ENTRY;
5206
5207         CDEBUG(D_INFO, "object init, fid = "DFID"\n",
5208                PFID(lu_object_fid(o)));
5209
5210         under = &d->mdt_child->md_lu_dev;
5211         below = under->ld_ops->ldo_object_alloc(env, o->lo_header, under);
5212         if (below != NULL) {
5213                 lu_object_add(o, below);
5214         } else
5215                 rc = -ENOMEM;
5216
5217         RETURN(rc);
5218 }
5219
5220 static void mdt_object_free(const struct lu_env *env, struct lu_object *o)
5221 {
5222         struct mdt_object *mo = mdt_obj(o);
5223         struct lu_object_header *h;
5224         ENTRY;
5225
5226         h = o->lo_header;
5227         CDEBUG(D_INFO, "object free, fid = "DFID"\n",
5228                PFID(lu_object_fid(o)));
5229
5230         LASSERT(atomic_read(&mo->mot_open_count) == 0);
5231         LASSERT(atomic_read(&mo->mot_lease_count) == 0);
5232
5233         lu_object_fini(o);
5234         lu_object_header_fini(h);
5235         OBD_SLAB_FREE_PTR(mo, mdt_object_kmem);
5236
5237         EXIT;
5238 }
5239
5240 static int mdt_object_print(const struct lu_env *env, void *cookie,
5241                             lu_printer_t p, const struct lu_object *o)
5242 {
5243         struct mdt_object *mdto = mdt_obj((struct lu_object *)o);
5244         return (*p)(env, cookie, LUSTRE_MDT_NAME"-object@%p(ioepoch="LPU64" "
5245                     "flags="LPX64", epochcount=%d, writecount=%d)",
5246                     mdto, mdto->mot_ioepoch, mdto->mot_flags,
5247                     mdto->mot_ioepoch_count, mdto->mot_writecount);
5248 }
5249
5250 static int mdt_prepare(const struct lu_env *env,
5251                 struct lu_device *pdev,
5252                 struct lu_device *cdev)
5253 {
5254         struct mdt_device *mdt = mdt_dev(cdev);
5255         struct lu_device *next = &mdt->mdt_child->md_lu_dev;
5256         struct obd_device *obd = cdev->ld_obd;
5257         struct lfsck_start_param lsp;
5258         int rc;
5259
5260         ENTRY;
5261
5262         LASSERT(obd);
5263
5264         rc = next->ld_ops->ldo_prepare(env, cdev, next);
5265         if (rc)
5266                 RETURN(rc);
5267
5268         rc = mdt_llog_ctxt_clone(env, mdt, LLOG_CHANGELOG_ORIG_CTXT);
5269         if (rc)
5270                 RETURN(rc);
5271
5272         rc = mdt_llog_ctxt_clone(env, mdt, LLOG_AGENT_ORIG_CTXT);
5273         if (rc)
5274                 RETURN(rc);
5275
5276         lsp.lsp_start = NULL;
5277         lsp.lsp_namespace = mdt->mdt_namespace;
5278         rc = mdt->mdt_child->md_ops->mdo_iocontrol(env, mdt->mdt_child,
5279                                                    OBD_IOC_START_LFSCK,
5280                                                    0, &lsp);
5281         if (rc != 0) {
5282                 CWARN("%s: auto trigger paused LFSCK failed: rc = %d\n",
5283                       mdt_obd_name(mdt), rc);
5284                 rc = 0;
5285         }
5286
5287         if (mdt->mdt_seq_site.ss_node_id == 0) {
5288                 rc = mdt->mdt_child->md_ops->mdo_root_get(env, mdt->mdt_child,
5289                                                          &mdt->mdt_md_root_fid);
5290                 if (rc)
5291                         RETURN(rc);
5292         }
5293
5294         LASSERT(!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state));
5295         target_recovery_init(&mdt->mdt_lut, mdt_recovery_handle);
5296         set_bit(MDT_FL_CFGLOG, &mdt->mdt_state);
5297         LASSERT(obd->obd_no_conn);
5298         spin_lock(&obd->obd_dev_lock);
5299         obd->obd_no_conn = 0;
5300         spin_unlock(&obd->obd_dev_lock);
5301
5302         if (obd->obd_recovering == 0)
5303                 mdt_postrecov(env, mdt);
5304
5305         RETURN(rc);
5306 }
5307
5308 const struct lu_device_operations mdt_lu_ops = {
5309         .ldo_object_alloc   = mdt_object_alloc,
5310         .ldo_process_config = mdt_process_config,
5311         .ldo_prepare        = mdt_prepare,
5312 };
5313
5314 static const struct lu_object_operations mdt_obj_ops = {
5315         .loo_object_init    = mdt_object_init,
5316         .loo_object_free    = mdt_object_free,
5317         .loo_object_print   = mdt_object_print
5318 };
5319
5320 static int mdt_obd_set_info_async(const struct lu_env *env,
5321                                   struct obd_export *exp,
5322                                   __u32 keylen, void *key,
5323                                   __u32 vallen, void *val,
5324                                   struct ptlrpc_request_set *set)
5325 {
5326         struct obd_device     *obd = exp->exp_obd;
5327         int                    rc;
5328         ENTRY;
5329
5330         LASSERT(obd);
5331
5332         if (KEY_IS(KEY_SPTLRPC_CONF)) {
5333                 rc = mdt_adapt_sptlrpc_conf(obd, 0);
5334                 RETURN(rc);
5335         }
5336
5337         RETURN(0);
5338 }
5339
5340 /**
5341  * Match client and server connection feature flags.
5342  *
5343  * Compute the compatibility flags for a connection request based on
5344  * features mutually supported by client and server.
5345  *
5346  * The obd_export::exp_connect_data.ocd_connect_flags field in \a exp
5347  * must not be updated here, otherwise a partially initialized value may
5348  * be exposed. After the connection request is successfully processed,
5349  * the top-level MDT connect request handler atomically updates the export
5350  * connect flags from the obd_connect_data::ocd_connect_flags field of the
5351  * reply. \see mdt_connect().
5352  *
5353  * \param exp   the obd_export associated with this client/target pair
5354  * \param mdt   the target device for the connection
5355  * \param data  stores data for this connect request
5356  *
5357  * \retval 0       success
5358  * \retval -EPROTO \a data unexpectedly has zero obd_connect_data::ocd_brw_size
5359  * \retval -EBADE  client and server feature requirements are incompatible
5360  */
5361 static int mdt_connect_internal(struct obd_export *exp,
5362                                 struct mdt_device *mdt,
5363                                 struct obd_connect_data *data)
5364 {
5365         LASSERT(data != NULL);
5366
5367         data->ocd_connect_flags &= MDT_CONNECT_SUPPORTED;
5368         data->ocd_ibits_known &= MDS_INODELOCK_FULL;
5369
5370         /* If no known bits (which should not happen, probably,
5371            as everybody should support LOOKUP and UPDATE bits at least)
5372            revert to compat mode with plain locks. */
5373         if (!data->ocd_ibits_known &&
5374             data->ocd_connect_flags & OBD_CONNECT_IBITS)
5375                 data->ocd_connect_flags &= ~OBD_CONNECT_IBITS;
5376
5377         if (!mdt->mdt_opts.mo_acl)
5378                 data->ocd_connect_flags &= ~OBD_CONNECT_ACL;
5379
5380         if (!mdt->mdt_opts.mo_user_xattr)
5381                 data->ocd_connect_flags &= ~OBD_CONNECT_XATTR;
5382
5383         if (!mdt->mdt_som_conf)
5384                 data->ocd_connect_flags &= ~OBD_CONNECT_SOM;
5385
5386         if (data->ocd_connect_flags & OBD_CONNECT_BRW_SIZE) {
5387                 data->ocd_brw_size = min(data->ocd_brw_size,
5388                                          (__u32)MD_MAX_BRW_SIZE);
5389                 if (data->ocd_brw_size == 0) {
5390                         CERROR("%s: cli %s/%p ocd_connect_flags: "LPX64
5391                                " ocd_version: %x ocd_grant: %d "
5392                                "ocd_index: %u ocd_brw_size is "
5393                                "unexpectedly zero, network data "
5394                                "corruption? Refusing connection of this"
5395                                " client\n",
5396                                mdt_obd_name(mdt),
5397                                exp->exp_client_uuid.uuid,
5398                                exp, data->ocd_connect_flags, data->ocd_version,
5399                                data->ocd_grant, data->ocd_index);
5400                         return -EPROTO;
5401                 }
5402         }
5403
5404         /* NB: Disregard the rule against updating
5405          * exp_connect_data.ocd_connect_flags in this case, since
5406          * tgt_client_new() needs to know if this is a lightweight
5407          * connection, and it is safe to expose this flag before
5408          * connection processing completes. */
5409         if (data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT) {
5410                 spin_lock(&exp->exp_lock);
5411                 *exp_connect_flags_ptr(exp) |= OBD_CONNECT_LIGHTWEIGHT;
5412                 spin_unlock(&exp->exp_lock);
5413         }
5414
5415         data->ocd_version = LUSTRE_VERSION_CODE;
5416         exp->exp_connect_data = *data;
5417         exp->exp_mdt_data.med_ibits_known = data->ocd_ibits_known;
5418
5419         if ((data->ocd_connect_flags & OBD_CONNECT_FID) == 0) {
5420                 CWARN("%s: MDS requires FID support, but client not\n",
5421                       mdt_obd_name(mdt));
5422                 return -EBADE;
5423         }
5424
5425         if (mdt->mdt_som_conf &&
5426             !(data->ocd_connect_flags & (OBD_CONNECT_LIGHTWEIGHT |
5427                                          OBD_CONNECT_MDS_MDS |
5428                                          OBD_CONNECT_SOM))) {
5429                 CWARN("%s: MDS has SOM enabled, but client does not support "
5430                       "it\n", mdt_obd_name(mdt));
5431                 return -EBADE;
5432         }
5433
5434         if (OCD_HAS_FLAG(data, PINGLESS)) {
5435                 if (ptlrpc_pinger_suppress_pings()) {
5436                         spin_lock(&exp->exp_obd->obd_dev_lock);
5437                         list_del_init(&exp->exp_obd_chain_timed);
5438                         spin_unlock(&exp->exp_obd->obd_dev_lock);
5439                 } else {
5440                         data->ocd_connect_flags &= ~OBD_CONNECT_PINGLESS;
5441                 }
5442         }
5443
5444         data->ocd_max_easize = mdt->mdt_max_ea_size;
5445
5446         return 0;
5447 }
5448
5449 int mdt_connect_check_sptlrpc(struct mdt_device *mdt, struct obd_export *exp,
5450                               struct ptlrpc_request *req)
5451 {
5452         struct sptlrpc_flavor   flvr;
5453         int                     rc = 0;
5454
5455         if (exp->exp_flvr.sf_rpc == SPTLRPC_FLVR_INVALID) {
5456                 read_lock(&mdt->mdt_sptlrpc_lock);
5457                 sptlrpc_target_choose_flavor(&mdt->mdt_sptlrpc_rset,
5458                                              req->rq_sp_from,
5459                                              req->rq_peer.nid,
5460                                              &flvr);
5461                 read_unlock(&mdt->mdt_sptlrpc_lock);
5462
5463                 spin_lock(&exp->exp_lock);
5464
5465                 exp->exp_sp_peer = req->rq_sp_from;
5466                 exp->exp_flvr = flvr;
5467
5468                 if (exp->exp_flvr.sf_rpc != SPTLRPC_FLVR_ANY &&
5469                     exp->exp_flvr.sf_rpc != req->rq_flvr.sf_rpc) {
5470                         CERROR("unauthorized rpc flavor %x from %s, "
5471                                "expect %x\n", req->rq_flvr.sf_rpc,
5472                                libcfs_nid2str(req->rq_peer.nid),
5473                                exp->exp_flvr.sf_rpc);
5474                         rc = -EACCES;
5475                 }
5476
5477                 spin_unlock(&exp->exp_lock);
5478         } else {
5479                 if (exp->exp_sp_peer != req->rq_sp_from) {
5480                         CERROR("RPC source %s doesn't match %s\n",
5481                                sptlrpc_part2name(req->rq_sp_from),
5482                                sptlrpc_part2name(exp->exp_sp_peer));
5483                         rc = -EACCES;
5484                 } else {
5485                         rc = sptlrpc_target_export_check(exp, req);
5486                 }
5487         }
5488
5489         return rc;
5490 }
5491
5492 /* mds_connect copy */
5493 static int mdt_obd_connect(const struct lu_env *env,
5494                            struct obd_export **exp, struct obd_device *obd,
5495                            struct obd_uuid *cluuid,
5496                            struct obd_connect_data *data,
5497                            void *localdata)
5498 {
5499         struct obd_export      *lexp;
5500         struct lustre_handle    conn = { 0 };
5501         struct mdt_device      *mdt;
5502         int                     rc;
5503         ENTRY;
5504
5505         LASSERT(env != NULL);
5506         if (!exp || !obd || !cluuid)
5507                 RETURN(-EINVAL);
5508
5509         mdt = mdt_dev(obd->obd_lu_dev);
5510
5511         /*
5512          * first, check whether the stack is ready to handle requests
5513          * XXX: probably not very appropriate method is used now
5514          *      at some point we should find a better one
5515          */
5516         if (!test_bit(MDT_FL_SYNCED, &mdt->mdt_state) &&
5517             !(data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT)) {
5518                 rc = obd_health_check(env, mdt->mdt_child_exp->exp_obd);
5519                 if (rc)
5520                         RETURN(-EAGAIN);
5521                 set_bit(MDT_FL_SYNCED, &mdt->mdt_state);
5522         }
5523
5524         rc = class_connect(&conn, obd, cluuid);
5525         if (rc)
5526                 RETURN(rc);
5527
5528         lexp = class_conn2export(&conn);
5529         LASSERT(lexp != NULL);
5530
5531         rc = mdt_connect_internal(lexp, mdt, data);
5532         if (rc == 0) {
5533                 struct lsd_client_data *lcd = lexp->exp_target_data.ted_lcd;
5534
5535                 LASSERT(lcd);
5536                 memcpy(lcd->lcd_uuid, cluuid, sizeof lcd->lcd_uuid);
5537                 rc = tgt_client_new(env, lexp);
5538                 if (rc == 0)
5539                         mdt_export_stats_init(obd, lexp, localdata);
5540         }
5541
5542         if (rc != 0) {
5543                 class_disconnect(lexp);
5544                 *exp = NULL;
5545         } else {
5546                 *exp = lexp;
5547         }
5548
5549         RETURN(rc);
5550 }
5551
5552 static int mdt_obd_reconnect(const struct lu_env *env,
5553                              struct obd_export *exp, struct obd_device *obd,
5554                              struct obd_uuid *cluuid,
5555                              struct obd_connect_data *data,
5556                              void *localdata)
5557 {
5558         int                     rc;
5559         ENTRY;
5560
5561         if (exp == NULL || obd == NULL || cluuid == NULL)
5562                 RETURN(-EINVAL);
5563
5564         rc = mdt_connect_internal(exp, mdt_dev(obd->obd_lu_dev), data);
5565         if (rc == 0)
5566                 mdt_export_stats_init(obd, exp, localdata);
5567
5568         RETURN(rc);
5569 }
5570
5571 static int mdt_ctxt_add_dirty_flag(struct lu_env *env,
5572                                    struct mdt_thread_info *info,
5573                                    struct mdt_file_data *mfd)
5574 {
5575         struct lu_context ses;
5576         int rc;
5577         ENTRY;
5578
5579         rc = lu_context_init(&ses, LCT_SESSION);
5580         if (rc)
5581                 RETURN(rc);
5582
5583         env->le_ses = &ses;
5584         lu_context_enter(&ses);
5585
5586         mdt_ucred(info)->uc_valid = UCRED_OLD;
5587         rc = mdt_add_dirty_flag(info, mfd->mfd_object, &info->mti_attr);
5588
5589         lu_context_exit(&ses);
5590         lu_context_fini(&ses);
5591         env->le_ses = NULL;
5592
5593         RETURN(rc);
5594 }
5595
5596 static int mdt_export_cleanup(struct obd_export *exp)
5597 {
5598         struct mdt_export_data *med = &exp->exp_mdt_data;
5599         struct obd_device      *obd = exp->exp_obd;
5600         struct mdt_device      *mdt;
5601         struct mdt_thread_info *info;
5602         struct lu_env           env;
5603         CFS_LIST_HEAD(closing_list);
5604         struct mdt_file_data *mfd, *n;
5605         int rc = 0;
5606         ENTRY;
5607
5608         spin_lock(&med->med_open_lock);
5609         while (!cfs_list_empty(&med->med_open_head)) {
5610                 cfs_list_t *tmp = med->med_open_head.next;
5611                 mfd = cfs_list_entry(tmp, struct mdt_file_data, mfd_list);
5612
5613                 /* Remove mfd handle so it can't be found again.
5614                  * We are consuming the mfd_list reference here. */
5615                 class_handle_unhash(&mfd->mfd_handle);
5616                 cfs_list_move_tail(&mfd->mfd_list, &closing_list);
5617         }
5618         spin_unlock(&med->med_open_lock);
5619         mdt = mdt_dev(obd->obd_lu_dev);
5620         LASSERT(mdt != NULL);
5621
5622         rc = lu_env_init(&env, LCT_MD_THREAD);
5623         if (rc)
5624                 RETURN(rc);
5625
5626         info = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5627         LASSERT(info != NULL);
5628         memset(info, 0, sizeof *info);
5629         info->mti_env = &env;
5630         info->mti_mdt = mdt;
5631         info->mti_exp = exp;
5632
5633         if (!cfs_list_empty(&closing_list)) {
5634                 struct md_attr *ma = &info->mti_attr;
5635
5636                 /* Close any open files (which may also cause orphan unlinking). */
5637                 cfs_list_for_each_entry_safe(mfd, n, &closing_list, mfd_list) {
5638                         cfs_list_del_init(&mfd->mfd_list);
5639                         ma->ma_need = ma->ma_valid = 0;
5640
5641                         /* This file is being closed due to an eviction, it
5642                          * could have been modified and now dirty regarding to
5643                          * HSM archive, check this!
5644                          * The logic here is to mark a file dirty if there's a
5645                          * chance it was dirtied before the client was evicted,
5646                          * so that we don't have to wait for a release attempt
5647                          * before finding out the file was actually dirty and
5648                          * fail the release. Aggressively marking it dirty here
5649                          * will cause the policy engine to attempt to
5650                          * re-archive it; when rearchiving, we can compare the
5651                          * current version to the HSM data_version and make the
5652                          * archive request into a noop if it's not actually
5653                          * dirty.
5654                          */
5655                         if (mfd->mfd_mode & (FMODE_WRITE|MDS_FMODE_TRUNC))
5656                                 rc = mdt_ctxt_add_dirty_flag(&env, info, mfd);
5657
5658                         /* Don't unlink orphan on failover umount, LU-184 */
5659                         if (exp->exp_flags & OBD_OPT_FAILOVER) {
5660                                 ma->ma_valid = MA_FLAGS;
5661                                 ma->ma_attr_flags |= MDS_KEEP_ORPHAN;
5662                         }
5663                         mdt_mfd_close(info, mfd);
5664                 }
5665         }
5666         info->mti_mdt = NULL;
5667         /* cleanup client slot early */
5668         /* Do not erase record for recoverable client. */
5669         if (!(exp->exp_flags & OBD_OPT_FAILOVER) || exp->exp_failed)
5670                 tgt_client_del(&env, exp);
5671         lu_env_fini(&env);
5672
5673         RETURN(rc);
5674 }
5675
5676 static int mdt_obd_disconnect(struct obd_export *exp)
5677 {
5678         int rc;
5679         ENTRY;
5680
5681         LASSERT(exp);
5682         class_export_get(exp);
5683
5684         rc = server_disconnect_export(exp);
5685         if (rc != 0)
5686                 CDEBUG(D_IOCTL, "server disconnect error: %d\n", rc);
5687
5688         rc = mdt_export_cleanup(exp);
5689         class_export_put(exp);
5690         RETURN(rc);
5691 }
5692
5693 /* FIXME: Can we avoid using these two interfaces? */
5694 static int mdt_init_export(struct obd_export *exp)
5695 {
5696         struct mdt_export_data *med = &exp->exp_mdt_data;
5697         int                     rc;
5698         ENTRY;
5699
5700         CFS_INIT_LIST_HEAD(&med->med_open_head);
5701         spin_lock_init(&med->med_open_lock);
5702         mutex_init(&med->med_idmap_mutex);
5703         med->med_idmap = NULL;
5704         spin_lock(&exp->exp_lock);
5705         exp->exp_connecting = 1;
5706         spin_unlock(&exp->exp_lock);
5707
5708         /* self-export doesn't need client data and ldlm initialization */
5709         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
5710                                      &exp->exp_client_uuid)))
5711                 RETURN(0);
5712
5713         rc = tgt_client_alloc(exp);
5714         if (rc)
5715                 GOTO(err, rc);
5716
5717         rc = ldlm_init_export(exp);
5718         if (rc)
5719                 GOTO(err_free, rc);
5720
5721         RETURN(rc);
5722
5723 err_free:
5724         tgt_client_free(exp);
5725 err:
5726         CERROR("%s: Failed to initialize export: rc = %d\n",
5727                exp->exp_obd->obd_name, rc);
5728         return rc;
5729 }
5730
5731 static int mdt_destroy_export(struct obd_export *exp)
5732 {
5733         ENTRY;
5734
5735         if (exp_connect_rmtclient(exp))
5736                 mdt_cleanup_idmap(&exp->exp_mdt_data);
5737
5738         target_destroy_export(exp);
5739         /* destroy can be called from failed obd_setup, so
5740          * checking uuid is safer than obd_self_export */
5741         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
5742                                      &exp->exp_client_uuid)))
5743                 RETURN(0);
5744
5745         ldlm_destroy_export(exp);
5746         tgt_client_free(exp);
5747
5748         LASSERT(cfs_list_empty(&exp->exp_outstanding_replies));
5749         LASSERT(cfs_list_empty(&exp->exp_mdt_data.med_open_head));
5750
5751         RETURN(0);
5752 }
5753
5754 /** The maximum depth that fid2path() will search.
5755  * This is limited only because we want to store the fids for
5756  * historical path lookup purposes.
5757  */
5758 #define MAX_PATH_DEPTH 100
5759
5760 /** mdt_path() lookup structure. */
5761 struct path_lookup_info {
5762         __u64                   pli_recno;      /**< history point */
5763         __u64                   pli_currec;     /**< current record */
5764         struct lu_fid           pli_fid;
5765         struct lu_fid           pli_fids[MAX_PATH_DEPTH]; /**< path, in fids */
5766         struct mdt_object       *pli_mdt_obj;
5767         char                    *pli_path;      /**< full path */
5768         int                     pli_pathlen;
5769         int                     pli_linkno;     /**< which hardlink to follow */
5770         int                     pli_fidcount;   /**< number of \a pli_fids */
5771 };
5772
5773 static int mdt_links_read(struct mdt_thread_info *info,
5774                           struct mdt_object *mdt_obj, struct linkea_data *ldata)
5775 {
5776         int rc;
5777
5778         LASSERT(ldata->ld_buf->lb_buf != NULL);
5779
5780         if (!mdt_object_exists(mdt_obj))
5781                 return -ENODATA;
5782
5783         rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
5784                           ldata->ld_buf, XATTR_NAME_LINK);
5785         if (rc == -ERANGE) {
5786                 /* Buf was too small, figure out what we need. */
5787                 lu_buf_free(ldata->ld_buf);
5788                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
5789                                   ldata->ld_buf, XATTR_NAME_LINK);
5790                 if (rc < 0)
5791                         return rc;
5792                 ldata->ld_buf = lu_buf_check_and_alloc(ldata->ld_buf, rc);
5793                 if (ldata->ld_buf->lb_buf == NULL)
5794                         return -ENOMEM;
5795                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
5796                                   ldata->ld_buf, XATTR_NAME_LINK);
5797         }
5798         if (rc < 0)
5799                 return rc;
5800
5801         return linkea_init(ldata);
5802 }
5803
5804 static int mdt_path_current(struct mdt_thread_info *info,
5805                             struct path_lookup_info *pli)
5806 {
5807         struct mdt_device       *mdt = info->mti_mdt;
5808         struct mdt_object       *mdt_obj;
5809         struct link_ea_header   *leh;
5810         struct link_ea_entry    *lee;
5811         struct lu_name          *tmpname = &info->mti_name;
5812         struct lu_fid           *tmpfid = &info->mti_tmp_fid1;
5813         struct lu_buf           *buf = &info->mti_big_buf;
5814         char                    *ptr;
5815         int                     reclen;
5816         struct linkea_data      ldata = { 0 };
5817         int                     rc = 0;
5818         ENTRY;
5819
5820         /* temp buffer for path element, the buffer will be finally freed
5821          * in mdt_thread_info_fini */
5822         buf = lu_buf_check_and_alloc(buf, PATH_MAX);
5823         if (buf->lb_buf == NULL)
5824                 RETURN(-ENOMEM);
5825
5826         ldata.ld_buf = buf;
5827         ptr = pli->pli_path + pli->pli_pathlen - 1;
5828         *ptr = 0;
5829         --ptr;
5830         pli->pli_fidcount = 0;
5831         pli->pli_fids[0] = *(struct lu_fid *)mdt_object_fid(pli->pli_mdt_obj);
5832
5833         /* root FID only exists on MDT0, and fid2path should also ends at MDT0,
5834          * so checking root_fid can only happen on MDT0. */
5835         while (!lu_fid_eq(&mdt->mdt_md_root_fid,
5836                           &pli->pli_fids[pli->pli_fidcount])) {
5837                 mdt_obj = mdt_object_find(info->mti_env, mdt,
5838                                           &pli->pli_fids[pli->pli_fidcount]);
5839                 if (IS_ERR(mdt_obj))
5840                         GOTO(out, rc = PTR_ERR(mdt_obj));
5841                 if (mdt_object_remote(mdt_obj)) {
5842                         mdt_object_put(info->mti_env, mdt_obj);
5843                         GOTO(remote_out, rc = -EREMOTE);
5844                 }
5845                 if (!mdt_object_exists(mdt_obj)) {
5846                         mdt_object_put(info->mti_env, mdt_obj);
5847                         GOTO(out, rc = -ENOENT);
5848                 }
5849
5850                 rc = mdt_links_read(info, mdt_obj, &ldata);
5851                 mdt_object_put(info->mti_env, mdt_obj);
5852                 if (rc != 0)
5853                         GOTO(out, rc);
5854
5855                 leh = buf->lb_buf;
5856                 lee = (struct link_ea_entry *)(leh + 1); /* link #0 */
5857                 linkea_entry_unpack(lee, &reclen, tmpname, tmpfid);
5858                 /* If set, use link #linkno for path lookup, otherwise use
5859                    link #0.  Only do this for the final path element. */
5860                 if (pli->pli_fidcount == 0 &&
5861                     pli->pli_linkno < leh->leh_reccount) {
5862                         int count;
5863                         for (count = 0; count < pli->pli_linkno; count++) {
5864                                 lee = (struct link_ea_entry *)
5865                                      ((char *)lee + reclen);
5866                                 linkea_entry_unpack(lee, &reclen, tmpname,
5867                                                     tmpfid);
5868                         }
5869                         if (pli->pli_linkno < leh->leh_reccount - 1)
5870                                 /* indicate to user there are more links */
5871                                 pli->pli_linkno++;
5872                 }
5873
5874                 /* Pack the name in the end of the buffer */
5875                 ptr -= tmpname->ln_namelen;
5876                 if (ptr - 1 <= pli->pli_path)
5877                         GOTO(out, rc = -EOVERFLOW);
5878                 strncpy(ptr, tmpname->ln_name, tmpname->ln_namelen);
5879                 *(--ptr) = '/';
5880
5881                 /* Store the parent fid for historic lookup */
5882                 if (++pli->pli_fidcount >= MAX_PATH_DEPTH)
5883                         GOTO(out, rc = -EOVERFLOW);
5884                 pli->pli_fids[pli->pli_fidcount] = *tmpfid;
5885         }
5886
5887 remote_out:
5888         ptr++; /* skip leading / */
5889         memmove(pli->pli_path, ptr, pli->pli_path + pli->pli_pathlen - ptr);
5890
5891         EXIT;
5892 out:
5893         return rc;
5894 }
5895
5896 /* Returns the full path to this fid, as of changelog record recno. */
5897 static int mdt_path(struct mdt_thread_info *info, struct mdt_object *obj,
5898                     char *path, int pathlen, __u64 *recno, int *linkno,
5899                     struct lu_fid *fid)
5900 {
5901         struct mdt_device       *mdt = info->mti_mdt;
5902         struct path_lookup_info *pli;
5903         int                     tries = 3;
5904         int                     rc = -EAGAIN;
5905         ENTRY;
5906
5907         if (pathlen < 3)
5908                 RETURN(-EOVERFLOW);
5909
5910         if (lu_fid_eq(&mdt->mdt_md_root_fid, mdt_object_fid(obj))) {
5911                 path[0] = '\0';
5912                 RETURN(0);
5913         }
5914
5915         OBD_ALLOC_PTR(pli);
5916         if (pli == NULL)
5917                 RETURN(-ENOMEM);
5918
5919         pli->pli_mdt_obj = obj;
5920         pli->pli_recno = *recno;
5921         pli->pli_path = path;
5922         pli->pli_pathlen = pathlen;
5923         pli->pli_linkno = *linkno;
5924
5925         /* Retry multiple times in case file is being moved */
5926         while (tries-- && rc == -EAGAIN)
5927                 rc = mdt_path_current(info, pli);
5928
5929         /* return the last resolved fids to the client, so the client will
5930          * build the left path on another MDT for remote object */
5931         *fid = pli->pli_fids[pli->pli_fidcount];
5932
5933         *recno = pli->pli_currec;
5934         /* Return next link index to caller */
5935         *linkno = pli->pli_linkno;
5936
5937         OBD_FREE_PTR(pli);
5938
5939         RETURN(rc);
5940 }
5941
5942 static int mdt_fid2path(struct mdt_thread_info *info,
5943                         struct getinfo_fid2path *fp)
5944 {
5945         struct mdt_device *mdt = info->mti_mdt;
5946         struct mdt_object *obj;
5947         int    rc;
5948         ENTRY;
5949
5950         CDEBUG(D_IOCTL, "path get "DFID" from "LPU64" #%d\n",
5951                 PFID(&fp->gf_fid), fp->gf_recno, fp->gf_linkno);
5952
5953         if (!fid_is_sane(&fp->gf_fid))
5954                 RETURN(-EINVAL);
5955
5956         if (!fid_is_namespace_visible(&fp->gf_fid)) {
5957                 CWARN("%s: "DFID" is invalid, sequence should be "
5958                       ">= "LPX64"\n", mdt_obd_name(mdt),
5959                       PFID(&fp->gf_fid), (__u64)FID_SEQ_NORMAL);
5960                 RETURN(-EINVAL);
5961         }
5962
5963         obj = mdt_object_find(info->mti_env, mdt, &fp->gf_fid);
5964         if (obj == NULL || IS_ERR(obj)) {
5965                 CDEBUG(D_IOCTL, "no object "DFID": %ld\n", PFID(&fp->gf_fid),
5966                        PTR_ERR(obj));
5967                 RETURN(-EINVAL);
5968         }
5969
5970         if (mdt_object_remote(obj))
5971                 rc = -EREMOTE;
5972         else if (!mdt_object_exists(obj))
5973                 rc = -ENOENT;
5974         else
5975                 rc = 0;
5976
5977         if (rc < 0) {
5978                 mdt_object_put(info->mti_env, obj);
5979                 CDEBUG(D_IOCTL, "nonlocal object "DFID": %d\n",
5980                        PFID(&fp->gf_fid), rc);
5981                 RETURN(rc);
5982         }
5983
5984         rc = mdt_path(info, obj, fp->gf_path, fp->gf_pathlen, &fp->gf_recno,
5985                       &fp->gf_linkno, &fp->gf_fid);
5986
5987         CDEBUG(D_INFO, "fid "DFID", path %s recno "LPX64" linkno %u\n",
5988                PFID(&fp->gf_fid), fp->gf_path, fp->gf_recno, fp->gf_linkno);
5989
5990         mdt_object_put(info->mti_env, obj);
5991
5992         RETURN(rc);
5993 }
5994
5995 static int mdt_rpc_fid2path(struct mdt_thread_info *info, void *key,
5996                             void *val, int vallen)
5997 {
5998         struct getinfo_fid2path *fpout, *fpin;
5999         int rc = 0;
6000
6001         fpin = key + cfs_size_round(sizeof(KEY_FID2PATH));
6002         fpout = val;
6003
6004         if (ptlrpc_req_need_swab(info->mti_pill->rc_req))
6005                 lustre_swab_fid2path(fpin);
6006
6007         memcpy(fpout, fpin, sizeof(*fpin));
6008         if (fpout->gf_pathlen != vallen - sizeof(*fpin))
6009                 RETURN(-EINVAL);
6010
6011         rc = mdt_fid2path(info, fpout);
6012         RETURN(rc);
6013 }
6014
6015 int mdt_get_info(struct mdt_thread_info *info)
6016 {
6017         struct ptlrpc_request *req = mdt_info_req(info);
6018         char *key;
6019         int keylen;
6020         __u32 *vallen;
6021         void *valout;
6022         int rc;
6023         ENTRY;
6024
6025         key = req_capsule_client_get(info->mti_pill, &RMF_GETINFO_KEY);
6026         if (key == NULL) {
6027                 CDEBUG(D_IOCTL, "No GETINFO key");
6028                 RETURN(-EFAULT);
6029         }
6030         keylen = req_capsule_get_size(info->mti_pill, &RMF_GETINFO_KEY,
6031                                       RCL_CLIENT);
6032
6033         vallen = req_capsule_client_get(info->mti_pill, &RMF_GETINFO_VALLEN);
6034         if (vallen == NULL) {
6035                 CDEBUG(D_IOCTL, "Unable to get RMF_GETINFO_VALLEN buffer");
6036                 RETURN(-EFAULT);
6037         }
6038
6039         req_capsule_set_size(info->mti_pill, &RMF_GETINFO_VAL, RCL_SERVER,
6040                              *vallen);
6041         rc = req_capsule_server_pack(info->mti_pill);
6042         valout = req_capsule_server_get(info->mti_pill, &RMF_GETINFO_VAL);
6043         if (valout == NULL) {
6044                 CDEBUG(D_IOCTL, "Unable to get get-info RPC out buffer");
6045                 RETURN(-EFAULT);
6046         }
6047
6048         if (KEY_IS(KEY_FID2PATH))
6049                 rc = mdt_rpc_fid2path(info, key, valout, *vallen);
6050         else
6051                 rc = -EINVAL;
6052
6053         lustre_msg_set_status(req->rq_repmsg, rc);
6054
6055         RETURN(rc);
6056 }
6057
6058 /* Pass the ioc down */
6059 static int mdt_ioc_child(struct lu_env *env, struct mdt_device *mdt,
6060                          unsigned int cmd, int len, void *data)
6061 {
6062         struct lu_context ioctl_session;
6063         struct md_device *next = mdt->mdt_child;
6064         int rc;
6065         ENTRY;
6066
6067         rc = lu_context_init(&ioctl_session, LCT_SESSION);
6068         if (rc)
6069                 RETURN(rc);
6070         ioctl_session.lc_thread = (struct ptlrpc_thread *)cfs_current();
6071         lu_context_enter(&ioctl_session);
6072         env->le_ses = &ioctl_session;
6073
6074         LASSERT(next->md_ops->mdo_iocontrol);
6075         rc = next->md_ops->mdo_iocontrol(env, next, cmd, len, data);
6076
6077         lu_context_exit(&ioctl_session);
6078         lu_context_fini(&ioctl_session);
6079         RETURN(rc);
6080 }
6081
6082 static int mdt_ioc_version_get(struct mdt_thread_info *mti, void *karg)
6083 {
6084         struct obd_ioctl_data *data = karg;
6085         struct lu_fid *fid;
6086         __u64 version;
6087         struct mdt_object *obj;
6088         struct mdt_lock_handle  *lh;
6089         int rc;
6090         ENTRY;
6091
6092         if (data->ioc_inlbuf1 == NULL || data->ioc_inllen1 != sizeof(*fid) ||
6093             data->ioc_inlbuf2 == NULL || data->ioc_inllen2 != sizeof(version))
6094                 RETURN(-EINVAL);
6095
6096         fid = (struct lu_fid *)data->ioc_inlbuf1;
6097
6098         if (!fid_is_sane(fid))
6099                 RETURN(-EINVAL);
6100
6101         CDEBUG(D_IOCTL, "getting version for "DFID"\n", PFID(fid));
6102
6103         lh = &mti->mti_lh[MDT_LH_PARENT];
6104         mdt_lock_reg_init(lh, LCK_CR);
6105
6106         obj = mdt_object_find_lock(mti, fid, lh, MDS_INODELOCK_UPDATE);
6107         if (IS_ERR(obj))
6108                 RETURN(PTR_ERR(obj));
6109
6110         if (mdt_object_remote(obj)) {
6111                 rc = -EREMOTE;
6112                 /**
6113                  * before calling version get the correct MDS should be
6114                  * fid, this is error to find remote object here
6115                  */
6116                 CERROR("nonlocal object "DFID"\n", PFID(fid));
6117         } else if (!mdt_object_exists(obj)) {
6118                 *(__u64 *)data->ioc_inlbuf2 = ENOENT_VERSION;
6119                 rc = -ENOENT;
6120         } else {
6121                 version = dt_version_get(mti->mti_env, mdt_obj2dt(obj));
6122                *(__u64 *)data->ioc_inlbuf2 = version;
6123                 rc = 0;
6124         }
6125         mdt_object_unlock_put(mti, obj, lh, 1);
6126         RETURN(rc);
6127 }
6128
6129 /* ioctls on obd dev */
6130 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
6131                          void *karg, void *uarg)
6132 {
6133         struct lu_env      env;
6134         struct obd_device *obd = exp->exp_obd;
6135         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
6136         struct dt_device  *dt = mdt->mdt_bottom;
6137         int rc;
6138
6139         ENTRY;
6140         CDEBUG(D_IOCTL, "handling ioctl cmd %#x\n", cmd);
6141         rc = lu_env_init(&env, LCT_MD_THREAD);
6142         if (rc)
6143                 RETURN(rc);
6144
6145         switch (cmd) {
6146         case OBD_IOC_SYNC:
6147                 rc = mdt_device_sync(&env, mdt);
6148                 break;
6149         case OBD_IOC_SET_READONLY:
6150                 rc = dt->dd_ops->dt_ro(&env, dt);
6151                 break;
6152         case OBD_IOC_ABORT_RECOVERY:
6153                 CERROR("%s: Aborting recovery for device\n", mdt_obd_name(mdt));
6154                 target_stop_recovery_thread(obd);
6155                 rc = 0;
6156                 break;
6157         case OBD_IOC_CHANGELOG_REG:
6158         case OBD_IOC_CHANGELOG_DEREG:
6159         case OBD_IOC_CHANGELOG_CLEAR:
6160                 rc = mdt_ioc_child(&env, mdt, cmd, len, karg);
6161                 break;
6162         case OBD_IOC_START_LFSCK: {
6163                 struct md_device *next = mdt->mdt_child;
6164                 struct obd_ioctl_data *data = karg;
6165                 struct lfsck_start_param lsp;
6166
6167                 if (unlikely(data == NULL)) {
6168                         rc = -EINVAL;
6169                         break;
6170                 }
6171
6172                 lsp.lsp_start = (struct lfsck_start *)(data->ioc_inlbuf1);
6173                 lsp.lsp_namespace = mdt->mdt_namespace;
6174                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0, &lsp);
6175                 break;
6176         }
6177         case OBD_IOC_STOP_LFSCK: {
6178                 struct md_device *next = mdt->mdt_child;
6179
6180                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0, NULL);
6181                 break;
6182         }
6183         case OBD_IOC_GET_OBJ_VERSION: {
6184                 struct mdt_thread_info *mti;
6185                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
6186                 memset(mti, 0, sizeof *mti);
6187                 mti->mti_env = &env;
6188                 mti->mti_mdt = mdt;
6189                 mti->mti_exp = exp;
6190
6191                 rc = mdt_ioc_version_get(mti, karg);
6192                 break;
6193         }
6194         default:
6195                 rc = -EOPNOTSUPP;
6196                 CERROR("%s: Not supported cmd = %d, rc = %d\n",
6197                         mdt_obd_name(mdt), cmd, rc);
6198         }
6199
6200         lu_env_fini(&env);
6201         RETURN(rc);
6202 }
6203
6204 int mdt_postrecov(const struct lu_env *env, struct mdt_device *mdt)
6205 {
6206         struct lu_device *ld = md2lu_dev(mdt->mdt_child);
6207         int rc;
6208         ENTRY;
6209
6210         rc = ld->ld_ops->ldo_recovery_complete(env, ld);
6211         RETURN(rc);
6212 }
6213
6214 int mdt_obd_postrecov(struct obd_device *obd)
6215 {
6216         struct lu_env env;
6217         int rc;
6218
6219         rc = lu_env_init(&env, LCT_MD_THREAD);
6220         if (rc)
6221                 RETURN(rc);
6222         rc = mdt_postrecov(&env, mdt_dev(obd->obd_lu_dev));
6223         lu_env_fini(&env);
6224         return rc;
6225 }
6226
6227 static struct obd_ops mdt_obd_device_ops = {
6228         .o_owner          = THIS_MODULE,
6229         .o_set_info_async = mdt_obd_set_info_async,
6230         .o_connect        = mdt_obd_connect,
6231         .o_reconnect      = mdt_obd_reconnect,
6232         .o_disconnect     = mdt_obd_disconnect,
6233         .o_init_export    = mdt_init_export,
6234         .o_destroy_export = mdt_destroy_export,
6235         .o_iocontrol      = mdt_iocontrol,
6236         .o_postrecov      = mdt_obd_postrecov,
6237 };
6238
6239 static struct lu_device* mdt_device_fini(const struct lu_env *env,
6240                                          struct lu_device *d)
6241 {
6242         struct mdt_device *m = mdt_dev(d);
6243         ENTRY;
6244
6245         mdt_fini(env, m);
6246         RETURN(NULL);
6247 }
6248
6249 static struct lu_device *mdt_device_free(const struct lu_env *env,
6250                                          struct lu_device *d)
6251 {
6252         struct mdt_device *m = mdt_dev(d);
6253         ENTRY;
6254
6255         lu_device_fini(&m->mdt_lu_dev);
6256         OBD_FREE_PTR(m);
6257
6258         RETURN(NULL);
6259 }
6260
6261 static struct lu_device *mdt_device_alloc(const struct lu_env *env,
6262                                           struct lu_device_type *t,
6263                                           struct lustre_cfg *cfg)
6264 {
6265         struct lu_device  *l;
6266         struct mdt_device *m;
6267
6268         OBD_ALLOC_PTR(m);
6269         if (m != NULL) {
6270                 int rc;
6271
6272                 l = &m->mdt_lu_dev;
6273                 rc = mdt_init0(env, m, t, cfg);
6274                 if (rc != 0) {
6275                         mdt_device_free(env, l);
6276                         l = ERR_PTR(rc);
6277                         return l;
6278                 }
6279         } else
6280                 l = ERR_PTR(-ENOMEM);
6281         return l;
6282 }
6283
6284 /* context key constructor/destructor: mdt_key_init, mdt_key_fini */
6285 LU_KEY_INIT(mdt, struct mdt_thread_info);
6286
6287 static void mdt_key_fini(const struct lu_context *ctx,
6288                          struct lu_context_key *key, void* data)
6289 {
6290         struct mdt_thread_info *info = data;
6291
6292         if (info->mti_big_lmm) {
6293                 OBD_FREE_LARGE(info->mti_big_lmm, info->mti_big_lmmsize);
6294                 info->mti_big_lmm = NULL;
6295                 info->mti_big_lmmsize = 0;
6296         }
6297         OBD_FREE_PTR(info);
6298 }
6299
6300 /* context key: mdt_thread_key */
6301 LU_CONTEXT_KEY_DEFINE(mdt, LCT_MD_THREAD);
6302
6303 struct lu_ucred *mdt_ucred(const struct mdt_thread_info *info)
6304 {
6305         return lu_ucred(info->mti_env);
6306 }
6307
6308 struct lu_ucred *mdt_ucred_check(const struct mdt_thread_info *info)
6309 {
6310         return lu_ucred_check(info->mti_env);
6311 }
6312
6313 /**
6314  * Enable/disable COS (Commit On Sharing).
6315  *
6316  * Set/Clear the COS flag in mdt options.
6317  *
6318  * \param mdt mdt device
6319  * \param val 0 disables COS, other values enable COS
6320  */
6321 void mdt_enable_cos(struct mdt_device *mdt, int val)
6322 {
6323         struct lu_env env;
6324         int rc;
6325
6326         mdt->mdt_opts.mo_cos = !!val;
6327         rc = lu_env_init(&env, LCT_LOCAL);
6328         if (unlikely(rc != 0)) {
6329                 CWARN("lu_env initialization failed with rc = %d,"
6330                       "cannot sync\n", rc);
6331                 return;
6332         }
6333         mdt_device_sync(&env, mdt);
6334         lu_env_fini(&env);
6335 }
6336
6337 /**
6338  * Check COS (Commit On Sharing) status.
6339  *
6340  * Return COS flag status.
6341  *
6342  * \param mdt mdt device
6343  */
6344 int mdt_cos_is_enabled(struct mdt_device *mdt)
6345 {
6346         return mdt->mdt_opts.mo_cos != 0;
6347 }
6348
6349 static struct lu_device_type_operations mdt_device_type_ops = {
6350         .ldto_device_alloc = mdt_device_alloc,
6351         .ldto_device_free  = mdt_device_free,
6352         .ldto_device_fini  = mdt_device_fini
6353 };
6354
6355 static struct lu_device_type mdt_device_type = {
6356         .ldt_tags     = LU_DEVICE_MD,
6357         .ldt_name     = LUSTRE_MDT_NAME,
6358         .ldt_ops      = &mdt_device_type_ops,
6359         .ldt_ctx_tags = LCT_MD_THREAD
6360 };
6361
6362 static int __init mdt_mod_init(void)
6363 {
6364         struct lprocfs_static_vars lvars;
6365         int rc;
6366
6367         CLASSERT(sizeof("0x0123456789ABCDEF:0x01234567:0x01234567") ==
6368                  FID_NOBRACE_LEN + 1);
6369         CLASSERT(sizeof("[0x0123456789ABCDEF:0x01234567:0x01234567]") ==
6370                  FID_LEN + 1);
6371         rc = lu_kmem_init(mdt_caches);
6372         if (rc)
6373                 return rc;
6374
6375         rc = mds_mod_init();
6376         if (rc)
6377                 GOTO(lu_fini, rc);
6378
6379         lprocfs_mdt_init_vars(&lvars);
6380         rc = class_register_type(&mdt_obd_device_ops, NULL,
6381                                  lvars.module_vars, LUSTRE_MDT_NAME,
6382                                  &mdt_device_type);
6383         if (rc)
6384                 GOTO(mds_fini, rc);
6385 lu_fini:
6386         if (rc)
6387                 lu_kmem_fini(mdt_caches);
6388 mds_fini:
6389         if (rc)
6390                 mds_mod_exit();
6391         return rc;
6392 }
6393
6394 static void __exit mdt_mod_exit(void)
6395 {
6396         class_unregister_type(LUSTRE_MDT_NAME);
6397         mds_mod_exit();
6398         lu_kmem_fini(mdt_caches);
6399 }
6400
6401 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
6402 MODULE_DESCRIPTION("Lustre Metadata Target ("LUSTRE_MDT_NAME")");
6403 MODULE_LICENSE("GPL");
6404
6405 cfs_module(mdt, LUSTRE_VERSION_STRING, mdt_mod_init, mdt_mod_exit);