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