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