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