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