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