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