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