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         rdpg->rp_count  = reqbody->nlink;
1418         rdpg->rp_npages = (rdpg->rp_count + CFS_PAGE_SIZE - 1)>>CFS_PAGE_SHIFT;
1419         OBD_ALLOC(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1420         if (rdpg->rp_pages == NULL)
1421                 RETURN(-ENOMEM);
1422
1423         for (i = 0; i < rdpg->rp_npages; ++i) {
1424                 rdpg->rp_pages[i] = cfs_alloc_page(CFS_ALLOC_STD);
1425                 if (rdpg->rp_pages[i] == NULL)
1426                         GOTO(free_rdpg, rc = -ENOMEM);
1427         }
1428
1429         /* call lower layers to fill allocated pages with directory data */
1430         rc = mo_readpage(info->mti_env, mdt_object_child(object), rdpg);
1431         if (rc)
1432                 GOTO(free_rdpg, rc);
1433
1434         /* send pages to client */
1435         rc = mdt_sendpage(info, rdpg);
1436
1437         EXIT;
1438 free_rdpg:
1439
1440         for (i = 0; i < rdpg->rp_npages; i++)
1441                 if (rdpg->rp_pages[i] != NULL)
1442                         cfs_free_page(rdpg->rp_pages[i]);
1443         OBD_FREE(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1444
1445         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE))
1446                 RETURN(0);
1447
1448         return rc;
1449 }
1450
1451 static int mdt_reint_internal(struct mdt_thread_info *info,
1452                               struct mdt_lock_handle *lhc,
1453                               __u32 op)
1454 {
1455         struct req_capsule      *pill = info->mti_pill;
1456         struct mdt_device       *mdt = info->mti_mdt;
1457         struct mdt_body         *repbody;
1458         int                      rc = 0;
1459         ENTRY;
1460
1461         /* pack reply */
1462         if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1463                 req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
1464                                      mdt->mdt_max_mdsize);
1465         if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
1466                 req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER,
1467                                      mdt->mdt_max_cookiesize);
1468
1469         rc = req_capsule_server_pack(pill);
1470         if (rc != 0) {
1471                 CERROR("Can't pack response, rc %d\n", rc);
1472                 RETURN(err_serious(rc));
1473         }
1474
1475         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_SERVER)) {
1476                 repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
1477                 LASSERT(repbody);
1478                 repbody->eadatasize = 0;
1479                 repbody->aclsize = 0;
1480         }
1481
1482         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_REINT_UNPACK))
1483                 GOTO(out_shrink, rc = err_serious(-EFAULT));
1484
1485         rc = mdt_reint_unpack(info, op);
1486         if (rc != 0) {
1487                 CERROR("Can't unpack reint, rc %d\n", rc);
1488                 GOTO(out_shrink, rc = err_serious(rc));
1489         }
1490
1491         /* for replay no cookkie / lmm need, because client have this already */
1492         if (info->mti_spec.no_create == 1)  {
1493                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1494                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, 0);
1495
1496                 if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
1497                         req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER,
1498                                              0);
1499         }
1500
1501         rc = mdt_init_ucred_reint(info);
1502         if (rc)
1503                 GOTO(out_shrink, rc);
1504
1505         rc = mdt_fix_attr_ucred(info, op);
1506         if (rc != 0)
1507                 GOTO(out_ucred, rc = err_serious(rc));
1508
1509         if (mdt_check_resent(info, mdt_reconstruct, lhc)) {
1510                 rc = lustre_msg_get_status(mdt_info_req(info)->rq_repmsg);
1511                 GOTO(out_ucred, rc);
1512         }
1513         rc = mdt_reint_rec(info, lhc);
1514         EXIT;
1515 out_ucred:
1516         mdt_exit_ucred(info);
1517 out_shrink:
1518         mdt_shrink_reply(info);
1519         return rc;
1520 }
1521
1522 static long mdt_reint_opcode(struct mdt_thread_info *info,
1523                              const struct req_format **fmt)
1524 {
1525         struct mdt_rec_reint *rec;
1526         long opc;
1527
1528         opc = err_serious(-EFAULT);
1529         rec = req_capsule_client_get(info->mti_pill, &RMF_REC_REINT);
1530         if (rec != NULL) {
1531                 opc = rec->rr_opcode;
1532                 DEBUG_REQ(D_INODE, mdt_info_req(info), "reint opt = %ld", opc);
1533                 if (opc < REINT_MAX && fmt[opc] != NULL)
1534                         req_capsule_extend(info->mti_pill, fmt[opc]);
1535                 else {
1536                         CERROR("Unsupported opc: %ld\n", opc);
1537                         opc = err_serious(opc);
1538                 }
1539         }
1540         return opc;
1541 }
1542
1543 static int mdt_reint(struct mdt_thread_info *info)
1544 {
1545         long opc;
1546         int  rc;
1547
1548         static const struct req_format *reint_fmts[REINT_MAX] = {
1549                 [REINT_SETATTR]  = &RQF_MDS_REINT_SETATTR,
1550                 [REINT_CREATE]   = &RQF_MDS_REINT_CREATE,
1551                 [REINT_LINK]     = &RQF_MDS_REINT_LINK,
1552                 [REINT_UNLINK]   = &RQF_MDS_REINT_UNLINK,
1553                 [REINT_RENAME]   = &RQF_MDS_REINT_RENAME,
1554                 [REINT_OPEN]     = &RQF_MDS_REINT_OPEN,
1555                 [REINT_SETXATTR] = &RQF_MDS_REINT_SETXATTR
1556         };
1557
1558         ENTRY;
1559
1560         opc = mdt_reint_opcode(info, reint_fmts);
1561         if (opc >= 0) {
1562                 /*
1563                  * No lock possible here from client to pass it to reint code
1564                  * path.
1565                  */
1566                 rc = mdt_reint_internal(info, NULL, opc);
1567         } else {
1568                 rc = opc;
1569         }
1570
1571         info->mti_fail_id = OBD_FAIL_MDS_REINT_NET_REP;
1572         RETURN(rc);
1573 }
1574
1575 /* this should sync the whole device */
1576 static int mdt_device_sync(const struct lu_env *env, struct mdt_device *mdt)
1577 {
1578         struct dt_device *dt = mdt->mdt_bottom;
1579         int rc;
1580         ENTRY;
1581
1582         rc = dt->dd_ops->dt_sync(env, dt);
1583         RETURN(rc);
1584 }
1585
1586 /* this should sync this object */
1587 static int mdt_object_sync(struct mdt_thread_info *info)
1588 {
1589         struct md_object *next;
1590         int rc;
1591         ENTRY;
1592
1593         if (!mdt_object_exists(info->mti_object)) {
1594                 CWARN("Non existing object  "DFID"!\n",
1595                       PFID(mdt_object_fid(info->mti_object)));
1596                 RETURN(-ESTALE);
1597         }
1598         next = mdt_object_child(info->mti_object);
1599         rc = mo_object_sync(info->mti_env, next);
1600
1601         RETURN(rc);
1602 }
1603
1604 static int mdt_sync(struct mdt_thread_info *info)
1605 {
1606         struct req_capsule *pill = info->mti_pill;
1607         struct mdt_body *body;
1608         int rc;
1609         ENTRY;
1610
1611         /* The fid may be zero, so we req_capsule_set manually */
1612         req_capsule_set(pill, &RQF_MDS_SYNC);
1613
1614         body = req_capsule_client_get(pill, &RMF_MDT_BODY);
1615         if (body == NULL)
1616                 RETURN(err_serious(-EINVAL));
1617
1618         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SYNC_PACK))
1619                 RETURN(err_serious(-ENOMEM));
1620
1621         if (fid_seq(&body->fid1) == 0) {
1622                 /* sync the whole device */
1623                 rc = req_capsule_server_pack(pill);
1624                 if (rc == 0)
1625                         rc = mdt_device_sync(info->mti_env, info->mti_mdt);
1626                 else
1627                         rc = err_serious(rc);
1628         } else {
1629                 /* sync an object */
1630                 rc = mdt_unpack_req_pack_rep(info, HABEO_CORPUS|HABEO_REFERO);
1631                 if (rc == 0) {
1632                         rc = mdt_object_sync(info);
1633                         if (rc == 0) {
1634                                 struct md_object *next;
1635                                 const struct lu_fid *fid;
1636                                 struct lu_attr *la = &info->mti_attr.ma_attr;
1637
1638                                 next = mdt_object_child(info->mti_object);
1639                                 info->mti_attr.ma_need = MA_INODE;
1640                                 info->mti_attr.ma_valid = 0;
1641                                 rc = mo_attr_get(info->mti_env, next,
1642                                                  &info->mti_attr);
1643                                 if (rc == 0) {
1644                                         body = req_capsule_server_get(pill,
1645                                                                 &RMF_MDT_BODY);
1646                                         fid = mdt_object_fid(info->mti_object);
1647                                         mdt_pack_attr2body(info, body, la, fid);
1648                                 }
1649                         }
1650                 } else
1651                         rc = err_serious(rc);
1652         }
1653         RETURN(rc);
1654 }
1655
1656 #ifdef HAVE_QUOTA_SUPPORT
1657 static int mdt_quotacheck_handle(struct mdt_thread_info *info)
1658 {
1659         struct obd_quotactl *oqctl;
1660         struct req_capsule *pill = info->mti_pill;
1661         struct obd_export *exp = info->mti_exp;
1662         struct md_device *next = info->mti_mdt->mdt_child;
1663         int rc;
1664         ENTRY;
1665
1666         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_QUOTACHECK_NET))
1667                 RETURN(0);
1668
1669         oqctl = req_capsule_client_get(pill, &RMF_OBD_QUOTACTL);
1670         if (oqctl == NULL)
1671                 RETURN(-EPROTO);
1672
1673         /* remote client has no permission for quotacheck */
1674         if (unlikely(exp_connect_rmtclient(exp)))
1675                 RETURN(-EPERM);
1676
1677         rc = req_capsule_server_pack(pill);
1678         if (rc)
1679                 RETURN(rc);
1680
1681         rc = next->md_ops->mdo_quota.mqo_check(info->mti_env, next, exp,
1682                                                oqctl->qc_type);
1683         RETURN(rc);
1684 }
1685
1686 static int mdt_quotactl_handle(struct mdt_thread_info *info)
1687 {
1688         struct obd_quotactl *oqctl, *repoqc;
1689         struct req_capsule *pill = info->mti_pill;
1690         struct obd_export *exp = info->mti_exp;
1691         struct md_device *next = info->mti_mdt->mdt_child;
1692         const struct md_quota_operations *mqo = &next->md_ops->mdo_quota;
1693         int id, rc;
1694         ENTRY;
1695
1696         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_QUOTACTL_NET))
1697                 RETURN(0);
1698
1699         oqctl = req_capsule_client_get(pill, &RMF_OBD_QUOTACTL);
1700         if (oqctl == NULL)
1701                 RETURN(-EPROTO);
1702
1703         id = oqctl->qc_id;
1704         if (exp_connect_rmtclient(exp)) {
1705                 struct ptlrpc_request *req = mdt_info_req(info);
1706                 struct mdt_export_data *med = mdt_req2med(req);
1707                 struct lustre_idmap_table *idmap = med->med_idmap;
1708
1709                 if (unlikely(oqctl->qc_cmd != Q_GETQUOTA &&
1710                              oqctl->qc_cmd != Q_GETINFO))
1711                         RETURN(-EPERM);
1712
1713
1714                 if (oqctl->qc_type == USRQUOTA)
1715                         id = lustre_idmap_lookup_uid(NULL, idmap, 0,
1716                                                      oqctl->qc_id);
1717                 else if (oqctl->qc_type == GRPQUOTA)
1718                         id = lustre_idmap_lookup_gid(NULL, idmap, 0,
1719                                                      oqctl->qc_id);
1720                 else
1721                         RETURN(-EINVAL);
1722
1723                 if (id == CFS_IDMAP_NOTFOUND) {
1724                         CDEBUG(D_QUOTA, "no mapping for id %u\n",
1725                                oqctl->qc_id);
1726                         RETURN(-EACCES);
1727                 }
1728         }
1729
1730         rc = req_capsule_server_pack(pill);
1731         if (rc)
1732                 RETURN(rc);
1733
1734         repoqc = req_capsule_server_get(pill, &RMF_OBD_QUOTACTL);
1735         LASSERT(repoqc != NULL);
1736
1737         switch (oqctl->qc_cmd) {
1738         case Q_QUOTAON:
1739                 rc = mqo->mqo_on(info->mti_env, next, oqctl->qc_type);
1740                 break;
1741         case Q_QUOTAOFF:
1742                 rc = mqo->mqo_off(info->mti_env, next, oqctl->qc_type);
1743                 break;
1744         case Q_SETINFO:
1745                 rc = mqo->mqo_setinfo(info->mti_env, next, oqctl->qc_type, id,
1746                                       &oqctl->qc_dqinfo);
1747                 break;
1748         case Q_GETINFO:
1749                 rc = mqo->mqo_getinfo(info->mti_env, next, oqctl->qc_type, id,
1750                                       &oqctl->qc_dqinfo);
1751                 break;
1752         case Q_SETQUOTA:
1753                 rc = mqo->mqo_setquota(info->mti_env, next, oqctl->qc_type, id,
1754                                        &oqctl->qc_dqblk);
1755                 break;
1756         case Q_GETQUOTA:
1757                 rc = mqo->mqo_getquota(info->mti_env, next, oqctl->qc_type, id,
1758                                        &oqctl->qc_dqblk);
1759                 break;
1760         case Q_GETOINFO:
1761                 rc = mqo->mqo_getoinfo(info->mti_env, next, oqctl->qc_type, id,
1762                                        &oqctl->qc_dqinfo);
1763                 break;
1764         case Q_GETOQUOTA:
1765                 rc = mqo->mqo_getoquota(info->mti_env, next, oqctl->qc_type, id,
1766                                         &oqctl->qc_dqblk);
1767                 break;
1768         case LUSTRE_Q_INVALIDATE:
1769                 rc = mqo->mqo_invalidate(info->mti_env, next, oqctl->qc_type);
1770                 break;
1771         case LUSTRE_Q_FINVALIDATE:
1772                 rc = mqo->mqo_finvalidate(info->mti_env, next, oqctl->qc_type);
1773                 break;
1774         default:
1775                 CERROR("unsupported mdt_quotactl command: %d\n",
1776                        oqctl->qc_cmd);
1777                 RETURN(-EFAULT);
1778         }
1779
1780         *repoqc = *oqctl;
1781         RETURN(rc);
1782 }
1783 #endif
1784
1785 /*
1786  * OBD PING and other handlers.
1787  */
1788 static int mdt_obd_ping(struct mdt_thread_info *info)
1789 {
1790         int rc;
1791         ENTRY;
1792
1793         req_capsule_set(info->mti_pill, &RQF_OBD_PING);
1794
1795         rc = target_handle_ping(mdt_info_req(info));
1796         if (rc < 0)
1797                 rc = err_serious(rc);
1798         RETURN(rc);
1799 }
1800
1801 static int mdt_obd_log_cancel(struct mdt_thread_info *info)
1802 {
1803         return err_serious(-EOPNOTSUPP);
1804 }
1805
1806 static int mdt_obd_qc_callback(struct mdt_thread_info *info)
1807 {
1808         return err_serious(-EOPNOTSUPP);
1809 }
1810
1811
1812 /*
1813  * DLM handlers.
1814  */
1815 static struct ldlm_callback_suite cbs = {
1816         .lcs_completion = ldlm_server_completion_ast,
1817         .lcs_blocking   = ldlm_server_blocking_ast,
1818         .lcs_glimpse    = NULL
1819 };
1820
1821 static int mdt_enqueue(struct mdt_thread_info *info)
1822 {
1823         struct ptlrpc_request *req;
1824         __u64 req_bits;
1825         int rc;
1826
1827         /*
1828          * info->mti_dlm_req already contains swapped and (if necessary)
1829          * converted dlm request.
1830          */
1831         LASSERT(info->mti_dlm_req != NULL);
1832
1833         req = mdt_info_req(info);
1834
1835         /*
1836          * Lock without inodebits makes no sense and will oops later in
1837          * ldlm. Let's check it now to see if we have wrong lock from client or
1838          * bits get corrupted somewhere in mdt_intent_policy().
1839          */
1840         req_bits = info->mti_dlm_req->lock_desc.l_policy_data.l_inodebits.bits;
1841         /* This is disabled because we need to support liblustre flock.
1842          * LASSERT(req_bits != 0);
1843          */
1844
1845         rc = ldlm_handle_enqueue0(info->mti_mdt->mdt_namespace,
1846                                   req, info->mti_dlm_req, &cbs);
1847         info->mti_fail_id = OBD_FAIL_LDLM_REPLY;
1848         return rc ? err_serious(rc) : req->rq_status;
1849 }
1850
1851 static int mdt_convert(struct mdt_thread_info *info)
1852 {
1853         int rc;
1854         struct ptlrpc_request *req;
1855
1856         LASSERT(info->mti_dlm_req);
1857         req = mdt_info_req(info);
1858         rc = ldlm_handle_convert0(req, info->mti_dlm_req);
1859         return rc ? err_serious(rc) : req->rq_status;
1860 }
1861
1862 static int mdt_bl_callback(struct mdt_thread_info *info)
1863 {
1864         CERROR("bl callbacks should not happen on MDS\n");
1865         LBUG();
1866         return err_serious(-EOPNOTSUPP);
1867 }
1868
1869 static int mdt_cp_callback(struct mdt_thread_info *info)
1870 {
1871         CERROR("cp callbacks should not happen on MDS\n");
1872         LBUG();
1873         return err_serious(-EOPNOTSUPP);
1874 }
1875
1876 /*
1877  * sec context handlers
1878  */
1879 static int mdt_sec_ctx_handle(struct mdt_thread_info *info)
1880 {
1881         int rc;
1882
1883         rc = mdt_handle_idmap(info);
1884
1885         if (unlikely(rc)) {
1886                 struct ptlrpc_request *req = mdt_info_req(info);
1887                 __u32                  opc;
1888
1889                 opc = lustre_msg_get_opc(req->rq_reqmsg);
1890                 if (opc == SEC_CTX_INIT || opc == SEC_CTX_INIT_CONT)
1891                         sptlrpc_svc_ctx_invalidate(req);
1892         }
1893
1894         OBD_FAIL_TIMEOUT(OBD_FAIL_SEC_CTX_HDL_PAUSE, obd_fail_val);
1895
1896         return rc;
1897 }
1898
1899 static struct mdt_object *mdt_obj(struct lu_object *o)
1900 {
1901         LASSERT(lu_device_is_mdt(o->lo_dev));
1902         return container_of0(o, struct mdt_object, mot_obj.mo_lu);
1903 }
1904
1905 struct mdt_object *mdt_object_find(const struct lu_env *env,
1906                                    struct mdt_device *d,
1907                                    const struct lu_fid *f)
1908 {
1909         struct lu_object *o;
1910         struct mdt_object *m;
1911         ENTRY;
1912
1913         CDEBUG(D_INFO, "Find object for "DFID"\n", PFID(f));
1914         o = lu_object_find(env, &d->mdt_md_dev.md_lu_dev, f, NULL);
1915         if (unlikely(IS_ERR(o)))
1916                 m = (struct mdt_object *)o;
1917         else
1918                 m = mdt_obj(o);
1919         RETURN(m);
1920 }
1921
1922 /**
1923  * Asyncronous commit for mdt device.
1924  *
1925  * Pass asynchonous commit call down the MDS stack.
1926  *
1927  * \param env environment
1928  * \param mdt the mdt device
1929  */
1930 static void mdt_device_commit_async(const struct lu_env *env,
1931                                     struct mdt_device *mdt)
1932 {
1933         struct dt_device *dt = mdt->mdt_bottom;
1934         int rc;
1935
1936         rc = dt->dd_ops->dt_commit_async(env, dt);
1937         if (unlikely(rc != 0))
1938                 CWARN("async commit start failed with rc = %d", rc);
1939 }
1940
1941 /**
1942  * Mark the lock as "synchonous".
1943  *
1944  * Mark the lock to deffer transaction commit to the unlock time.
1945  *
1946  * \param lock the lock to mark as "synchonous"
1947  *
1948  * \see mdt_is_lock_sync
1949  * \see mdt_save_lock
1950  */
1951 static inline void mdt_set_lock_sync(struct ldlm_lock *lock)
1952 {
1953         lock->l_ast_data = (void*)1;
1954 }
1955
1956 /**
1957  * Check whehter the lock "synchonous" or not.
1958  *
1959  * \param lock the lock to check
1960  * \retval 1 the lock is "synchonous"
1961  * \retval 0 the lock isn't "synchronous"
1962  *
1963  * \see mdt_set_lock_sync
1964  * \see mdt_save_lock
1965  */
1966 static inline int mdt_is_lock_sync(struct ldlm_lock *lock)
1967 {
1968         return lock->l_ast_data != NULL;
1969 }
1970
1971 /**
1972  * Blocking AST for mdt locks.
1973  *
1974  * Starts transaction commit if in case of COS lock conflict or
1975  * deffers such a commit to the mdt_save_lock.
1976  *
1977  * \param lock the lock which blocks a request or cancelling lock
1978  * \param desc unused
1979  * \param data unused
1980  * \param flag indicates whether this cancelling or blocking callback
1981  * \retval 0
1982  * \see ldlm_blocking_ast_nocheck
1983  */
1984 int mdt_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
1985                      void *data, int flag)
1986 {
1987         struct obd_device *obd = lock->l_resource->lr_namespace->ns_obd;
1988         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
1989         int rc;
1990         ENTRY;
1991
1992         if (flag == LDLM_CB_CANCELING)
1993                 RETURN(0);
1994         lock_res_and_lock(lock);
1995         if (lock->l_blocking_ast != mdt_blocking_ast) {
1996                 unlock_res_and_lock(lock);
1997                 RETURN(0);
1998         }
1999         if (mdt_cos_is_enabled(mdt) &&
2000             lock->l_req_mode & (LCK_PW | LCK_EX) &&
2001             lock->l_blocking_lock != NULL &&
2002             lock->l_client_cookie != lock->l_blocking_lock->l_client_cookie) {
2003                 mdt_set_lock_sync(lock);
2004         }
2005         rc = ldlm_blocking_ast_nocheck(lock);
2006
2007         /* There is no lock conflict if l_blocking_lock == NULL,
2008          * it indicates a blocking ast sent from ldlm_lock_decref_internal
2009          * when the last reference to a local lock was released */
2010         if (lock->l_req_mode == LCK_COS && lock->l_blocking_lock != NULL) {
2011                 struct lu_env env;
2012
2013                 rc = lu_env_init(&env, LCT_MD_THREAD);
2014                 if (unlikely(rc != 0))
2015                         CWARN("lu_env initialization failed with rc = %d,"
2016                               "cannot start asynchronous commit\n", rc);
2017                 else
2018                         mdt_device_commit_async(&env, mdt);
2019                 lu_env_fini(&env);
2020         }
2021         RETURN(rc);
2022 }
2023
2024 int mdt_object_lock(struct mdt_thread_info *info, struct mdt_object *o,
2025                     struct mdt_lock_handle *lh, __u64 ibits, int locality)
2026 {
2027         struct ldlm_namespace *ns = info->mti_mdt->mdt_namespace;
2028         ldlm_policy_data_t *policy = &info->mti_policy;
2029         struct ldlm_res_id *res_id = &info->mti_res_id;
2030         int rc;
2031         ENTRY;
2032
2033         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2034         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2035         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
2036         LASSERT(lh->mlh_type != MDT_NUL_LOCK);
2037
2038         if (mdt_object_exists(o) < 0) {
2039                 if (locality == MDT_CROSS_LOCK) {
2040                         /* cross-ref object fix */
2041                         ibits &= ~MDS_INODELOCK_UPDATE;
2042                         ibits |= MDS_INODELOCK_LOOKUP;
2043                 } else {
2044                         LASSERT(!(ibits & MDS_INODELOCK_UPDATE));
2045                         LASSERT(ibits & MDS_INODELOCK_LOOKUP);
2046                 }
2047                 /* No PDO lock on remote object */
2048                 LASSERT(lh->mlh_type != MDT_PDO_LOCK);
2049         }
2050
2051         if (lh->mlh_type == MDT_PDO_LOCK) {
2052                 /* check for exists after object is locked */
2053                 if (mdt_object_exists(o) == 0) {
2054                         /* Non-existent object shouldn't have PDO lock */
2055                         RETURN(-ESTALE);
2056                 } else {
2057                         /* Non-dir object shouldn't have PDO lock */
2058                         LASSERT(S_ISDIR(lu_object_attr(&o->mot_obj.mo_lu)));
2059                 }
2060         }
2061
2062         memset(policy, 0, sizeof(*policy));
2063         fid_build_reg_res_name(mdt_object_fid(o), res_id);
2064
2065         /*
2066          * Take PDO lock on whole directory and build correct @res_id for lock
2067          * on part of directory.
2068          */
2069         if (lh->mlh_pdo_hash != 0) {
2070                 LASSERT(lh->mlh_type == MDT_PDO_LOCK);
2071                 mdt_lock_pdo_mode(info, o, lh);
2072                 if (lh->mlh_pdo_mode != LCK_NL) {
2073                         /*
2074                          * Do not use LDLM_FL_LOCAL_ONLY for parallel lock, it
2075                          * is never going to be sent to client and we do not
2076                          * want it slowed down due to possible cancels.
2077                          */
2078                         policy->l_inodebits.bits = MDS_INODELOCK_UPDATE;
2079                         rc = mdt_fid_lock(ns, &lh->mlh_pdo_lh, lh->mlh_pdo_mode,
2080                                           policy, res_id, LDLM_FL_ATOMIC_CB,
2081                                           &info->mti_exp->exp_handle.h_cookie);
2082                         if (unlikely(rc))
2083                                 RETURN(rc);
2084                 }
2085
2086                 /*
2087                  * Finish res_id initializing by name hash marking part of
2088                  * directory which is taking modification.
2089                  */
2090                 res_id->name[LUSTRE_RES_ID_HSH_OFF] = lh->mlh_pdo_hash;
2091         }
2092
2093         policy->l_inodebits.bits = ibits;
2094
2095         /*
2096          * Use LDLM_FL_LOCAL_ONLY for this lock. We do not know yet if it is
2097          * going to be sent to client. If it is - mdt_intent_policy() path will
2098          * fix it up and turn FL_LOCAL flag off.
2099          */
2100         rc = mdt_fid_lock(ns, &lh->mlh_reg_lh, lh->mlh_reg_mode, policy,
2101                           res_id, LDLM_FL_LOCAL_ONLY | LDLM_FL_ATOMIC_CB,
2102                           &info->mti_exp->exp_handle.h_cookie);
2103         if (rc)
2104                 GOTO(out, rc);
2105
2106 out:
2107         if (rc)
2108                 mdt_object_unlock(info, o, lh, 1);
2109
2110
2111         RETURN(rc);
2112 }
2113
2114 /**
2115  * Save a lock within request object.
2116  *
2117  * Keep the lock referenced until whether client ACK or transaction
2118  * commit happens or release the lock immediately depending on input
2119  * parameters. If COS is ON, a write lock is converted to COS lock
2120  * before saving.
2121  *
2122  * \param info thead info object
2123  * \param h lock handle
2124  * \param mode lock mode
2125  * \param decref force immediate lock releasing
2126  */
2127 static
2128 void mdt_save_lock(struct mdt_thread_info *info, struct lustre_handle *h,
2129                    ldlm_mode_t mode, int decref)
2130 {
2131         ENTRY;
2132
2133         if (lustre_handle_is_used(h)) {
2134                 if (decref || !info->mti_has_trans ||
2135                     !(mode & (LCK_PW | LCK_EX))){
2136                         mdt_fid_unlock(h, mode);
2137                 } else {
2138                         struct mdt_device *mdt = info->mti_mdt;
2139                         struct ldlm_lock *lock = ldlm_handle2lock(h);
2140                         struct ptlrpc_request *req = mdt_info_req(info);
2141                         int no_ack = 0;
2142
2143                         LASSERTF(lock != NULL, "no lock for cookie "LPX64"\n",
2144                                  h->cookie);
2145                         CDEBUG(D_HA, "request = %p reply state = %p"
2146                                " transno = "LPD64"\n",
2147                                req, req->rq_reply_state, req->rq_transno);
2148                         if (mdt_cos_is_enabled(mdt)) {
2149                                 no_ack = 1;
2150                                 ldlm_lock_downgrade(lock, LCK_COS);
2151                                 mode = LCK_COS;
2152                         }
2153                         ptlrpc_save_lock(req, h, mode, no_ack);
2154                         if (mdt_is_lock_sync(lock)) {
2155                                 CDEBUG(D_HA, "found sync-lock,"
2156                                        " async commit started\n");
2157                                 mdt_device_commit_async(info->mti_env,
2158                                                         mdt);
2159                         }
2160                         LDLM_LOCK_PUT(lock);
2161                 }
2162                 h->cookie = 0ull;
2163         }
2164
2165         EXIT;
2166 }
2167
2168 /**
2169  * Unlock mdt object.
2170  *
2171  * Immeditely release the regular lock and the PDO lock or save the
2172  * lock in reqeuest and keep them referenced until client ACK or
2173  * transaction commit.
2174  *
2175  * \param info thread info object
2176  * \param o mdt object
2177  * \param h mdt lock handle referencing regular and PDO locks
2178  * \param decref force immediate lock releasing
2179  */
2180 void mdt_object_unlock(struct mdt_thread_info *info, struct mdt_object *o,
2181                        struct mdt_lock_handle *lh, int decref)
2182 {
2183         ENTRY;
2184
2185         mdt_save_lock(info, &lh->mlh_pdo_lh, lh->mlh_pdo_mode, decref);
2186         mdt_save_lock(info, &lh->mlh_reg_lh, lh->mlh_reg_mode, decref);
2187
2188         EXIT;
2189 }
2190
2191 struct mdt_object *mdt_object_find_lock(struct mdt_thread_info *info,
2192                                         const struct lu_fid *f,
2193                                         struct mdt_lock_handle *lh,
2194                                         __u64 ibits)
2195 {
2196         struct mdt_object *o;
2197
2198         o = mdt_object_find(info->mti_env, info->mti_mdt, f);
2199         if (!IS_ERR(o)) {
2200                 int rc;
2201
2202                 rc = mdt_object_lock(info, o, lh, ibits,
2203                                      MDT_LOCAL_LOCK);
2204                 if (rc != 0) {
2205                         mdt_object_put(info->mti_env, o);
2206                         o = ERR_PTR(rc);
2207                 }
2208         }
2209         return o;
2210 }
2211
2212 void mdt_object_unlock_put(struct mdt_thread_info * info,
2213                            struct mdt_object * o,
2214                            struct mdt_lock_handle *lh,
2215                            int decref)
2216 {
2217         mdt_object_unlock(info, o, lh, decref);
2218         mdt_object_put(info->mti_env, o);
2219 }
2220
2221 static struct mdt_handler *mdt_handler_find(__u32 opc,
2222                                             struct mdt_opc_slice *supported)
2223 {
2224         struct mdt_opc_slice *s;
2225         struct mdt_handler   *h;
2226
2227         h = NULL;
2228         for (s = supported; s->mos_hs != NULL; s++) {
2229                 if (s->mos_opc_start <= opc && opc < s->mos_opc_end) {
2230                         h = s->mos_hs + (opc - s->mos_opc_start);
2231                         if (likely(h->mh_opc != 0))
2232                                 LASSERT(h->mh_opc == opc);
2233                         else
2234                                 h = NULL; /* unsupported opc */
2235                         break;
2236                 }
2237         }
2238         return h;
2239 }
2240
2241 static int mdt_lock_resname_compat(struct mdt_device *m,
2242                                    struct ldlm_request *req)
2243 {
2244         /* XXX something... later. */
2245         return 0;
2246 }
2247
2248 static int mdt_lock_reply_compat(struct mdt_device *m, struct ldlm_reply *rep)
2249 {
2250         /* XXX something... later. */
2251         return 0;
2252 }
2253
2254 /*
2255  * Generic code handling requests that have struct mdt_body passed in:
2256  *
2257  *  - extract mdt_body from request and save it in @info, if present;
2258  *
2259  *  - create lu_object, corresponding to the fid in mdt_body, and save it in
2260  *  @info;
2261  *
2262  *  - if HABEO_CORPUS flag is set for this request type check whether object
2263  *  actually exists on storage (lu_object_exists()).
2264  *
2265  */
2266 static int mdt_body_unpack(struct mdt_thread_info *info, __u32 flags)
2267 {
2268         const struct mdt_body    *body;
2269         struct mdt_object        *obj;
2270         const struct lu_env      *env;
2271         struct req_capsule       *pill;
2272         int                       rc;
2273         ENTRY;
2274
2275         env = info->mti_env;
2276         pill = info->mti_pill;
2277
2278         body = info->mti_body = req_capsule_client_get(pill, &RMF_MDT_BODY);
2279         if (body == NULL)
2280                 RETURN(-EFAULT);
2281
2282         if (!(body->valid & OBD_MD_FLID))
2283                 RETURN(0);
2284
2285         if (!fid_is_sane(&body->fid1)) {
2286                 CERROR("Invalid fid: "DFID"\n", PFID(&body->fid1));
2287                 RETURN(-EINVAL);
2288         }
2289
2290         /*
2291          * Do not get size or any capa fields before we check that request
2292          * contains capa actually. There are some requests which do not, for
2293          * instance MDS_IS_SUBDIR.
2294          */
2295         if (req_capsule_has_field(pill, &RMF_CAPA1, RCL_CLIENT) &&
2296             req_capsule_get_size(pill, &RMF_CAPA1, RCL_CLIENT))
2297                 mdt_set_capainfo(info, 0, &body->fid1,
2298                                  req_capsule_client_get(pill, &RMF_CAPA1));
2299
2300         obj = mdt_object_find(env, info->mti_mdt, &body->fid1);
2301         if (!IS_ERR(obj)) {
2302                 if ((flags & HABEO_CORPUS) &&
2303                     !mdt_object_exists(obj)) {
2304                         mdt_object_put(env, obj);
2305                         /* for capability renew ENOENT will be handled in
2306                          * mdt_renew_capa */
2307                         if (body->valid & OBD_MD_FLOSSCAPA)
2308                                 rc = 0;
2309                         else
2310                                 rc = -ENOENT;
2311                 } else {
2312                         info->mti_object = obj;
2313                         rc = 0;
2314                 }
2315         } else
2316                 rc = PTR_ERR(obj);
2317
2318         RETURN(rc);
2319 }
2320
2321 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags)
2322 {
2323         struct req_capsule *pill = info->mti_pill;
2324         int rc;
2325         ENTRY;
2326
2327         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_CLIENT))
2328                 rc = mdt_body_unpack(info, flags);
2329         else
2330                 rc = 0;
2331
2332         if (rc == 0 && (flags & HABEO_REFERO)) {
2333                 struct mdt_device *mdt = info->mti_mdt;
2334
2335                 /* Pack reply. */
2336                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
2337                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
2338                                              mdt->mdt_max_mdsize);
2339                 if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
2340                         req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER,
2341                                              mdt->mdt_max_cookiesize);
2342
2343                 rc = req_capsule_server_pack(pill);
2344         }
2345         RETURN(rc);
2346 }
2347
2348 static int mdt_init_capa_ctxt(const struct lu_env *env, struct mdt_device *m)
2349 {
2350         struct md_device *next = m->mdt_child;
2351
2352         return next->md_ops->mdo_init_capa_ctxt(env, next,
2353                                                 m->mdt_opts.mo_mds_capa,
2354                                                 m->mdt_capa_timeout,
2355                                                 m->mdt_capa_alg,
2356                                                 m->mdt_capa_keys);
2357 }
2358
2359 /*
2360  * Invoke handler for this request opc. Also do necessary preprocessing
2361  * (according to handler ->mh_flags), and post-processing (setting of
2362  * ->last_{xid,committed}).
2363  */
2364 static int mdt_req_handle(struct mdt_thread_info *info,
2365                           struct mdt_handler *h, struct ptlrpc_request *req)
2366 {
2367         int   rc, serious = 0;
2368         __u32 flags;
2369
2370         ENTRY;
2371
2372         LASSERT(h->mh_act != NULL);
2373         LASSERT(h->mh_opc == lustre_msg_get_opc(req->rq_reqmsg));
2374         LASSERT(current->journal_info == NULL);
2375
2376         /*
2377          * Checking for various OBD_FAIL_$PREF_$OPC_NET codes. _Do_ not try
2378          * to put same checks into handlers like mdt_close(), mdt_reint(),
2379          * etc., without talking to mdt authors first. Checking same thing
2380          * there again is useless and returning 0 error wihtout packing reply
2381          * is buggy! Handlers either pack reply or return error.
2382          *
2383          * We return 0 here and do not send any reply in order to emulate
2384          * network failure. Do not send any reply in case any of NET related
2385          * fail_id has occured.
2386          */
2387         if (OBD_FAIL_CHECK_ORSET(h->mh_fail_id, OBD_FAIL_ONCE))
2388                 RETURN(0);
2389
2390         rc = 0;
2391         flags = h->mh_flags;
2392         LASSERT(ergo(flags & (HABEO_CORPUS|HABEO_REFERO), h->mh_fmt != NULL));
2393
2394         if (h->mh_fmt != NULL) {
2395                 req_capsule_set(info->mti_pill, h->mh_fmt);
2396                 rc = mdt_unpack_req_pack_rep(info, flags);
2397         }
2398
2399         if (rc == 0 && flags & MUTABOR &&
2400             req->rq_export->exp_connect_flags & OBD_CONNECT_RDONLY)
2401                 /* should it be rq_status? */
2402                 rc = -EROFS;
2403
2404         if (rc == 0 && flags & HABEO_CLAVIS) {
2405                 struct ldlm_request *dlm_req;
2406
2407                 LASSERT(h->mh_fmt != NULL);
2408
2409                 dlm_req = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
2410                 if (dlm_req != NULL) {
2411                         if (info->mti_mdt->mdt_opts.mo_compat_resname)
2412                                 rc = mdt_lock_resname_compat(info->mti_mdt,
2413                                                              dlm_req);
2414                         info->mti_dlm_req = dlm_req;
2415                 } else {
2416                         rc = -EFAULT;
2417                 }
2418         }
2419
2420         /* capability setting changed via /proc, needs reinitialize ctxt */
2421         if (info->mti_mdt && info->mti_mdt->mdt_capa_conf) {
2422                 mdt_init_capa_ctxt(info->mti_env, info->mti_mdt);
2423                 info->mti_mdt->mdt_capa_conf = 0;
2424         }
2425
2426         if (likely(rc == 0)) {
2427                 /*
2428                  * Process request, there can be two types of rc:
2429                  * 1) errors with msg unpack/pack, other failures outside the
2430                  * operation itself. This is counted as serious errors;
2431                  * 2) errors during fs operation, should be placed in rq_status
2432                  * only
2433                  */
2434                 rc = h->mh_act(info);
2435                 if (rc == 0 &&
2436                     !req->rq_no_reply && req->rq_reply_state == NULL) {
2437                         DEBUG_REQ(D_ERROR, req, "MDT \"handler\" %s did not "
2438                                   "pack reply and returned 0 error\n",
2439                                   h->mh_name);
2440                         LBUG();
2441                 }
2442                 serious = is_serious(rc);
2443                 rc = clear_serious(rc);
2444         } else
2445                 serious = 1;
2446
2447         req->rq_status = rc;
2448
2449         /*
2450          * ELDLM_* codes which > 0 should be in rq_status only as well as
2451          * all non-serious errors.
2452          */
2453         if (rc > 0 || !serious)
2454                 rc = 0;
2455
2456         LASSERT(current->journal_info == NULL);
2457
2458         if (rc == 0 && (flags & HABEO_CLAVIS) &&
2459             info->mti_mdt->mdt_opts.mo_compat_resname) {
2460                 struct ldlm_reply *dlmrep;
2461
2462                 dlmrep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
2463                 if (dlmrep != NULL)
2464                         rc = mdt_lock_reply_compat(info->mti_mdt, dlmrep);
2465         }
2466
2467         /* If we're DISCONNECTing, the mdt_export_data is already freed */
2468         if (likely(rc == 0 && h->mh_opc != MDS_DISCONNECT))
2469                 target_committed_to_req(req);
2470
2471         if (unlikely((lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY) &&
2472                      lustre_msg_get_transno(req->rq_reqmsg) == 0)) {
2473                 DEBUG_REQ(D_ERROR, req, "transno is 0 during REPLAY");
2474                 LBUG();
2475         }
2476
2477         target_send_reply(req, rc, info->mti_fail_id);
2478         RETURN(0);
2479 }
2480
2481 void mdt_lock_handle_init(struct mdt_lock_handle *lh)
2482 {
2483         lh->mlh_type = MDT_NUL_LOCK;
2484         lh->mlh_reg_lh.cookie = 0ull;
2485         lh->mlh_reg_mode = LCK_MINMODE;
2486         lh->mlh_pdo_lh.cookie = 0ull;
2487         lh->mlh_pdo_mode = LCK_MINMODE;
2488 }
2489
2490 void mdt_lock_handle_fini(struct mdt_lock_handle *lh)
2491 {
2492         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2493         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2494 }
2495
2496 /*
2497  * Initialize fields of struct mdt_thread_info. Other fields are left in
2498  * uninitialized state, because it's too expensive to zero out whole
2499  * mdt_thread_info (> 1K) on each request arrival.
2500  */
2501 static void mdt_thread_info_init(struct ptlrpc_request *req,
2502                                  struct mdt_thread_info *info)
2503 {
2504         int i;
2505         struct md_capainfo *ci;
2506
2507         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2508         info->mti_pill = &req->rq_pill;
2509
2510         /* lock handle */
2511         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
2512                 mdt_lock_handle_init(&info->mti_lh[i]);
2513
2514         /* mdt device: it can be NULL while CONNECT */
2515         if (req->rq_export) {
2516                 info->mti_mdt = mdt_dev(req->rq_export->exp_obd->obd_lu_dev);
2517                 info->mti_exp = req->rq_export;
2518         } else
2519                 info->mti_mdt = NULL;
2520         info->mti_env = req->rq_svc_thread->t_env;
2521         ci = md_capainfo(info->mti_env);
2522         memset(ci, 0, sizeof *ci);
2523         if (req->rq_export) {
2524                 if (exp_connect_rmtclient(req->rq_export))
2525                         ci->mc_auth = LC_ID_CONVERT;
2526                 else if (req->rq_export->exp_connect_flags &
2527                          OBD_CONNECT_MDS_CAPA)
2528                         ci->mc_auth = LC_ID_PLAIN;
2529                 else
2530                         ci->mc_auth = LC_ID_NONE;
2531         }
2532
2533         info->mti_fail_id = OBD_FAIL_MDS_ALL_REPLY_NET;
2534         info->mti_transno = lustre_msg_get_transno(req->rq_reqmsg);
2535
2536         memset(&info->mti_attr, 0, sizeof(info->mti_attr));
2537         info->mti_body = NULL;
2538         info->mti_object = NULL;
2539         info->mti_dlm_req = NULL;
2540         info->mti_has_trans = 0;
2541         info->mti_no_need_trans = 0;
2542         info->mti_cross_ref = 0;
2543         info->mti_opdata = 0;
2544
2545         /* To not check for split by default. */
2546         info->mti_spec.sp_ck_split = 0;
2547         info->mti_spec.no_create = 0;
2548 }
2549
2550 static void mdt_thread_info_fini(struct mdt_thread_info *info)
2551 {
2552         int i;
2553
2554         req_capsule_fini(info->mti_pill);
2555         if (info->mti_object != NULL) {
2556                 mdt_object_put(info->mti_env, info->mti_object);
2557                 info->mti_object = NULL;
2558         }
2559         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
2560                 mdt_lock_handle_fini(&info->mti_lh[i]);
2561         info->mti_env = NULL;
2562 }
2563
2564 static int mdt_filter_recovery_request(struct ptlrpc_request *req,
2565                                        struct obd_device *obd, int *process)
2566 {
2567         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2568         case MDS_CONNECT: /* This will never get here, but for completeness. */
2569         case OST_CONNECT: /* This will never get here, but for completeness. */
2570         case MDS_DISCONNECT:
2571         case OST_DISCONNECT:
2572                *process = 1;
2573                RETURN(0);
2574
2575         case MDS_CLOSE:
2576         case MDS_DONE_WRITING:
2577         case MDS_SYNC: /* used in unmounting */
2578         case OBD_PING:
2579         case MDS_REINT:
2580         case SEQ_QUERY:
2581         case FLD_QUERY:
2582         case LDLM_ENQUEUE:
2583                 *process = target_queue_recovery_request(req, obd);
2584                 RETURN(0);
2585
2586         default:
2587                 DEBUG_REQ(D_ERROR, req, "not permitted during recovery");
2588                 *process = -EAGAIN;
2589                 RETURN(0);
2590         }
2591 }
2592
2593 /*
2594  * Handle recovery. Return:
2595  *        +1: continue request processing;
2596  *       -ve: abort immediately with the given error code;
2597  *         0: send reply with error code in req->rq_status;
2598  */
2599 static int mdt_recovery(struct mdt_thread_info *info)
2600 {
2601         struct ptlrpc_request *req = mdt_info_req(info);
2602         int recovering;
2603         struct obd_device *obd;
2604
2605         ENTRY;
2606
2607         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2608         case MDS_CONNECT:
2609         case SEC_CTX_INIT:
2610         case SEC_CTX_INIT_CONT:
2611         case SEC_CTX_FINI:
2612                 {
2613 #if 0
2614                         int rc;
2615
2616                         rc = mdt_handle_idmap(info);
2617                         if (rc)
2618                                 RETURN(rc);
2619                         else
2620 #endif
2621                                 RETURN(+1);
2622                 }
2623         }
2624
2625         if (unlikely(req->rq_export == NULL)) {
2626                 CERROR("operation %d on unconnected MDS from %s\n",
2627                        lustre_msg_get_opc(req->rq_reqmsg),
2628                        libcfs_id2str(req->rq_peer));
2629                 /* FIXME: For CMD cleanup, when mds_B stop, the req from
2630                  * mds_A will get -ENOTCONN(especially for ping req),
2631                  * which will cause that mds_A deactive timeout, then when
2632                  * mds_A cleanup, the cleanup process will be suspended since
2633                  * deactive timeout is not zero.
2634                  */
2635                 req->rq_status = -ENOTCONN;
2636                 target_send_reply(req, -ENOTCONN, info->mti_fail_id);
2637                 RETURN(0);
2638         }
2639
2640         /* sanity check: if the xid matches, the request must be marked as a
2641          * resent or replayed */
2642         if (req_xid_is_last(req)) {
2643                 if (!(lustre_msg_get_flags(req->rq_reqmsg) &
2644                       (MSG_RESENT | MSG_REPLAY))) {
2645                         DEBUG_REQ(D_WARNING, req, "rq_xid "LPU64" matches last_xid, "
2646                                   "expected REPLAY or RESENT flag (%x)", req->rq_xid,
2647                                   lustre_msg_get_flags(req->rq_reqmsg));
2648                         LBUG();
2649                         req->rq_status = -ENOTCONN;
2650                         RETURN(-ENOTCONN);
2651                 }
2652         }
2653
2654         /* else: note the opposite is not always true; a RESENT req after a
2655          * failover will usually not match the last_xid, since it was likely
2656          * never committed. A REPLAYed request will almost never match the
2657          * last xid, however it could for a committed, but still retained,
2658          * open. */
2659
2660         obd = req->rq_export->exp_obd;
2661
2662         /* Check for aborted recovery... */
2663         spin_lock_bh(&obd->obd_processing_task_lock);
2664         recovering = obd->obd_recovering;
2665         spin_unlock_bh(&obd->obd_processing_task_lock);
2666         if (unlikely(recovering)) {
2667                 int rc;
2668                 int should_process;
2669                 DEBUG_REQ(D_INFO, req, "Got new replay");
2670                 rc = mdt_filter_recovery_request(req, obd, &should_process);
2671                 if (rc != 0 || !should_process)
2672                         RETURN(rc);
2673                 else if (should_process < 0) {
2674                         req->rq_status = should_process;
2675                         rc = ptlrpc_error(req);
2676                         RETURN(rc);
2677                 }
2678         }
2679         RETURN(+1);
2680 }
2681
2682 static int mdt_msg_check_version(struct lustre_msg *msg)
2683 {
2684         int rc;
2685
2686         switch (lustre_msg_get_opc(msg)) {
2687         case MDS_CONNECT:
2688         case MDS_DISCONNECT:
2689         case OBD_PING:
2690         case SEC_CTX_INIT:
2691         case SEC_CTX_INIT_CONT:
2692         case SEC_CTX_FINI:
2693                 rc = lustre_msg_check_version(msg, LUSTRE_OBD_VERSION);
2694                 if (rc)
2695                         CERROR("bad opc %u version %08x, expecting %08x\n",
2696                                lustre_msg_get_opc(msg),
2697                                lustre_msg_get_version(msg),
2698                                LUSTRE_OBD_VERSION);
2699                 break;
2700         case MDS_GETSTATUS:
2701         case MDS_GETATTR:
2702         case MDS_GETATTR_NAME:
2703         case MDS_STATFS:
2704         case MDS_READPAGE:
2705         case MDS_WRITEPAGE:
2706         case MDS_IS_SUBDIR:
2707         case MDS_REINT:
2708         case MDS_CLOSE:
2709         case MDS_DONE_WRITING:
2710         case MDS_PIN:
2711         case MDS_SYNC:
2712         case MDS_GETXATTR:
2713         case MDS_SETXATTR:
2714         case MDS_SET_INFO:
2715         case MDS_QUOTACHECK:
2716         case MDS_QUOTACTL:
2717         case QUOTA_DQACQ:
2718         case QUOTA_DQREL:
2719         case SEQ_QUERY:
2720         case FLD_QUERY:
2721                 rc = lustre_msg_check_version(msg, LUSTRE_MDS_VERSION);
2722                 if (rc)
2723                         CERROR("bad opc %u version %08x, expecting %08x\n",
2724                                lustre_msg_get_opc(msg),
2725                                lustre_msg_get_version(msg),
2726                                LUSTRE_MDS_VERSION);
2727                 break;
2728         case LDLM_ENQUEUE:
2729         case LDLM_CONVERT:
2730         case LDLM_BL_CALLBACK:
2731         case LDLM_CP_CALLBACK:
2732                 rc = lustre_msg_check_version(msg, LUSTRE_DLM_VERSION);
2733                 if (rc)
2734                         CERROR("bad opc %u version %08x, expecting %08x\n",
2735                                lustre_msg_get_opc(msg),
2736                                lustre_msg_get_version(msg),
2737                                LUSTRE_DLM_VERSION);
2738                 break;
2739         case OBD_LOG_CANCEL:
2740         case LLOG_ORIGIN_HANDLE_CREATE:
2741         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
2742         case LLOG_ORIGIN_HANDLE_READ_HEADER:
2743         case LLOG_ORIGIN_HANDLE_CLOSE:
2744         case LLOG_ORIGIN_HANDLE_DESTROY:
2745         case LLOG_ORIGIN_HANDLE_PREV_BLOCK:
2746         case LLOG_CATINFO:
2747                 rc = lustre_msg_check_version(msg, LUSTRE_LOG_VERSION);
2748                 if (rc)
2749                         CERROR("bad opc %u version %08x, expecting %08x\n",
2750                                lustre_msg_get_opc(msg),
2751                                lustre_msg_get_version(msg),
2752                                LUSTRE_LOG_VERSION);
2753                 break;
2754         default:
2755                 CERROR("MDS unknown opcode %d\n", lustre_msg_get_opc(msg));
2756                 rc = -ENOTSUPP;
2757         }
2758         return rc;
2759 }
2760
2761 static int mdt_handle0(struct ptlrpc_request *req,
2762                        struct mdt_thread_info *info,
2763                        struct mdt_opc_slice *supported)
2764 {
2765         struct mdt_handler *h;
2766         struct lustre_msg  *msg;
2767         int                 rc;
2768
2769         ENTRY;
2770
2771         if (OBD_FAIL_CHECK_ORSET(OBD_FAIL_MDS_ALL_REQUEST_NET, OBD_FAIL_ONCE))
2772                 RETURN(0);
2773
2774         LASSERT(current->journal_info == NULL);
2775
2776         msg = req->rq_reqmsg;
2777         rc = mdt_msg_check_version(msg);
2778         if (likely(rc == 0)) {
2779                 rc = mdt_recovery(info);
2780                 if (likely(rc == +1)) {
2781                         switch (lustre_msg_get_opc(msg)) {
2782                         case MDS_READPAGE:
2783                                 req->rq_bulk_read = 1;
2784                                 break;
2785                         case MDS_WRITEPAGE:
2786                                 req->rq_bulk_write = 1;
2787                                 break;
2788                         }
2789
2790                         h = mdt_handler_find(lustre_msg_get_opc(msg),
2791                                              supported);
2792                         if (likely(h != NULL)) {
2793                                 rc = mdt_req_handle(info, h, req);
2794                         } else {
2795                                 CERROR("The unsupported opc: 0x%x\n", lustre_msg_get_opc(msg) );
2796                                 req->rq_status = -ENOTSUPP;
2797                                 rc = ptlrpc_error(req);
2798                                 RETURN(rc);
2799                         }
2800                 }
2801         } else
2802                 CERROR(LUSTRE_MDT_NAME" drops mal-formed request\n");
2803         RETURN(rc);
2804 }
2805
2806 /*
2807  * MDT handler function called by ptlrpc service thread when request comes.
2808  *
2809  * XXX common "target" functionality should be factored into separate module
2810  * shared by mdt, ost and stand-alone services like fld.
2811  */
2812 static int mdt_handle_common(struct ptlrpc_request *req,
2813                              struct mdt_opc_slice *supported)
2814 {
2815         struct lu_env          *env;
2816         struct mdt_thread_info *info;
2817         int                     rc;
2818         ENTRY;
2819
2820         env = req->rq_svc_thread->t_env;
2821         LASSERT(env != NULL);
2822         LASSERT(env->le_ses != NULL);
2823         LASSERT(env->le_ctx.lc_thread == req->rq_svc_thread);
2824         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
2825         LASSERT(info != NULL);
2826
2827         mdt_thread_info_init(req, info);
2828
2829         rc = mdt_handle0(req, info, supported);
2830
2831         mdt_thread_info_fini(info);
2832         RETURN(rc);
2833 }
2834
2835 /*
2836  * This is called from recovery code as handler of _all_ RPC types, FLD and SEQ
2837  * as well.
2838  */
2839 int mdt_recovery_handle(struct ptlrpc_request *req)
2840 {
2841         int rc;
2842         ENTRY;
2843
2844         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2845         case FLD_QUERY:
2846                 rc = mdt_handle_common(req, mdt_fld_handlers);
2847                 break;
2848         case SEQ_QUERY:
2849                 rc = mdt_handle_common(req, mdt_seq_handlers);
2850                 break;
2851         default:
2852                 rc = mdt_handle_common(req, mdt_regular_handlers);
2853                 break;
2854         }
2855
2856         RETURN(rc);
2857 }
2858
2859 static int mdt_regular_handle(struct ptlrpc_request *req)
2860 {
2861         return mdt_handle_common(req, mdt_regular_handlers);
2862 }
2863
2864 static int mdt_readpage_handle(struct ptlrpc_request *req)
2865 {
2866         return mdt_handle_common(req, mdt_readpage_handlers);
2867 }
2868
2869 static int mdt_xmds_handle(struct ptlrpc_request *req)
2870 {
2871         return mdt_handle_common(req, mdt_xmds_handlers);
2872 }
2873
2874 static int mdt_mdsc_handle(struct ptlrpc_request *req)
2875 {
2876         return mdt_handle_common(req, mdt_seq_handlers);
2877 }
2878
2879 static int mdt_mdss_handle(struct ptlrpc_request *req)
2880 {
2881         return mdt_handle_common(req, mdt_seq_handlers);
2882 }
2883
2884 static int mdt_dtss_handle(struct ptlrpc_request *req)
2885 {
2886         return mdt_handle_common(req, mdt_seq_handlers);
2887 }
2888
2889 static int mdt_fld_handle(struct ptlrpc_request *req)
2890 {
2891         return mdt_handle_common(req, mdt_fld_handlers);
2892 }
2893
2894 enum mdt_it_code {
2895         MDT_IT_OPEN,
2896         MDT_IT_OCREAT,
2897         MDT_IT_CREATE,
2898         MDT_IT_GETATTR,
2899         MDT_IT_READDIR,
2900         MDT_IT_LOOKUP,
2901         MDT_IT_UNLINK,
2902         MDT_IT_TRUNC,
2903         MDT_IT_GETXATTR,
2904         MDT_IT_NR
2905 };
2906
2907 static int mdt_intent_getattr(enum mdt_it_code opcode,
2908                               struct mdt_thread_info *info,
2909                               struct ldlm_lock **,
2910                               int);
2911 static int mdt_intent_reint(enum mdt_it_code opcode,
2912                             struct mdt_thread_info *info,
2913                             struct ldlm_lock **,
2914                             int);
2915
2916 static struct mdt_it_flavor {
2917         const struct req_format *it_fmt;
2918         __u32                    it_flags;
2919         int                    (*it_act)(enum mdt_it_code ,
2920                                          struct mdt_thread_info *,
2921                                          struct ldlm_lock **,
2922                                          int);
2923         long                     it_reint;
2924 } mdt_it_flavor[] = {
2925         [MDT_IT_OPEN]     = {
2926                 .it_fmt   = &RQF_LDLM_INTENT,
2927                 /*.it_flags = HABEO_REFERO,*/
2928                 .it_flags = 0,
2929                 .it_act   = mdt_intent_reint,
2930                 .it_reint = REINT_OPEN
2931         },
2932         [MDT_IT_OCREAT]   = {
2933                 .it_fmt   = &RQF_LDLM_INTENT,
2934                 .it_flags = MUTABOR,
2935                 .it_act   = mdt_intent_reint,
2936                 .it_reint = REINT_OPEN
2937         },
2938         [MDT_IT_CREATE]   = {
2939                 .it_fmt   = &RQF_LDLM_INTENT,
2940                 .it_flags = MUTABOR,
2941                 .it_act   = mdt_intent_reint,
2942                 .it_reint = REINT_CREATE
2943         },
2944         [MDT_IT_GETATTR]  = {
2945                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
2946                 .it_flags = HABEO_REFERO,
2947                 .it_act   = mdt_intent_getattr
2948         },
2949         [MDT_IT_READDIR]  = {
2950                 .it_fmt   = NULL,
2951                 .it_flags = 0,
2952                 .it_act   = NULL
2953         },
2954         [MDT_IT_LOOKUP]   = {
2955                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
2956                 .it_flags = HABEO_REFERO,
2957                 .it_act   = mdt_intent_getattr
2958         },
2959         [MDT_IT_UNLINK]   = {
2960                 .it_fmt   = &RQF_LDLM_INTENT_UNLINK,
2961                 .it_flags = MUTABOR,
2962                 .it_act   = NULL,
2963                 .it_reint = REINT_UNLINK
2964         },
2965         [MDT_IT_TRUNC]    = {
2966                 .it_fmt   = NULL,
2967                 .it_flags = MUTABOR,
2968                 .it_act   = NULL
2969         },
2970         [MDT_IT_GETXATTR] = {
2971                 .it_fmt   = NULL,
2972                 .it_flags = 0,
2973                 .it_act   = NULL
2974         }
2975 };
2976
2977 int mdt_intent_lock_replace(struct mdt_thread_info *info,
2978                             struct ldlm_lock **lockp,
2979                             struct ldlm_lock *new_lock,
2980                             struct mdt_lock_handle *lh,
2981                             int flags)
2982 {
2983         struct ptlrpc_request  *req = mdt_info_req(info);
2984         struct ldlm_lock       *lock = *lockp;
2985
2986         /*
2987          * Get new lock only for cases when possible resent did not find any
2988          * lock.
2989          */
2990         if (new_lock == NULL)
2991                 new_lock = ldlm_handle2lock_long(&lh->mlh_reg_lh, 0);
2992
2993         if (new_lock == NULL && (flags & LDLM_FL_INTENT_ONLY)) {
2994                 lh->mlh_reg_lh.cookie = 0;
2995                 RETURN(0);
2996         }
2997
2998         LASSERTF(new_lock != NULL,
2999                  "lockh "LPX64"\n", lh->mlh_reg_lh.cookie);
3000
3001         /*
3002          * If we've already given this lock to a client once, then we should
3003          * have no readers or writers.  Otherwise, we should have one reader
3004          * _or_ writer ref (which will be zeroed below) before returning the
3005          * lock to a client.
3006          */
3007         if (new_lock->l_export == req->rq_export) {
3008                 LASSERT(new_lock->l_readers + new_lock->l_writers == 0);
3009         } else {
3010                 LASSERT(new_lock->l_export == NULL);
3011                 LASSERT(new_lock->l_readers + new_lock->l_writers == 1);
3012         }
3013
3014         *lockp = new_lock;
3015
3016         if (new_lock->l_export == req->rq_export) {
3017                 /*
3018                  * Already gave this to the client, which means that we
3019                  * reconstructed a reply.
3020                  */
3021                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) &
3022                         MSG_RESENT);
3023                 lh->mlh_reg_lh.cookie = 0;
3024                 RETURN(ELDLM_LOCK_REPLACED);
3025         }
3026
3027         /*
3028          * Fixup the lock to be given to the client.
3029          */
3030         lock_res_and_lock(new_lock);
3031         /* Zero new_lock->l_readers and new_lock->l_writers without triggering
3032          * possible blocking AST. */
3033         while (new_lock->l_readers > 0) {
3034                 lu_ref_del(&new_lock->l_reference, "reader", new_lock);
3035                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3036                 new_lock->l_readers--;
3037         }
3038         while (new_lock->l_writers > 0) {
3039                 lu_ref_del(&new_lock->l_reference, "writer", new_lock);
3040                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3041                 new_lock->l_writers--;
3042         }
3043
3044         new_lock->l_export = class_export_get(req->rq_export);
3045         new_lock->l_blocking_ast = lock->l_blocking_ast;
3046         new_lock->l_completion_ast = lock->l_completion_ast;
3047         new_lock->l_remote_handle = lock->l_remote_handle;
3048         new_lock->l_flags &= ~LDLM_FL_LOCAL;
3049
3050         unlock_res_and_lock(new_lock);
3051
3052         lustre_hash_add(new_lock->l_export->exp_lock_hash,
3053                         &new_lock->l_remote_handle,
3054                         &new_lock->l_exp_hash);
3055
3056         LDLM_LOCK_RELEASE(new_lock);
3057         lh->mlh_reg_lh.cookie = 0;
3058
3059         RETURN(ELDLM_LOCK_REPLACED);
3060 }
3061
3062 static void mdt_intent_fixup_resent(struct mdt_thread_info *info,
3063                                     struct ldlm_lock *new_lock,
3064                                     struct ldlm_lock **old_lock,
3065                                     struct mdt_lock_handle *lh)
3066 {
3067         struct ptlrpc_request  *req = mdt_info_req(info);
3068         struct obd_export      *exp = req->rq_export;
3069         struct lustre_handle    remote_hdl;
3070         struct ldlm_request    *dlmreq;
3071         struct ldlm_lock       *lock;
3072
3073         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT))
3074                 return;
3075
3076         dlmreq = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
3077         remote_hdl = dlmreq->lock_handle[0];
3078
3079         lock = lustre_hash_lookup(exp->exp_lock_hash, &remote_hdl);
3080         if (lock) {
3081                 if (lock != new_lock) {
3082                         lh->mlh_reg_lh.cookie = lock->l_handle.h_cookie;
3083                         lh->mlh_reg_mode = lock->l_granted_mode;
3084
3085                         LDLM_DEBUG(lock, "Restoring lock cookie");
3086                         DEBUG_REQ(D_DLMTRACE, req,
3087                                   "restoring lock cookie "LPX64,
3088                                   lh->mlh_reg_lh.cookie);
3089                         if (old_lock)
3090                                 *old_lock = LDLM_LOCK_GET(lock);
3091                         lh_put(exp->exp_lock_hash, &lock->l_exp_hash);
3092                         return;
3093                 }
3094
3095                 lh_put(exp->exp_lock_hash, &lock->l_exp_hash);
3096         }
3097
3098         /*
3099          * If the xid matches, then we know this is a resent request, and allow
3100          * it. (It's probably an OPEN, for which we don't send a lock.
3101          */
3102         if (req_xid_is_last(req))
3103                 return;
3104
3105         /*
3106          * This remote handle isn't enqueued, so we never received or processed
3107          * this request.  Clear MSG_RESENT, because it can be handled like any
3108          * normal request now.
3109          */
3110         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
3111
3112         DEBUG_REQ(D_DLMTRACE, req, "no existing lock with rhandle "LPX64,
3113                   remote_hdl.cookie);
3114 }
3115
3116 static int mdt_intent_getattr(enum mdt_it_code opcode,
3117                               struct mdt_thread_info *info,
3118                               struct ldlm_lock **lockp,
3119                               int flags)
3120 {
3121         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3122         struct ldlm_lock       *new_lock = NULL;
3123         __u64                   child_bits;
3124         struct ldlm_reply      *ldlm_rep;
3125         struct ptlrpc_request  *req;
3126         struct mdt_body        *reqbody;
3127         struct mdt_body        *repbody;
3128         int                     rc;
3129         ENTRY;
3130
3131         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
3132         LASSERT(reqbody);
3133
3134         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
3135         LASSERT(repbody);
3136
3137         info->mti_spec.sp_ck_split = !!(reqbody->valid & OBD_MD_FLCKSPLIT);
3138         info->mti_cross_ref = !!(reqbody->valid & OBD_MD_FLCROSSREF);
3139         repbody->eadatasize = 0;
3140         repbody->aclsize = 0;
3141
3142         switch (opcode) {
3143         case MDT_IT_LOOKUP:
3144                 child_bits = MDS_INODELOCK_LOOKUP;
3145                 break;
3146         case MDT_IT_GETATTR:
3147                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
3148                 break;
3149         default:
3150                 CERROR("Unhandled till now");
3151                 GOTO(out_shrink, rc = -EINVAL);
3152         }
3153
3154         rc = mdt_init_ucred(info, reqbody);
3155         if (rc)
3156                 GOTO(out_shrink, rc);
3157
3158         req = info->mti_pill->rc_req;
3159         ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3160         mdt_set_disposition(info, ldlm_rep, DISP_IT_EXECD);
3161
3162         /* Get lock from request for possible resent case. */
3163         mdt_intent_fixup_resent(info, *lockp, &new_lock, lhc);
3164
3165         ldlm_rep->lock_policy_res2 =
3166                 mdt_getattr_name_lock(info, lhc, child_bits, ldlm_rep);
3167
3168         if (mdt_get_disposition(ldlm_rep, DISP_LOOKUP_NEG))
3169                 ldlm_rep->lock_policy_res2 = 0;
3170         if (!mdt_get_disposition(ldlm_rep, DISP_LOOKUP_POS) ||
3171             ldlm_rep->lock_policy_res2) {
3172                 lhc->mlh_reg_lh.cookie = 0ull;
3173                 GOTO(out_ucred, rc = ELDLM_LOCK_ABORTED);
3174         }
3175
3176         rc = mdt_intent_lock_replace(info, lockp, new_lock, lhc, flags);
3177         EXIT;
3178 out_ucred:
3179         mdt_exit_ucred(info);
3180 out_shrink:
3181         mdt_shrink_reply(info);
3182         return rc;
3183 }
3184
3185 static int mdt_intent_reint(enum mdt_it_code opcode,
3186                             struct mdt_thread_info *info,
3187                             struct ldlm_lock **lockp,
3188                             int flags)
3189 {
3190         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3191         struct ldlm_reply      *rep = NULL;
3192         long                    opc;
3193         int                     rc;
3194
3195         static const struct req_format *intent_fmts[REINT_MAX] = {
3196                 [REINT_CREATE]  = &RQF_LDLM_INTENT_CREATE,
3197                 [REINT_OPEN]    = &RQF_LDLM_INTENT_OPEN
3198         };
3199
3200         ENTRY;
3201
3202         opc = mdt_reint_opcode(info, intent_fmts);
3203         if (opc < 0)
3204                 RETURN(opc);
3205
3206         if (mdt_it_flavor[opcode].it_reint != opc) {
3207                 CERROR("Reint code %ld doesn't match intent: %d\n",
3208                        opc, opcode);
3209                 RETURN(err_serious(-EPROTO));
3210         }
3211
3212         /* Get lock from request for possible resent case. */
3213         mdt_intent_fixup_resent(info, *lockp, NULL, lhc);
3214
3215         rc = mdt_reint_internal(info, lhc, opc);
3216
3217         /* Check whether the reply has been packed successfully. */
3218         if (mdt_info_req(info)->rq_repmsg != NULL)
3219                 rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3220         if (rep == NULL)
3221                 RETURN(err_serious(-EFAULT));
3222
3223         /* MDC expects this in any case */
3224         if (rc != 0)
3225                 mdt_set_disposition(info, rep, DISP_LOOKUP_EXECD);
3226
3227         /* Cross-ref case, the lock should be returned to the client */
3228         if (rc == -EREMOTE) {
3229                 LASSERT(lustre_handle_is_used(&lhc->mlh_reg_lh));
3230                 rep->lock_policy_res2 = 0;
3231                 rc = mdt_intent_lock_replace(info, lockp, NULL, lhc, flags);
3232                 RETURN(rc);
3233         }
3234         rep->lock_policy_res2 = clear_serious(rc);
3235
3236         lhc->mlh_reg_lh.cookie = 0ull;
3237         if (rc == -ENOTCONN || rc == -ENODEV) {
3238                 /*
3239                  * If it is the disconnect error (ENODEV & ENOCONN), the error
3240                  * will be returned by rq_status, and client at ptlrpc layer
3241                  * will detect this, then disconnect, reconnect the import
3242                  * immediately, instead of impacting the following the rpc.
3243                  */
3244                 RETURN(rc);
3245         } else {
3246                 /*
3247                  * For other cases, the error will be returned by intent.
3248                  * and client will retrieve the result from intent.
3249                  */
3250                  /*
3251                   * FIXME: when open lock is finished, that should be
3252                   * checked here.
3253                   */
3254                 RETURN(ELDLM_LOCK_ABORTED);
3255         }
3256 }
3257
3258 static int mdt_intent_code(long itcode)
3259 {
3260         int rc;
3261
3262         switch(itcode) {
3263         case IT_OPEN:
3264                 rc = MDT_IT_OPEN;
3265                 break;
3266         case IT_OPEN|IT_CREAT:
3267                 rc = MDT_IT_OCREAT;
3268                 break;
3269         case IT_CREAT:
3270                 rc = MDT_IT_CREATE;
3271                 break;
3272         case IT_READDIR:
3273                 rc = MDT_IT_READDIR;
3274                 break;
3275         case IT_GETATTR:
3276                 rc = MDT_IT_GETATTR;
3277                 break;
3278         case IT_LOOKUP:
3279                 rc = MDT_IT_LOOKUP;
3280                 break;
3281         case IT_UNLINK:
3282                 rc = MDT_IT_UNLINK;
3283                 break;
3284         case IT_TRUNC:
3285                 rc = MDT_IT_TRUNC;
3286                 break;
3287         case IT_GETXATTR:
3288                 rc = MDT_IT_GETXATTR;
3289                 break;
3290         default:
3291                 CERROR("Unknown intent opcode: %ld\n", itcode);
3292                 rc = -EINVAL;
3293                 break;
3294         }
3295         return rc;
3296 }
3297
3298 static int mdt_intent_opc(long itopc, struct mdt_thread_info *info,
3299                           struct ldlm_lock **lockp, int flags)
3300 {
3301         struct req_capsule   *pill;
3302         struct mdt_it_flavor *flv;
3303         int opc;
3304         int rc;
3305         ENTRY;
3306
3307         opc = mdt_intent_code(itopc);
3308         if (opc < 0)
3309                 RETURN(-EINVAL);
3310
3311         pill = info->mti_pill;
3312         flv  = &mdt_it_flavor[opc];
3313
3314         if (flv->it_fmt != NULL)
3315                 req_capsule_extend(pill, flv->it_fmt);
3316
3317         rc = mdt_unpack_req_pack_rep(info, flv->it_flags);
3318         if (rc == 0) {
3319                 struct ptlrpc_request *req = mdt_info_req(info);
3320                 if (flv->it_flags & MUTABOR &&
3321                     req->rq_export->exp_connect_flags & OBD_CONNECT_RDONLY)
3322                         RETURN(-EROFS);
3323         }
3324         if (rc == 0 && flv->it_act != NULL) {
3325                 /* execute policy */
3326                 rc = flv->it_act(opc, info, lockp, flags);
3327         } else {
3328                 rc = -EOPNOTSUPP;
3329         }
3330         RETURN(rc);
3331 }
3332
3333 static int mdt_intent_policy(struct ldlm_namespace *ns,
3334                              struct ldlm_lock **lockp, void *req_cookie,
3335                              ldlm_mode_t mode, int flags, void *data)
3336 {
3337         struct mdt_thread_info *info;
3338         struct ptlrpc_request  *req  =  req_cookie;
3339         struct ldlm_intent     *it;
3340         struct req_capsule     *pill;
3341         int rc;
3342
3343         ENTRY;
3344
3345         LASSERT(req != NULL);
3346
3347         info = lu_context_key_get(&req->rq_svc_thread->t_env->le_ctx,
3348                                   &mdt_thread_key);
3349         LASSERT(info != NULL);
3350         pill = info->mti_pill;
3351         LASSERT(pill->rc_req == req);
3352
3353         if (req->rq_reqmsg->lm_bufcount > DLM_INTENT_IT_OFF) {
3354                 req_capsule_extend(pill, &RQF_LDLM_INTENT);
3355                 it = req_capsule_client_get(pill, &RMF_LDLM_INTENT);
3356                 if (it != NULL) {
3357                         const struct ldlm_request *dlmreq;
3358                         __u64 req_bits;
3359
3360                         rc = mdt_intent_opc(it->opc, info, lockp, flags);
3361                         if (rc == 0)
3362                                 rc = ELDLM_OK;
3363
3364                         /*
3365                          * Lock without inodebits makes no sense and will oops
3366                          * later in ldlm. Let's check it now to see if we have
3367                          * wrong lock from client or bits get corrupted
3368                          * somewhere in mdt_intent_opc().
3369                          */
3370                         dlmreq = info->mti_dlm_req;
3371                         req_bits = dlmreq->lock_desc.l_policy_data.l_inodebits.bits;
3372                         LASSERT(req_bits != 0);
3373
3374                 } else
3375                         rc = err_serious(-EFAULT);
3376         } else {
3377                 /* No intent was provided */
3378                 LASSERT(pill->rc_fmt == &RQF_LDLM_ENQUEUE);
3379                 rc = req_capsule_server_pack(pill);
3380                 if (rc)
3381                         rc = err_serious(rc);
3382         }
3383         RETURN(rc);
3384 }
3385
3386 /*
3387  * Seq wrappers
3388  */
3389 static void mdt_seq_adjust(const struct lu_env *env,
3390                           struct mdt_device *m, int lost)
3391 {
3392         struct md_site *ms = mdt_md_site(m);
3393         struct lu_seq_range out;
3394         ENTRY;
3395
3396         LASSERT(ms && ms->ms_server_seq);
3397         LASSERT(lost >= 0);
3398         /* get extra seq from seq_server, moving it's range up */
3399         while (lost-- > 0) {
3400                 seq_server_alloc_meta(ms->ms_server_seq, NULL, &out, env);
3401         }
3402         EXIT;
3403 }
3404
3405 static int mdt_seq_fini(const struct lu_env *env,
3406                         struct mdt_device *m)
3407 {
3408         struct md_site *ms = mdt_md_site(m);
3409         ENTRY;
3410
3411         if (ms != NULL) {
3412                 if (ms->ms_server_seq) {
3413                         seq_server_fini(ms->ms_server_seq, env);
3414                         OBD_FREE_PTR(ms->ms_server_seq);
3415                         ms->ms_server_seq = NULL;
3416         }
3417
3418                 if (ms->ms_control_seq) {
3419                         seq_server_fini(ms->ms_control_seq, env);
3420                         OBD_FREE_PTR(ms->ms_control_seq);
3421                         ms->ms_control_seq = NULL;
3422         }
3423
3424                 if (ms->ms_client_seq) {
3425                         seq_client_fini(ms->ms_client_seq);
3426                         OBD_FREE_PTR(ms->ms_client_seq);
3427                         ms->ms_client_seq = NULL;
3428                 }
3429         }
3430
3431         RETURN(0);
3432 }
3433
3434 static int mdt_seq_init(const struct lu_env *env,
3435                         const char *uuid,
3436                         struct mdt_device *m)
3437 {
3438         struct md_site *ms;
3439         char *prefix;
3440         int rc;
3441         ENTRY;
3442
3443         ms = mdt_md_site(m);
3444
3445         /*
3446          * This is sequence-controller node. Init seq-controller server on local
3447          * MDT.
3448          */
3449         if (ms->ms_node_id == 0) {
3450                 LASSERT(ms->ms_control_seq == NULL);
3451
3452                 OBD_ALLOC_PTR(ms->ms_control_seq);
3453                 if (ms->ms_control_seq == NULL)
3454                         RETURN(-ENOMEM);
3455
3456                 rc = seq_server_init(ms->ms_control_seq,
3457                                      m->mdt_bottom, uuid,
3458                                      LUSTRE_SEQ_CONTROLLER,
3459                                      ms,
3460                                      env);
3461
3462                 if (rc)
3463                         GOTO(out_seq_fini, rc);
3464
3465                 OBD_ALLOC_PTR(ms->ms_client_seq);
3466                 if (ms->ms_client_seq == NULL)
3467                         GOTO(out_seq_fini, rc = -ENOMEM);
3468
3469                 OBD_ALLOC(prefix, MAX_OBD_NAME + 5);
3470                 if (prefix == NULL) {
3471                         OBD_FREE_PTR(ms->ms_client_seq);
3472                         GOTO(out_seq_fini, rc = -ENOMEM);
3473                 }
3474
3475                 snprintf(prefix, MAX_OBD_NAME + 5, "ctl-%s",
3476                          uuid);
3477
3478                 /*
3479                  * Init seq-controller client after seq-controller server is
3480                  * ready. Pass ms->ms_control_seq to it for direct talking.
3481                  */
3482                 rc = seq_client_init(ms->ms_client_seq, NULL,
3483                                      LUSTRE_SEQ_METADATA, prefix,
3484                                      ms->ms_control_seq);
3485                 OBD_FREE(prefix, MAX_OBD_NAME + 5);
3486
3487                 if (rc)
3488                         GOTO(out_seq_fini, rc);
3489         }
3490
3491         /* Init seq-server on local MDT */
3492         LASSERT(ms->ms_server_seq == NULL);
3493
3494         OBD_ALLOC_PTR(ms->ms_server_seq);
3495         if (ms->ms_server_seq == NULL)
3496                 GOTO(out_seq_fini, rc = -ENOMEM);
3497
3498         rc = seq_server_init(ms->ms_server_seq,
3499                              m->mdt_bottom, uuid,
3500                              LUSTRE_SEQ_SERVER,
3501                              ms,
3502                              env);
3503         if (rc)
3504                 GOTO(out_seq_fini, rc = -ENOMEM);
3505
3506         /* Assign seq-controller client to local seq-server. */
3507         if (ms->ms_node_id == 0) {
3508                 LASSERT(ms->ms_client_seq != NULL);
3509
3510                 rc = seq_server_set_cli(ms->ms_server_seq,
3511                                         ms->ms_client_seq,
3512                                         env);
3513         }
3514
3515         EXIT;
3516 out_seq_fini:
3517         if (rc)
3518                 mdt_seq_fini(env, m);
3519
3520         return rc;
3521 }
3522 /*
3523  * Init client sequence manager which is used by local MDS to talk to sequence
3524  * controller on remote node.
3525  */
3526 static int mdt_seq_init_cli(const struct lu_env *env,
3527                             struct mdt_device *m,
3528                             struct lustre_cfg *cfg)
3529 {
3530         struct md_site    *ms = mdt_md_site(m);
3531         struct obd_device *mdc;
3532         struct obd_uuid   *uuidp, *mdcuuidp;
3533         char              *uuid_str, *mdc_uuid_str;
3534         int                rc;
3535         int                index;
3536         struct mdt_thread_info *info;
3537         char *p, *index_string = lustre_cfg_string(cfg, 2);
3538         ENTRY;
3539
3540         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
3541         uuidp = &info->mti_u.uuid[0];
3542         mdcuuidp = &info->mti_u.uuid[1];
3543
3544         LASSERT(index_string);
3545
3546         index = simple_strtol(index_string, &p, 10);
3547         if (*p) {
3548                 CERROR("Invalid index in lustre_cgf, offset 2\n");
3549                 RETURN(-EINVAL);
3550         }
3551
3552         /* check if this is adding the first MDC and controller is not yet
3553          * initialized. */
3554         if (index != 0 || ms->ms_client_seq)
3555                 RETURN(0);
3556
3557         uuid_str = lustre_cfg_string(cfg, 1);
3558         mdc_uuid_str = lustre_cfg_string(cfg, 4);
3559         obd_str2uuid(uuidp, uuid_str);
3560         obd_str2uuid(mdcuuidp, mdc_uuid_str);
3561
3562         mdc = class_find_client_obd(uuidp, LUSTRE_MDC_NAME, mdcuuidp);
3563         if (!mdc) {
3564                 CERROR("can't find controller MDC by uuid %s\n",
3565                        uuid_str);
3566                 rc = -ENOENT;
3567         } else if (!mdc->obd_set_up) {
3568                 CERROR("target %s not set up\n", mdc->obd_name);
3569                 rc = -EINVAL;
3570         } else {
3571                 LASSERT(ms->ms_control_exp);
3572                 OBD_ALLOC_PTR(ms->ms_client_seq);
3573                 if (ms->ms_client_seq != NULL) {
3574                         char *prefix;
3575
3576                         OBD_ALLOC(prefix, MAX_OBD_NAME + 5);
3577                         if (!prefix)
3578                                 RETURN(-ENOMEM);
3579
3580                         snprintf(prefix, MAX_OBD_NAME + 5, "ctl-%s",
3581                                  mdc->obd_name);
3582
3583                         rc = seq_client_init(ms->ms_client_seq,
3584                                              ms->ms_control_exp,
3585                                              LUSTRE_SEQ_METADATA,
3586                                              prefix, NULL);
3587                         OBD_FREE(prefix, MAX_OBD_NAME + 5);
3588                 } else
3589                         rc = -ENOMEM;
3590
3591                 if (rc)
3592                         RETURN(rc);
3593
3594                 LASSERT(ms->ms_server_seq != NULL);
3595                 rc = seq_server_set_cli(ms->ms_server_seq, ms->ms_client_seq,
3596                                         env);
3597         }
3598
3599         RETURN(rc);
3600 }
3601
3602 static void mdt_seq_fini_cli(struct mdt_device *m)
3603 {
3604         struct md_site *ms;
3605
3606         ENTRY;
3607
3608         ms = mdt_md_site(m);
3609
3610         if (ms != NULL) {
3611                 if (ms->ms_server_seq)
3612                         seq_server_set_cli(ms->ms_server_seq,
3613                                    NULL, NULL);
3614
3615                 if (ms->ms_control_exp) {
3616                         class_export_put(ms->ms_control_exp);
3617                         ms->ms_control_exp = NULL;
3618                 }
3619         }
3620         EXIT;
3621 }
3622
3623 /*
3624  * FLD wrappers
3625  */
3626 static int mdt_fld_fini(const struct lu_env *env,
3627                         struct mdt_device *m)
3628 {
3629         struct md_site *ms = mdt_md_site(m);
3630         ENTRY;
3631
3632         if (ms && ms->ms_server_fld) {
3633                 fld_server_fini(ms->ms_server_fld, env);
3634                 OBD_FREE_PTR(ms->ms_server_fld);
3635                 ms->ms_server_fld = NULL;
3636         }
3637
3638         RETURN(0);
3639 }
3640
3641 static int mdt_fld_init(const struct lu_env *env,
3642                         const char *uuid,
3643                         struct mdt_device *m)
3644 {
3645         struct md_site *ms;
3646         int rc;
3647         ENTRY;
3648
3649         ms = mdt_md_site(m);
3650
3651         OBD_ALLOC_PTR(ms->ms_server_fld);
3652         if (ms->ms_server_fld == NULL)
3653                 RETURN(rc = -ENOMEM);
3654
3655         rc = fld_server_init(ms->ms_server_fld,
3656                              m->mdt_bottom, uuid,
3657                              env, ms->ms_node_id);
3658         if (rc) {
3659                 OBD_FREE_PTR(ms->ms_server_fld);
3660                 ms->ms_server_fld = NULL;
3661                 RETURN(rc);
3662         }
3663
3664         RETURN(0);
3665 }
3666
3667 /* device init/fini methods */
3668 static void mdt_stop_ptlrpc_service(struct mdt_device *m)
3669 {
3670         ENTRY;
3671         if (m->mdt_regular_service != NULL) {
3672                 ptlrpc_unregister_service(m->mdt_regular_service);
3673                 m->mdt_regular_service = NULL;
3674         }
3675         if (m->mdt_readpage_service != NULL) {
3676                 ptlrpc_unregister_service(m->mdt_readpage_service);
3677                 m->mdt_readpage_service = NULL;
3678         }
3679         if (m->mdt_xmds_service != NULL) {
3680                 ptlrpc_unregister_service(m->mdt_xmds_service);
3681                 m->mdt_xmds_service = NULL;
3682         }
3683         if (m->mdt_setattr_service != NULL) {
3684                 ptlrpc_unregister_service(m->mdt_setattr_service);
3685                 m->mdt_setattr_service = NULL;
3686         }
3687         if (m->mdt_mdsc_service != NULL) {
3688                 ptlrpc_unregister_service(m->mdt_mdsc_service);
3689                 m->mdt_mdsc_service = NULL;
3690         }
3691         if (m->mdt_mdss_service != NULL) {
3692                 ptlrpc_unregister_service(m->mdt_mdss_service);
3693                 m->mdt_mdss_service = NULL;
3694         }
3695         if (m->mdt_dtss_service != NULL) {
3696                 ptlrpc_unregister_service(m->mdt_dtss_service);
3697                 m->mdt_dtss_service = NULL;
3698         }
3699         if (m->mdt_fld_service != NULL) {
3700                 ptlrpc_unregister_service(m->mdt_fld_service);
3701                 m->mdt_fld_service = NULL;
3702         }
3703         EXIT;
3704 }
3705
3706 static int mdt_start_ptlrpc_service(struct mdt_device *m)
3707 {
3708         int rc;
3709         static struct ptlrpc_service_conf conf;
3710         cfs_proc_dir_entry_t *procfs_entry;
3711         ENTRY;
3712
3713         procfs_entry = m->mdt_md_dev.md_lu_dev.ld_obd->obd_proc_entry;
3714
3715         conf = (typeof(conf)) {
3716                 .psc_nbufs           = MDS_NBUFS,
3717                 .psc_bufsize         = MDS_BUFSIZE,
3718                 .psc_max_req_size    = MDS_MAXREQSIZE,
3719                 .psc_max_reply_size  = MDS_MAXREPSIZE,
3720                 .psc_req_portal      = MDS_REQUEST_PORTAL,
3721                 .psc_rep_portal      = MDC_REPLY_PORTAL,
3722                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
3723                 /*
3724                  * We'd like to have a mechanism to set this on a per-device
3725                  * basis, but alas...
3726                  */
3727                 .psc_min_threads    = min(max(mdt_num_threads, MDT_MIN_THREADS),
3728                                           MDT_MAX_THREADS),
3729                 .psc_max_threads     = MDT_MAX_THREADS,
3730                 .psc_ctx_tags        = LCT_MD_THREAD
3731         };
3732
3733         m->mdt_ldlm_client = &m->mdt_md_dev.md_lu_dev.ld_obd->obd_ldlm_client;
3734         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
3735                            "mdt_ldlm_client", m->mdt_ldlm_client);
3736
3737         m->mdt_regular_service =
3738                 ptlrpc_init_svc_conf(&conf, mdt_regular_handle, LUSTRE_MDT_NAME,
3739                                      procfs_entry, target_print_req,
3740                                      LUSTRE_MDT_NAME);
3741         if (m->mdt_regular_service == NULL)
3742                 RETURN(-ENOMEM);
3743
3744         rc = ptlrpc_start_threads(NULL, m->mdt_regular_service);
3745         if (rc)
3746                 GOTO(err_mdt_svc, rc);
3747
3748         /*
3749          * readpage service configuration. Parameters have to be adjusted,
3750          * ideally.
3751          */
3752         conf = (typeof(conf)) {
3753                 .psc_nbufs           = MDS_NBUFS,
3754                 .psc_bufsize         = MDS_BUFSIZE,
3755                 .psc_max_req_size    = MDS_MAXREQSIZE,
3756                 .psc_max_reply_size  = MDS_MAXREPSIZE,
3757                 .psc_req_portal      = MDS_READPAGE_PORTAL,
3758                 .psc_rep_portal      = MDC_REPLY_PORTAL,
3759                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
3760                 .psc_min_threads    = min(max(mdt_num_threads, MDT_MIN_THREADS),
3761                                           MDT_MAX_THREADS),
3762                 .psc_max_threads     = MDT_MAX_THREADS,
3763                 .psc_ctx_tags        = LCT_MD_THREAD
3764         };
3765         m->mdt_readpage_service =
3766                 ptlrpc_init_svc_conf(&conf, mdt_readpage_handle,
3767                                      LUSTRE_MDT_NAME "_readpage",
3768                                      procfs_entry, target_print_req,"mdt_rdpg");
3769
3770         if (m->mdt_readpage_service == NULL) {
3771                 CERROR("failed to start readpage service\n");
3772                 GOTO(err_mdt_svc, rc = -ENOMEM);
3773         }
3774
3775         rc = ptlrpc_start_threads(NULL, m->mdt_readpage_service);
3776
3777         /*
3778          * setattr service configuration.
3779          */
3780         conf = (typeof(conf)) {
3781                 .psc_nbufs           = MDS_NBUFS,
3782                 .psc_bufsize         = MDS_BUFSIZE,
3783                 .psc_max_req_size    = MDS_MAXREQSIZE,
3784                 .psc_max_reply_size  = MDS_MAXREPSIZE,
3785                 .psc_req_portal      = MDS_SETATTR_PORTAL,
3786                 .psc_rep_portal      = MDC_REPLY_PORTAL,
3787                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
3788                 .psc_min_threads   = min(max(mdt_num_threads, MDT_MIN_THREADS),
3789                                          MDT_MAX_THREADS),
3790                 .psc_max_threads     = MDT_MAX_THREADS,
3791                 .psc_ctx_tags        = LCT_MD_THREAD
3792         };
3793
3794         m->mdt_setattr_service =
3795                 ptlrpc_init_svc_conf(&conf, mdt_regular_handle,
3796                                      LUSTRE_MDT_NAME "_setattr",
3797                                      procfs_entry, target_print_req,"mdt_attr");
3798
3799         if (!m->mdt_setattr_service) {
3800                 CERROR("failed to start setattr service\n");
3801                 GOTO(err_mdt_svc, rc = -ENOMEM);
3802         }
3803
3804         rc = ptlrpc_start_threads(NULL, m->mdt_setattr_service);
3805         if (rc)
3806                 GOTO(err_mdt_svc, rc);
3807
3808         /*
3809          * sequence controller service configuration
3810          */
3811         conf = (typeof(conf)) {
3812                 .psc_nbufs           = MDS_NBUFS,
3813                 .psc_bufsize         = MDS_BUFSIZE,
3814                 .psc_max_req_size    = SEQ_MAXREQSIZE,
3815                 .psc_max_reply_size  = SEQ_MAXREPSIZE,
3816                 .psc_req_portal      = SEQ_CONTROLLER_PORTAL,
3817                 .psc_rep_portal      = MDC_REPLY_PORTAL,
3818                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
3819                 .psc_min_threads     = SEQ_NUM_THREADS,
3820                 .psc_max_threads     = SEQ_NUM_THREADS,
3821                 .psc_ctx_tags        = LCT_MD_THREAD|LCT_DT_THREAD
3822         };
3823
3824         m->mdt_mdsc_service =
3825                 ptlrpc_init_svc_conf(&conf, mdt_mdsc_handle,
3826                                      LUSTRE_MDT_NAME"_mdsc",
3827                                      procfs_entry, target_print_req,"mdt_mdsc");
3828         if (!m->mdt_mdsc_service) {
3829                 CERROR("failed to start seq controller service\n");
3830                 GOTO(err_mdt_svc, rc = -ENOMEM);
3831         }
3832
3833         rc = ptlrpc_start_threads(NULL, m->mdt_mdsc_service);
3834         if (rc)
3835                 GOTO(err_mdt_svc, rc);
3836
3837         /*
3838          * metadata sequence server service configuration
3839          */
3840         conf = (typeof(conf)) {
3841                 .psc_nbufs           = MDS_NBUFS,
3842                 .psc_bufsize         = MDS_BUFSIZE,
3843                 .psc_max_req_size    = SEQ_MAXREQSIZE,
3844                 .psc_max_reply_size  = SEQ_MAXREPSIZE,
3845                 .psc_req_portal      = SEQ_METADATA_PORTAL,
3846                 .psc_rep_portal      = MDC_REPLY_PORTAL,
3847                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
3848                 .psc_min_threads     = SEQ_NUM_THREADS,
3849                 .psc_max_threads     = SEQ_NUM_THREADS,
3850                 .psc_ctx_tags        = LCT_MD_THREAD|LCT_DT_THREAD
3851         };
3852
3853         m->mdt_mdss_service =
3854                 ptlrpc_init_svc_conf(&conf, mdt_mdss_handle,
3855                                      LUSTRE_MDT_NAME"_mdss",
3856                                      procfs_entry, target_print_req,"mdt_mdss");
3857         if (!m->mdt_mdss_service) {
3858                 CERROR("failed to start metadata seq server service\n");
3859                 GOTO(err_mdt_svc, rc = -ENOMEM);
3860         }
3861
3862         rc = ptlrpc_start_threads(NULL, m->mdt_mdss_service);
3863         if (rc)
3864                 GOTO(err_mdt_svc, rc);
3865
3866
3867         /*
3868          * Data sequence server service configuration. We want to have really
3869          * cluster-wide sequences space. This is why we start only one sequence
3870          * controller which manages space.
3871          */
3872         conf = (typeof(conf)) {
3873                 .psc_nbufs           = MDS_NBUFS,
3874                 .psc_bufsize         = MDS_BUFSIZE,
3875                 .psc_max_req_size    = SEQ_MAXREQSIZE,
3876                 .psc_max_reply_size  = SEQ_MAXREPSIZE,
3877                 .psc_req_portal      = SEQ_DATA_PORTAL,
3878                 .psc_rep_portal      = OSC_REPLY_PORTAL,
3879                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
3880                 .psc_min_threads     = SEQ_NUM_THREADS,
3881                 .psc_max_threads     = SEQ_NUM_THREADS,
3882                 .psc_ctx_tags        = LCT_MD_THREAD|LCT_DT_THREAD
3883         };
3884
3885         m->mdt_dtss_service =
3886                 ptlrpc_init_svc_conf(&conf, mdt_dtss_handle,
3887                                      LUSTRE_MDT_NAME"_dtss",
3888                                      procfs_entry, target_print_req,"mdt_dtss");
3889         if (!m->mdt_dtss_service) {
3890                 CERROR("failed to start data seq server service\n");
3891                 GOTO(err_mdt_svc, rc = -ENOMEM);
3892         }
3893
3894         rc = ptlrpc_start_threads(NULL, m->mdt_dtss_service);
3895         if (rc)
3896                 GOTO(err_mdt_svc, rc);
3897
3898         /* FLD service start */
3899         conf = (typeof(conf)) {
3900                 .psc_nbufs           = MDS_NBUFS,
3901                 .psc_bufsize         = MDS_BUFSIZE,
3902                 .psc_max_req_size    = FLD_MAXREQSIZE,
3903                 .psc_max_reply_size  = FLD_MAXREPSIZE,
3904                 .psc_req_portal      = FLD_REQUEST_PORTAL,
3905                 .psc_rep_portal      = MDC_REPLY_PORTAL,
3906                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
3907                 .psc_min_threads     = FLD_NUM_THREADS,
3908                 .psc_max_threads     = FLD_NUM_THREADS,
3909                 .psc_ctx_tags        = LCT_DT_THREAD|LCT_MD_THREAD
3910         };
3911
3912         m->mdt_fld_service =
3913                 ptlrpc_init_svc_conf(&conf, mdt_fld_handle,
3914                                      LUSTRE_MDT_NAME"_fld",
3915                                      procfs_entry, target_print_req, "mdt_fld");
3916         if (!m->mdt_fld_service) {
3917                 CERROR("failed to start fld service\n");
3918                 GOTO(err_mdt_svc, rc = -ENOMEM);
3919         }
3920
3921         rc = ptlrpc_start_threads(NULL, m->mdt_fld_service);
3922         if (rc)
3923                 GOTO(err_mdt_svc, rc);
3924
3925         /*
3926          * mds-mds service configuration. Separate portal is used to allow
3927          * mds-mds requests be not blocked during recovery.
3928          */
3929         conf = (typeof(conf)) {
3930                 .psc_nbufs           = MDS_NBUFS,
3931                 .psc_bufsize         = MDS_BUFSIZE,
3932                 .psc_max_req_size    = MDS_MAXREQSIZE,
3933                 .psc_max_reply_size  = MDS_MAXREPSIZE,
3934                 .psc_req_portal      = MDS_MDS_PORTAL,
3935                 .psc_rep_portal      = MDC_REPLY_PORTAL,
3936                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
3937                 .psc_min_threads    = min(max(mdt_num_threads, MDT_MIN_THREADS),
3938                                           MDT_MAX_THREADS),
3939                 .psc_max_threads     = MDT_MAX_THREADS,
3940                 .psc_ctx_tags        = LCT_MD_THREAD
3941         };
3942         m->mdt_xmds_service =
3943                 ptlrpc_init_svc_conf(&conf, mdt_xmds_handle,
3944                                      LUSTRE_MDT_NAME "_mds",
3945                                      procfs_entry, target_print_req,"mdt_xmds");
3946
3947         if (m->mdt_xmds_service == NULL) {
3948                 CERROR("failed to start readpage service\n");
3949                 GOTO(err_mdt_svc, rc = -ENOMEM);
3950         }
3951
3952         rc = ptlrpc_start_threads(NULL, m->mdt_xmds_service);
3953         if (rc)
3954                 GOTO(err_mdt_svc, rc);
3955
3956         EXIT;
3957 err_mdt_svc:
3958         if (rc)
3959                 mdt_stop_ptlrpc_service(m);
3960
3961         return rc;
3962 }
3963
3964 static void mdt_stack_fini(const struct lu_env *env,
3965                            struct mdt_device *m, struct lu_device *top)
3966 {
3967         struct obd_device       *obd = mdt2obd_dev(m);
3968         struct lustre_cfg_bufs  *bufs;
3969         struct lustre_cfg       *lcfg;
3970         struct mdt_thread_info  *info;
3971         char flags[3]="";
3972         ENTRY;
3973
3974         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
3975         LASSERT(info != NULL);
3976
3977         bufs = &info->mti_u.bufs;
3978         /* process cleanup, pass mdt obd name to get obd umount flags */
3979         lustre_cfg_bufs_reset(bufs, obd->obd_name);
3980         if (obd->obd_force)
3981                 strcat(flags, "F");
3982         if (obd->obd_fail)
3983                 strcat(flags, "A");
3984         lustre_cfg_bufs_set_string(bufs, 1, flags);
3985         lcfg = lustre_cfg_new(LCFG_CLEANUP, bufs);
3986         if (!lcfg) {
3987                 CERROR("Cannot alloc lcfg!\n");
3988                 return;
3989         }
3990
3991         LASSERT(top);
3992         top->ld_ops->ldo_process_config(env, top, lcfg);
3993         lustre_cfg_free(lcfg);
3994
3995         lu_stack_fini(env, top);
3996         m->mdt_child = NULL;
3997         m->mdt_bottom = NULL;
3998 }
3999
4000 static struct lu_device *mdt_layer_setup(struct lu_env *env,
4001                                          const char *typename,
4002                                          struct lu_device *child,
4003                                          struct lustre_cfg *cfg)
4004 {
4005         const char            *dev = lustre_cfg_string(cfg, 0);
4006         struct obd_type       *type;
4007         struct lu_device_type *ldt;
4008         struct lu_device      *d;
4009         int rc;
4010         ENTRY;
4011
4012         /* find the type */
4013         type = class_get_type(typename);
4014         if (!type) {
4015                 CERROR("Unknown type: '%s'\n", typename);
4016                 GOTO(out, rc = -ENODEV);
4017         }
4018
4019         rc = lu_env_refill((struct lu_env *)env);
4020         if (rc != 0) {
4021                 CERROR("Failure to refill session: '%d'\n", rc);
4022                 GOTO(out_type, rc);
4023         }
4024
4025         ldt = type->typ_lu;
4026         if (ldt == NULL) {
4027                 CERROR("type: '%s'\n", typename);
4028                 GOTO(out_type, rc = -EINVAL);
4029         }
4030
4031         ldt->ldt_obd_type = type;
4032         d = ldt->ldt_ops->ldto_device_alloc(env, ldt, cfg);
4033         if (IS_ERR(d)) {
4034                 CERROR("Cannot allocate device: '%s'\n", typename);
4035                 GOTO(out_type, rc = -ENODEV);
4036         }
4037
4038         LASSERT(child->ld_site);
4039         d->ld_site = child->ld_site;
4040
4041         type->typ_refcnt++;
4042         rc = ldt->ldt_ops->ldto_device_init(env, d, dev, child);
4043         if (rc) {
4044                 CERROR("can't init device '%s', rc %d\n", typename, rc);
4045                 GOTO(out_alloc, rc);
4046         }
4047         lu_device_get(d);
4048         lu_ref_add(&d->ld_reference, "lu-stack", &lu_site_init);
4049
4050         RETURN(d);
4051
4052 out_alloc:
4053         ldt->ldt_ops->ldto_device_free(env, d);
4054         type->typ_refcnt--;
4055 out_type:
4056         class_put_type(type);
4057 out:
4058         return ERR_PTR(rc);
4059 }
4060
4061 static int mdt_stack_init(struct lu_env *env,
4062                           struct mdt_device *m,
4063                           struct lustre_cfg *cfg,
4064                           struct lustre_mount_info  *lmi)
4065 {
4066         struct lu_device  *d = &m->mdt_md_dev.md_lu_dev;
4067         struct lu_device  *tmp;
4068         struct md_device  *md;
4069         struct lu_device  *child_lu_dev;
4070         int rc;
4071         ENTRY;
4072
4073         /* init the stack */
4074         tmp = mdt_layer_setup(env, LUSTRE_OSD_NAME, d, cfg);
4075         if (IS_ERR(tmp)) {
4076                 RETURN(PTR_ERR(tmp));
4077         }
4078         m->mdt_bottom = lu2dt_dev(tmp);
4079         d = tmp;
4080         tmp = mdt_layer_setup(env, LUSTRE_MDD_NAME, d, cfg);
4081         if (IS_ERR(tmp)) {
4082                 GOTO(out, rc = PTR_ERR(tmp));
4083         }
4084         d = tmp;
4085         md = lu2md_dev(d);
4086
4087         tmp = mdt_layer_setup(env, LUSTRE_CMM_NAME, d, cfg);
4088         if (IS_ERR(tmp)) {
4089                 GOTO(out, rc = PTR_ERR(tmp));
4090         }
4091         d = tmp;
4092         /*set mdd upcall device*/
4093         md_upcall_dev_set(md, lu2md_dev(d));
4094
4095         md = lu2md_dev(d);
4096         /*set cmm upcall device*/
4097         md_upcall_dev_set(md, &m->mdt_md_dev);
4098
4099         m->mdt_child = lu2md_dev(d);
4100
4101         /* process setup config */
4102         tmp = &m->mdt_md_dev.md_lu_dev;
4103         rc = tmp->ld_ops->ldo_process_config(env, tmp, cfg);
4104         if (rc)
4105                 GOTO(out, rc);
4106
4107         /* initialize local objects */
4108         child_lu_dev = &m->mdt_child->md_lu_dev;
4109
4110         rc = child_lu_dev->ld_ops->ldo_prepare(env,
4111                                                &m->mdt_md_dev.md_lu_dev,
4112                                                child_lu_dev);
4113 out:
4114         /* fini from last known good lu_device */
4115         if (rc)
4116                 mdt_stack_fini(env, m, d);
4117
4118         return rc;
4119 }
4120
4121 /**
4122  * setup CONFIG_ORIG context, used to access local config log.
4123  * this may need to be rewrite as part of llog rewrite for lu-api.
4124  */
4125 static int mdt_obd_llog_setup(struct obd_device *obd,
4126                               struct lustre_sb_info *lsi)
4127 {
4128         int     rc;
4129
4130         LASSERT(obd->obd_fsops == NULL);
4131
4132         obd->obd_fsops = fsfilt_get_ops(MT_STR(lsi->lsi_ldd));
4133         if (IS_ERR(obd->obd_fsops))
4134                 return PTR_ERR(obd->obd_fsops);
4135
4136         rc = fsfilt_setup(obd, lsi->lsi_srv_mnt->mnt_sb);
4137         if (rc) {
4138                 fsfilt_put_ops(obd->obd_fsops);
4139                 return rc;
4140         }
4141
4142         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
4143         obd->obd_lvfs_ctxt.pwdmnt = lsi->lsi_srv_mnt;
4144         obd->obd_lvfs_ctxt.pwd = lsi->lsi_srv_mnt->mnt_root;
4145         obd->obd_lvfs_ctxt.fs = get_ds();
4146
4147         rc = llog_setup(obd, &obd->obd_olg, LLOG_CONFIG_ORIG_CTXT, obd,
4148                         0, NULL, &llog_lvfs_ops);
4149         if (rc) {
4150                 CERROR("llog_setup() failed: %d\n", rc);
4151                 fsfilt_put_ops(obd->obd_fsops);
4152         }
4153
4154         return rc;
4155 }
4156
4157 static void mdt_obd_llog_cleanup(struct obd_device *obd)
4158 {
4159         struct llog_ctxt *ctxt;
4160
4161         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
4162         if (ctxt)
4163                 llog_cleanup(ctxt);
4164
4165         if (obd->obd_fsops) {
4166                 fsfilt_put_ops(obd->obd_fsops);
4167                 obd->obd_fsops = NULL;
4168         }
4169 }
4170
4171 static void mdt_fini(const struct lu_env *env, struct mdt_device *m)
4172 {
4173         struct md_device  *next = m->mdt_child;
4174         struct lu_device  *d    = &m->mdt_md_dev.md_lu_dev;
4175         struct lu_site    *ls   = d->ld_site;
4176         struct obd_device *obd = mdt2obd_dev(m);
4177         int                waited = 0;
4178         ENTRY;
4179
4180         /* At this point, obd exports might still be on the "obd_zombie_exports"
4181          * list, and obd_zombie_impexp_thread() is trying to destroy them.
4182          * We wait a little bit until all exports (except the self-export)
4183          * have been destroyed, because the whole mdt stack might be accessed
4184          * in mdt_destroy_export(). This will not be a long time, maybe one or
4185          * two seconds are enough. This is not a problem while umounting.
4186          *
4187          * The three references that should be remaining are the
4188          * obd_self_export and the attach and setup references.
4189          */
4190         while (atomic_read(&obd->obd_refcount) > 3) {
4191                 cfs_schedule_timeout(CFS_TASK_UNINT, cfs_time_seconds(1));
4192                 ++waited;
4193                 if (waited > 5 && IS_PO2(waited))
4194                         LCONSOLE_WARN("Waiting for obd_zombie_impexp_thread "
4195                                       "more than %d seconds to destroy all "
4196                                       "the exports. The current obd refcount ="
4197                                       " %d. Is it stuck there?\n",
4198                                       waited, atomic_read(&obd->obd_refcount));
4199         }
4200
4201         ping_evictor_stop();
4202
4203         target_recovery_fini(obd);
4204         mdt_stop_ptlrpc_service(m);
4205         mdt_obd_llog_cleanup(obd);
4206         obd_zombie_barrier();
4207 #ifdef HAVE_QUOTA_SUPPORT
4208         next->md_ops->mdo_quota.mqo_cleanup(env, next);
4209 #endif
4210         mdt_fs_cleanup(env, m);
4211         upcall_cache_cleanup(m->mdt_identity_cache);
4212         m->mdt_identity_cache = NULL;
4213
4214         if (m->mdt_namespace != NULL) {
4215                 ldlm_namespace_free(m->mdt_namespace, NULL, d->ld_obd->obd_force);
4216                 d->ld_obd->obd_namespace = m->mdt_namespace = NULL;
4217         }
4218
4219         cfs_free_nidlist(&m->mdt_nosquash_nids);
4220         if (m->mdt_nosquash_str) {
4221                 OBD_FREE(m->mdt_nosquash_str, m->mdt_nosquash_strlen);
4222                 m->mdt_nosquash_str = NULL;
4223                 m->mdt_nosquash_strlen = 0;
4224         }
4225
4226         mdt_seq_fini(env, m);
4227         mdt_seq_fini_cli(m);
4228         mdt_fld_fini(env, m);
4229         mdt_procfs_fini(m);
4230         if (obd->obd_proc_exports_entry) {
4231                 lprocfs_remove_proc_entry("clear", obd->obd_proc_exports_entry);
4232                 obd->obd_proc_exports_entry = NULL;
4233         }
4234         lprocfs_free_per_client_stats(obd);
4235         lprocfs_free_obd_stats(obd);
4236         ptlrpc_lprocfs_unregister_obd(d->ld_obd);
4237         lprocfs_obd_cleanup(d->ld_obd);
4238
4239         sptlrpc_rule_set_free(&m->mdt_sptlrpc_rset);
4240
4241         next->md_ops->mdo_init_capa_ctxt(env, next, 0, 0, 0, NULL);
4242         cfs_timer_disarm(&m->mdt_ck_timer);
4243         mdt_ck_thread_stop(m);
4244
4245         /* 
4246          * Finish the stack 
4247          */
4248         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
4249
4250         if (ls) {
4251                 struct md_site *mite;
4252
4253                 lu_site_fini(ls);
4254                 mite = lu_site2md(ls);
4255                 OBD_FREE_PTR(mite);
4256                 d->ld_site = NULL;
4257         }
4258         LASSERT(atomic_read(&d->ld_ref) == 0);
4259
4260         EXIT;
4261 }
4262
4263 static int mdt_adapt_sptlrpc_conf(struct obd_device *obd, int initial)
4264 {
4265         struct mdt_device       *m = mdt_dev(obd->obd_lu_dev);
4266         struct sptlrpc_rule_set  tmp_rset;
4267         int                      rc;
4268
4269         sptlrpc_rule_set_init(&tmp_rset);
4270         rc = sptlrpc_conf_target_get_rules(obd, &tmp_rset, initial);
4271         if (rc) {
4272                 CERROR("mdt %s: failed get sptlrpc rules: %d\n",
4273                        obd->obd_name, rc);
4274                 return rc;
4275         }
4276
4277         sptlrpc_target_update_exp_flavor(obd, &tmp_rset);
4278
4279         write_lock(&m->mdt_sptlrpc_lock);
4280         sptlrpc_rule_set_free(&m->mdt_sptlrpc_rset);
4281         m->mdt_sptlrpc_rset = tmp_rset;
4282         write_unlock(&m->mdt_sptlrpc_lock);
4283
4284         return 0;
4285 }
4286
4287 static void fsoptions_to_mdt_flags(struct mdt_device *m, char *options)
4288 {
4289         char *p = options;
4290
4291         m->mdt_opts.mo_mds_capa = 1;
4292         m->mdt_opts.mo_oss_capa = 1;
4293 #ifdef CONFIG_FS_POSIX_ACL
4294         /* ACLs should be enabled by default (b=13829) */
4295         m->mdt_opts.mo_acl = 1;
4296         LCONSOLE_INFO("Enabling ACL\n");
4297 #else
4298         m->mdt_opts.mo_acl = 0;
4299         LCONSOLE_INFO("Disabling ACL\n");
4300 #endif
4301
4302         if (!options)
4303                 return;
4304
4305         while (*options) {
4306                 int len;
4307
4308                 while (*p && *p != ',')
4309                         p++;
4310
4311                 len = p - options;
4312                 if ((len == sizeof("user_xattr") - 1) &&
4313                     (memcmp(options, "user_xattr", len) == 0)) {
4314                         m->mdt_opts.mo_user_xattr = 1;
4315                         LCONSOLE_INFO("Enabling user_xattr\n");
4316                 } else if ((len == sizeof("nouser_xattr") - 1) &&
4317                            (memcmp(options, "nouser_xattr", len) == 0)) {
4318                         m->mdt_opts.mo_user_xattr = 0;
4319                         LCONSOLE_INFO("Disabling user_xattr\n");
4320                 } else if ((len == sizeof("noacl") - 1) &&
4321                            (memcmp(options, "noacl", len) == 0)) {
4322                         m->mdt_opts.mo_acl = 0;
4323                         LCONSOLE_INFO("Disabling ACL\n");
4324                 }
4325
4326                 options = ++p;
4327         }
4328 }
4329
4330 int mdt_postrecov(const struct lu_env *, struct mdt_device *);
4331
4332 static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
4333                      struct lu_device_type *ldt, struct lustre_cfg *cfg)
4334 {
4335         struct lprocfs_static_vars lvars;
4336         struct mdt_thread_info    *info;
4337         struct obd_device         *obd;
4338         const char                *dev = lustre_cfg_string(cfg, 0);
4339         const char                *num = lustre_cfg_string(cfg, 2);
4340         struct lustre_mount_info  *lmi = NULL;
4341         struct lustre_sb_info     *lsi;
4342         struct lustre_disk_data   *ldd;
4343         struct lu_site            *s;
4344         struct md_site            *mite;
4345         const char                *identity_upcall = "NONE";
4346 #ifdef HAVE_QUOTA_SUPPORT
4347         struct md_device          *next;
4348 #endif
4349         int                        rc;
4350         int                        node_id;
4351         ENTRY;
4352
4353         md_device_init(&m->mdt_md_dev, ldt);
4354         /*
4355          * Environment (env) might be missing mdt_thread_key values at that
4356          * point, if device is allocated when mdt_thread_key is in QUIESCENT
4357          * mode.
4358          *
4359          * Usually device allocation path doesn't use module key values, but
4360          * mdt has to do a lot of work here, so allocate key value.
4361          */
4362         rc = lu_env_refill((struct lu_env *)env);
4363         if (rc != 0)
4364                 RETURN(rc);
4365
4366         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4367         LASSERT(info != NULL);
4368
4369         obd = class_name2obd(dev);
4370         LASSERT(obd != NULL);
4371
4372         spin_lock_init(&m->mdt_transno_lock);
4373
4374         m->mdt_max_mdsize = MAX_MD_SIZE;
4375         m->mdt_max_cookiesize = sizeof(struct llog_cookie);
4376
4377         m->mdt_opts.mo_user_xattr = 0;
4378         m->mdt_opts.mo_acl = 0;
4379         m->mdt_opts.mo_cos = MDT_COS_DEFAULT;
4380         lmi = server_get_mount_2(dev);
4381         if (lmi == NULL) {
4382                 CERROR("Cannot get mount info for %s!\n", dev);
4383                 RETURN(-EFAULT);
4384         } else {
4385                 lsi = s2lsi(lmi->lmi_sb);
4386                 fsoptions_to_mdt_flags(m, lsi->lsi_lmd->lmd_opts);
4387                 /* CMD is supported only in IAM mode */
4388                 ldd = lsi->lsi_ldd;
4389                 LASSERT(num);
4390                 node_id = simple_strtol(num, NULL, 10);
4391                 if (!(ldd->ldd_flags & LDD_F_IAM_DIR) && node_id) {
4392                         CERROR("CMD Operation not allowed in IOP mode\n");
4393                         GOTO(err_lmi, rc = -EINVAL);
4394                 }
4395         }
4396
4397         rwlock_init(&m->mdt_sptlrpc_lock);
4398         sptlrpc_rule_set_init(&m->mdt_sptlrpc_rset);
4399
4400         spin_lock_init(&m->mdt_ioepoch_lock);
4401         m->mdt_opts.mo_compat_resname = 0;
4402         m->mdt_capa_timeout = CAPA_TIMEOUT;
4403         m->mdt_capa_alg = CAPA_HMAC_ALG_SHA1;
4404         m->mdt_ck_timeout = CAPA_KEY_TIMEOUT;
4405         m->mdt_squash_uid = 0;
4406         m->mdt_squash_gid = 0;
4407         CFS_INIT_LIST_HEAD(&m->mdt_nosquash_nids);
4408         m->mdt_nosquash_str = NULL;
4409         m->mdt_nosquash_strlen = 0;
4410         init_rwsem(&m->mdt_squash_sem);
4411
4412         spin_lock_init(&m->mdt_client_bitmap_lock);
4413
4414         OBD_ALLOC_PTR(mite);
4415         if (mite == NULL)
4416                 GOTO(err_lmi, rc = -ENOMEM);
4417
4418         s = &mite->ms_lu;
4419
4420         m->mdt_md_dev.md_lu_dev.ld_ops = &mdt_lu_ops;
4421         m->mdt_md_dev.md_lu_dev.ld_obd = obd;
4422         /* set this lu_device to obd, because error handling need it */
4423         obd->obd_lu_dev = &m->mdt_md_dev.md_lu_dev;
4424
4425         rc = lu_site_init(s, &m->mdt_md_dev.md_lu_dev);
4426         if (rc) {
4427                 CERROR("Can't init lu_site, rc %d\n", rc);
4428                 GOTO(err_free_site, rc);
4429         }
4430
4431         lprocfs_mdt_init_vars(&lvars);
4432         rc = lprocfs_obd_setup(obd, lvars.obd_vars);
4433         if (rc) {
4434                 CERROR("Can't init lprocfs, rc %d\n", rc);
4435                 GOTO(err_fini_site, rc);
4436         }
4437         ptlrpc_lprocfs_register_obd(obd);
4438
4439         rc = mdt_procfs_init(m, dev);
4440         if (rc) {
4441                 CERROR("Can't init MDT lprocfs, rc %d\n", rc);
4442                 GOTO(err_fini_proc, rc);
4443         }
4444
4445         obd->obd_proc_exports_entry = proc_mkdir("exports",
4446                                                  obd->obd_proc_entry);
4447         if (obd->obd_proc_exports_entry)
4448                 lprocfs_add_simple(obd->obd_proc_exports_entry,
4449                                    "clear", lprocfs_nid_stats_clear_read,
4450                                    lprocfs_nid_stats_clear_write, obd, NULL);
4451
4452         /* set server index */
4453         lu_site2md(s)->ms_node_id = node_id;
4454
4455         /* failover is the default
4456          * FIXME: we do not failout mds0/mgs, which may cause some problems.
4457          * assumed whose ms_node_id == 0 XXX
4458          * */
4459         obd->obd_replayable = 1;
4460         /* No connection accepted until configurations will finish */
4461         obd->obd_no_conn = 1;
4462
4463         if (cfg->lcfg_bufcount > 4 && LUSTRE_CFG_BUFLEN(cfg, 4) > 0) {
4464                 char *str = lustre_cfg_string(cfg, 4);
4465                 if (strchr(str, 'n')) {
4466                         CWARN("%s: recovery disabled\n", obd->obd_name);
4467                         obd->obd_replayable = 0;
4468                 }
4469         }
4470
4471         /* init the stack */
4472         rc = mdt_stack_init((struct lu_env *)env, m, cfg, lmi);
4473         if (rc) {
4474                 CERROR("Can't init device stack, rc %d\n", rc);
4475                 GOTO(err_fini_proc, rc);
4476         }
4477
4478         rc = mdt_fld_init(env, obd->obd_name, m);
4479         if (rc)
4480                 GOTO(err_fini_stack, rc);
4481
4482         rc = mdt_seq_init(env, obd->obd_name, m);
4483         if (rc)
4484                 GOTO(err_fini_fld, rc);
4485
4486         snprintf(info->mti_u.ns_name, sizeof info->mti_u.ns_name,
4487                  LUSTRE_MDT_NAME"-%p", m);
4488         m->mdt_namespace = ldlm_namespace_new(obd, info->mti_u.ns_name,
4489                                               LDLM_NAMESPACE_SERVER,
4490                                               LDLM_NAMESPACE_GREEDY);
4491         if (m->mdt_namespace == NULL)
4492                 GOTO(err_fini_seq, rc = -ENOMEM);
4493
4494         ldlm_register_intent(m->mdt_namespace, mdt_intent_policy);
4495         /* set obd_namespace for compatibility with old code */
4496         obd->obd_namespace = m->mdt_namespace;
4497
4498         /* XXX: to support suppgid for ACL, we enable identity_upcall
4499          * by default, otherwise, maybe got unexpected -EACCESS. */
4500         if (m->mdt_opts.mo_acl)
4501                 identity_upcall = MDT_IDENTITY_UPCALL_PATH;
4502
4503         m->mdt_identity_cache = upcall_cache_init(obd->obd_name, identity_upcall,
4504                                                   &mdt_identity_upcall_cache_ops);
4505         if (IS_ERR(m->mdt_identity_cache)) {
4506                 rc = PTR_ERR(m->mdt_identity_cache);
4507                 m->mdt_identity_cache = NULL;
4508                 GOTO(err_free_ns, rc);
4509         }
4510
4511         cfs_timer_init(&m->mdt_ck_timer, mdt_ck_timer_callback, m);
4512
4513         rc = mdt_ck_thread_start(m);
4514         if (rc)
4515                 GOTO(err_free_ns, rc);
4516
4517         rc = mdt_fs_setup(env, m, obd, lsi);
4518         if (rc)
4519                 GOTO(err_capa, rc);
4520
4521         rc = mdt_obd_llog_setup(obd, lsi);
4522         if (rc)
4523                 GOTO(err_fs_cleanup, rc);
4524
4525         mdt_adapt_sptlrpc_conf(obd, 1);
4526
4527 #ifdef HAVE_QUOTA_SUPPORT
4528         next = m->mdt_child;
4529         rc = next->md_ops->mdo_quota.mqo_setup(env, next, lmi->lmi_mnt);
4530         if (rc)
4531                 GOTO(err_llog_cleanup, rc);
4532 #endif
4533
4534         server_put_mount_2(dev, lmi->lmi_mnt);
4535         lmi = NULL;
4536
4537         target_recovery_init(obd, mdt_recovery_handle);
4538
4539         rc = mdt_start_ptlrpc_service(m);
4540         if (rc)
4541                 GOTO(err_recovery, rc);
4542
4543         ping_evictor_start();
4544
4545         rc = lu_site_init_finish(s);
4546         if (rc)
4547                 GOTO(err_stop_service, rc);
4548
4549         if (obd->obd_recovering == 0)
4550                 mdt_postrecov(env, m);
4551
4552         mdt_init_capa_ctxt(env, m);
4553
4554         /* Reduce the initial timeout on an MDS because it doesn't need such
4555          * a long timeout as an OST does. Adaptive timeouts will adjust this
4556          * value appropriately. */
4557         if (ldlm_timeout == LDLM_TIMEOUT_DEFAULT)
4558                 ldlm_timeout = MDS_LDLM_TIMEOUT_DEFAULT;
4559
4560         RETURN(0);
4561
4562 err_stop_service:
4563         ping_evictor_stop();
4564         mdt_stop_ptlrpc_service(m);
4565 err_recovery:
4566         target_recovery_fini(obd);
4567 #ifdef HAVE_QUOTA_SUPPORT
4568         next->md_ops->mdo_quota.mqo_cleanup(env, next);
4569 err_llog_cleanup:
4570 #endif
4571         mdt_obd_llog_cleanup(obd);
4572 err_fs_cleanup:
4573         mdt_fs_cleanup(env, m);
4574 err_capa:
4575         cfs_timer_disarm(&m->mdt_ck_timer);
4576         mdt_ck_thread_stop(m);
4577 err_free_ns:
4578         upcall_cache_cleanup(m->mdt_identity_cache);
4579         m->mdt_identity_cache = NULL;
4580         ldlm_namespace_free(m->mdt_namespace, NULL, 0);
4581         obd->obd_namespace = m->mdt_namespace = NULL;
4582 err_fini_seq:
4583         mdt_seq_fini(env, m);
4584 err_fini_fld:
4585         mdt_fld_fini(env, m);
4586 err_fini_stack:
4587         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
4588 err_fini_proc:
4589         mdt_procfs_fini(m);
4590         if (obd->obd_proc_exports_entry) {
4591                 lprocfs_remove_proc_entry("clear", obd->obd_proc_exports_entry);
4592                 obd->obd_proc_exports_entry = NULL;
4593         }
4594         ptlrpc_lprocfs_unregister_obd(obd);
4595         lprocfs_obd_cleanup(obd);
4596 err_fini_site:
4597         lu_site_fini(s);
4598 err_free_site:
4599         OBD_FREE_PTR(mite);
4600 err_lmi:
4601         if (lmi) 
4602                 server_put_mount_2(dev, lmi->lmi_mnt);
4603         return (rc);
4604 }
4605
4606 /* used by MGS to process specific configurations */
4607 static int mdt_process_config(const struct lu_env *env,
4608                               struct lu_device *d, struct lustre_cfg *cfg)
4609 {
4610         struct mdt_device *m = mdt_dev(d);
4611         struct md_device *md_next = m->mdt_child;
4612         struct lu_device *next = md2lu_dev(md_next);
4613         int rc = 0;
4614         ENTRY;
4615
4616         switch (cfg->lcfg_command) {
4617         case LCFG_PARAM: {
4618                 struct lprocfs_static_vars lvars;
4619                 struct obd_device *obd = d->ld_obd;
4620
4621                 /*
4622                  * For interoperability between 1.8 and 2.0,
4623                  * skip old "mdt.group_upcall" param.
4624                  */
4625                 {
4626                         char *param = lustre_cfg_string(cfg, 1);
4627                         if (param && !strncmp("mdt.group_upcall", param, 16)) {
4628                                 CWARN("For 1.8 interoperability, skip this"
4629                                        " mdt.group_upcall. It is obsolete\n");
4630                                 break;
4631                         }
4632                 }
4633
4634                 lprocfs_mdt_init_vars(&lvars);
4635                 rc = class_process_proc_param(PARAM_MDT, lvars.obd_vars,
4636                                               cfg, obd);
4637                 if (rc > 0 || rc == -ENOSYS)
4638                         /* we don't understand; pass it on */
4639                         rc = next->ld_ops->ldo_process_config(env, next, cfg);
4640                 break;
4641         }
4642         case LCFG_ADD_MDC:
4643                 /*
4644                  * Add mdc hook to get first MDT uuid and connect it to
4645                  * ls->controller to use for seq manager.
4646                  */
4647                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
4648                 if (rc)
4649                         CERROR("Can't add mdc, rc %d\n", rc);
4650                 else
4651                         rc = mdt_seq_init_cli(env, mdt_dev(d), cfg);
4652                 break;
4653         default:
4654                 /* others are passed further */
4655                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
4656                 break;
4657         }
4658         RETURN(rc);
4659 }
4660
4661 static struct lu_object *mdt_object_alloc(const struct lu_env *env,
4662                                           const struct lu_object_header *hdr,
4663                                           struct lu_device *d)
4664 {
4665         struct mdt_object *mo;
4666
4667         ENTRY;
4668
4669         OBD_ALLOC_PTR(mo);
4670         if (mo != NULL) {
4671                 struct lu_object *o;
4672                 struct lu_object_header *h;
4673
4674                 o = &mo->mot_obj.mo_lu;
4675                 h = &mo->mot_header;
4676                 lu_object_header_init(h);
4677                 lu_object_init(o, h, d);
4678                 lu_object_add_top(h, o);
4679                 o->lo_ops = &mdt_obj_ops;
4680                 RETURN(o);
4681         } else
4682                 RETURN(NULL);
4683 }
4684
4685 static int mdt_object_init(const struct lu_env *env, struct lu_object *o,
4686                            const struct lu_object_conf *_)
4687 {
4688         struct mdt_device *d = mdt_dev(o->lo_dev);
4689         struct lu_device  *under;
4690         struct lu_object  *below;
4691         int                rc = 0;
4692         ENTRY;
4693
4694         CDEBUG(D_INFO, "object init, fid = "DFID"\n",
4695                PFID(lu_object_fid(o)));
4696
4697         under = &d->mdt_child->md_lu_dev;
4698         below = under->ld_ops->ldo_object_alloc(env, o->lo_header, under);
4699         if (below != NULL) {
4700                 lu_object_add(o, below);
4701         } else
4702                 rc = -ENOMEM;
4703
4704         RETURN(rc);
4705 }
4706
4707 static void mdt_object_free(const struct lu_env *env, struct lu_object *o)
4708 {
4709         struct mdt_object *mo = mdt_obj(o);
4710         struct lu_object_header *h;
4711         ENTRY;
4712
4713         h = o->lo_header;
4714         CDEBUG(D_INFO, "object free, fid = "DFID"\n",
4715                PFID(lu_object_fid(o)));
4716
4717         lu_object_fini(o);
4718         lu_object_header_fini(h);
4719         OBD_FREE_PTR(mo);
4720         EXIT;
4721 }
4722
4723 static const struct lu_device_operations mdt_lu_ops = {
4724         .ldo_object_alloc   = mdt_object_alloc,
4725         .ldo_process_config = mdt_process_config,
4726 };
4727
4728 static const struct lu_object_operations mdt_obj_ops = {
4729         .loo_object_init    = mdt_object_init,
4730         .loo_object_free    = mdt_object_free
4731 };
4732
4733 static int mdt_obd_set_info_async(struct obd_export *exp,
4734                                   __u32 keylen, void *key,
4735                                   __u32 vallen, void *val,
4736                                   struct ptlrpc_request_set *set)
4737 {
4738         struct obd_device     *obd = exp->exp_obd;
4739         int                    rc;
4740         ENTRY;
4741
4742         LASSERT(obd);
4743
4744         if (KEY_IS(KEY_SPTLRPC_CONF)) {
4745                 rc = mdt_adapt_sptlrpc_conf(obd, 0);
4746                 RETURN(rc);
4747         }
4748
4749         RETURN(0);
4750 }
4751
4752 /* mds_connect_internal */
4753 static int mdt_connect_internal(struct obd_export *exp,
4754                                 struct mdt_device *mdt,
4755                                 struct obd_connect_data *data)
4756 {
4757         if (data != NULL) {
4758                 data->ocd_connect_flags &= MDT_CONNECT_SUPPORTED;
4759                 data->ocd_ibits_known &= MDS_INODELOCK_FULL;
4760
4761                 /* If no known bits (which should not happen, probably,
4762                    as everybody should support LOOKUP and UPDATE bits at least)
4763                    revert to compat mode with plain locks. */
4764                 if (!data->ocd_ibits_known &&
4765                     data->ocd_connect_flags & OBD_CONNECT_IBITS)
4766                         data->ocd_connect_flags &= ~OBD_CONNECT_IBITS;
4767
4768                 if (!mdt->mdt_opts.mo_acl)
4769                         data->ocd_connect_flags &= ~OBD_CONNECT_ACL;
4770
4771                 if (!mdt->mdt_opts.mo_user_xattr)
4772                         data->ocd_connect_flags &= ~OBD_CONNECT_XATTR;
4773
4774                 spin_lock(&exp->exp_lock);
4775                 exp->exp_connect_flags = data->ocd_connect_flags;
4776                 spin_unlock(&exp->exp_lock);
4777                 data->ocd_version = LUSTRE_VERSION_CODE;
4778                 exp->exp_mdt_data.med_ibits_known = data->ocd_ibits_known;
4779         }
4780
4781 #if 0
4782         if (mdt->mdt_opts.mo_acl &&
4783             ((exp->exp_connect_flags & OBD_CONNECT_ACL) == 0)) {
4784                 CWARN("%s: MDS requires ACL support but client does not\n",
4785                       mdt->mdt_md_dev.md_lu_dev.ld_obd->obd_name);
4786                 return -EBADE;
4787         }
4788 #endif
4789
4790         if ((exp->exp_connect_flags & OBD_CONNECT_FID) == 0) {
4791                 CWARN("%s: MDS requires FID support, but client not\n",
4792                       mdt->mdt_md_dev.md_lu_dev.ld_obd->obd_name);
4793                 return -EBADE;
4794         }
4795
4796         return 0;
4797 }
4798
4799 static int mdt_connect_check_sptlrpc(struct mdt_device *mdt,
4800                                      struct obd_export *exp,
4801                                      struct ptlrpc_request *req)
4802 {
4803         struct sptlrpc_flavor   flvr;
4804         int                     rc = 0;
4805
4806         if (exp->exp_flvr.sf_rpc == SPTLRPC_FLVR_INVALID) {
4807                 read_lock(&mdt->mdt_sptlrpc_lock);
4808                 sptlrpc_target_choose_flavor(&mdt->mdt_sptlrpc_rset,
4809                                              req->rq_sp_from,
4810                                              req->rq_peer.nid,
4811                                              &flvr);
4812                 read_unlock(&mdt->mdt_sptlrpc_lock);
4813
4814                 spin_lock(&exp->exp_lock);
4815
4816                 exp->exp_sp_peer = req->rq_sp_from;
4817                 exp->exp_flvr = flvr;
4818
4819                 if (exp->exp_flvr.sf_rpc != SPTLRPC_FLVR_ANY &&
4820                     exp->exp_flvr.sf_rpc != req->rq_flvr.sf_rpc) {
4821                         CERROR("unauthorized rpc flavor %x from %s, "
4822                                "expect %x\n", req->rq_flvr.sf_rpc,
4823                                libcfs_nid2str(req->rq_peer.nid),
4824                                exp->exp_flvr.sf_rpc);
4825                         rc = -EACCES;
4826                 }
4827
4828                 spin_unlock(&exp->exp_lock);
4829         } else {
4830                 if (exp->exp_sp_peer != req->rq_sp_from) {
4831                         CERROR("RPC source %s doesn't match %s\n",
4832                                sptlrpc_part2name(req->rq_sp_from),
4833                                sptlrpc_part2name(exp->exp_sp_peer));
4834                         rc = -EACCES;
4835                 } else {
4836                         rc = sptlrpc_target_export_check(exp, req);
4837                 }
4838         }
4839
4840         return rc;
4841 }
4842
4843 /* mds_connect copy */
4844 static int mdt_obd_connect(const struct lu_env *env,
4845                            struct lustre_handle *conn, struct obd_device *obd,
4846                            struct obd_uuid *cluuid,
4847                            struct obd_connect_data *data,
4848                            void *localdata)
4849 {
4850         struct mdt_thread_info *info;
4851         struct lsd_client_data *lcd;
4852         struct obd_export      *exp;
4853         struct mdt_device      *mdt;
4854         struct ptlrpc_request  *req;
4855         int                     rc;
4856         ENTRY;
4857
4858         LASSERT(env != NULL);
4859         if (!conn || !obd || !cluuid)
4860                 RETURN(-EINVAL);
4861
4862         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4863         req = info->mti_pill->rc_req;
4864         mdt = mdt_dev(obd->obd_lu_dev);
4865
4866         rc = class_connect(conn, obd, cluuid);
4867         if (rc)
4868                 RETURN(rc);
4869
4870         exp = class_conn2export(conn);
4871         LASSERT(exp != NULL);
4872
4873         rc = mdt_connect_check_sptlrpc(mdt, exp, req);
4874         if (rc)
4875                 GOTO(out, rc);
4876
4877         rc = mdt_connect_internal(exp, mdt, data);
4878         if (rc == 0) {
4879                 OBD_ALLOC_PTR(lcd);
4880                 if (lcd != NULL) {
4881                         struct mdt_thread_info *mti;
4882                         mti = lu_context_key_get(&env->le_ctx,
4883                                                  &mdt_thread_key);
4884                         LASSERT(mti != NULL);
4885                         mti->mti_exp = exp;
4886                         memcpy(lcd->lcd_uuid, cluuid, sizeof lcd->lcd_uuid);
4887                         exp->exp_mdt_data.med_lcd = lcd;
4888                         rc = mdt_client_new(env, mdt);
4889                         if (rc != 0) {
4890                                 OBD_FREE_PTR(lcd);
4891                                 exp->exp_mdt_data.med_lcd = NULL;
4892                         } else {
4893                                 mdt_export_stats_init(obd, exp, localdata);
4894                         }
4895                 } else
4896                         rc = -ENOMEM;
4897         }
4898
4899 out:
4900         if (rc != 0)
4901                 class_disconnect(exp);
4902         else
4903                 class_export_put(exp);
4904
4905         RETURN(rc);
4906 }
4907
4908 static int mdt_obd_reconnect(const struct lu_env *env,
4909                              struct obd_export *exp, struct obd_device *obd,
4910                              struct obd_uuid *cluuid,
4911                              struct obd_connect_data *data,
4912                              void *localdata)
4913 {
4914         struct mdt_thread_info *info;
4915         struct mdt_device      *mdt;
4916         struct ptlrpc_request  *req;
4917         int                     rc;
4918         ENTRY;
4919
4920         if (exp == NULL || obd == NULL || cluuid == NULL)
4921                 RETURN(-EINVAL);
4922
4923         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4924         req = info->mti_pill->rc_req;
4925         mdt = mdt_dev(obd->obd_lu_dev);
4926
4927         rc = mdt_connect_check_sptlrpc(mdt, exp, req);
4928         if (rc)
4929                 RETURN(rc);
4930
4931         rc = mdt_connect_internal(exp, mdt_dev(obd->obd_lu_dev), data);
4932         if (rc == 0)
4933                 mdt_export_stats_init(obd, exp, localdata);
4934
4935         RETURN(rc);
4936 }
4937
4938 static int mdt_obd_disconnect(struct obd_export *exp)
4939 {
4940         struct mdt_device *mdt = mdt_dev(exp->exp_obd->obd_lu_dev);
4941         int rc;
4942         ENTRY;
4943
4944         LASSERT(exp);
4945         class_export_get(exp);
4946
4947         /* Disconnect early so that clients can't keep using export */
4948         rc = class_disconnect(exp);
4949         if (mdt->mdt_namespace != NULL || exp->exp_obd->obd_namespace != NULL)
4950                 ldlm_cancel_locks_for_export(exp);
4951
4952         /* release nid stat refererence */
4953         lprocfs_exp_cleanup(exp);
4954
4955         /* complete all outstanding replies */
4956         spin_lock(&exp->exp_lock);
4957         while (!list_empty(&exp->exp_outstanding_replies)) {
4958                 struct ptlrpc_reply_state *rs =
4959                         list_entry(exp->exp_outstanding_replies.next,
4960                                    struct ptlrpc_reply_state, rs_exp_list);
4961                 struct ptlrpc_service *svc = rs->rs_service;
4962
4963                 spin_lock(&svc->srv_lock);
4964                 list_del_init(&rs->rs_exp_list);
4965                 spin_lock(&rs->rs_lock);
4966                 ptlrpc_schedule_difficult_reply(rs);
4967                 spin_unlock(&rs->rs_lock);
4968                 spin_unlock(&svc->srv_lock);
4969         }
4970         spin_unlock(&exp->exp_lock);
4971
4972         class_export_put(exp);
4973         RETURN(rc);
4974 }
4975
4976 /* FIXME: Can we avoid using these two interfaces? */
4977 static int mdt_init_export(struct obd_export *exp)
4978 {
4979         struct mdt_export_data *med = &exp->exp_mdt_data;
4980         int                     rc;
4981         ENTRY;
4982
4983         CFS_INIT_LIST_HEAD(&med->med_open_head);
4984         spin_lock_init(&med->med_open_lock);
4985         sema_init(&med->med_idmap_sem, 1);
4986         med->med_idmap = NULL;
4987         spin_lock(&exp->exp_lock);
4988         exp->exp_connecting = 1;
4989         spin_unlock(&exp->exp_lock);
4990         rc = ldlm_init_export(exp);
4991         if (rc)
4992                 CERROR("Error %d while initializing export\n", rc);
4993         RETURN(rc);
4994 }
4995
4996 static int mdt_destroy_export(struct obd_export *export)
4997 {
4998         struct mdt_export_data *med;
4999         struct obd_device      *obd = export->exp_obd;
5000         struct mdt_device      *mdt;
5001         struct mdt_thread_info *info;
5002         struct lu_env           env;
5003         struct md_attr         *ma;
5004         int lmm_size;
5005         int cookie_size;
5006         CFS_LIST_HEAD(closing_list);
5007         struct mdt_file_data *mfd, *n;
5008         int rc = 0;
5009         ENTRY;
5010
5011         med = &export->exp_mdt_data;
5012         if (exp_connect_rmtclient(export))
5013                 mdt_cleanup_idmap(med);
5014
5015         target_destroy_export(export);
5016         ldlm_destroy_export(export);
5017
5018         if (obd_uuid_equals(&export->exp_client_uuid, &obd->obd_uuid))
5019                 RETURN(0);
5020
5021         mdt = mdt_dev(obd->obd_lu_dev);
5022         LASSERT(mdt != NULL);
5023
5024         rc = lu_env_init(&env, LCT_MD_THREAD);
5025         if (rc)
5026                 RETURN(rc);
5027
5028         info = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5029         LASSERT(info != NULL);
5030         memset(info, 0, sizeof *info);
5031         info->mti_env = &env;
5032         info->mti_mdt = mdt;
5033         info->mti_exp = export;
5034
5035         ma = &info->mti_attr;
5036         lmm_size = ma->ma_lmm_size = mdt->mdt_max_mdsize;
5037         cookie_size = ma->ma_cookie_size = mdt->mdt_max_cookiesize;
5038         OBD_ALLOC(ma->ma_lmm, lmm_size);
5039         OBD_ALLOC(ma->ma_cookie, cookie_size);
5040
5041         if (ma->ma_lmm == NULL || ma->ma_cookie == NULL)
5042                 GOTO(out, rc = -ENOMEM);
5043         ma->ma_need = MA_LOV | MA_COOKIE;
5044         ma->ma_valid = 0;
5045         /* Close any open files (which may also cause orphan unlinking). */
5046         spin_lock(&med->med_open_lock);
5047         while (!list_empty(&med->med_open_head)) {
5048                 struct list_head *tmp = med->med_open_head.next;
5049                 mfd = list_entry(tmp, struct mdt_file_data, mfd_list);
5050
5051                 /* Remove mfd handle so it can't be found again.
5052                  * We are consuming the mfd_list reference here. */
5053                 class_handle_unhash(&mfd->mfd_handle);
5054                 list_move_tail(&mfd->mfd_list, &closing_list);
5055         }
5056         spin_unlock(&med->med_open_lock);
5057
5058         list_for_each_entry_safe(mfd, n, &closing_list, mfd_list) {
5059                 list_del_init(&mfd->mfd_list);
5060                 mdt_mfd_close(info, mfd);
5061                 /* TODO: if we close the unlinked file,
5062                  * we need to remove its objects from OST */
5063                 memset(&ma->ma_attr, 0, sizeof(ma->ma_attr));
5064                 spin_lock(&med->med_open_lock);
5065                 ma->ma_lmm_size = lmm_size;
5066                 ma->ma_cookie_size = cookie_size;
5067                 ma->ma_need = MA_LOV | MA_COOKIE;
5068                 ma->ma_valid = 0;
5069                 spin_unlock(&med->med_open_lock);
5070         }
5071
5072         info->mti_mdt = NULL;
5073         mdt_client_del(&env, mdt);
5074
5075         EXIT;
5076 out:
5077         if (lmm_size) {
5078                 OBD_FREE(ma->ma_lmm, lmm_size);
5079                 ma->ma_lmm = NULL;
5080         }
5081         if (cookie_size) {
5082                 OBD_FREE(ma->ma_cookie, cookie_size);
5083                 ma->ma_cookie = NULL;
5084         }
5085         lu_env_fini(&env);
5086
5087         return rc;
5088 }
5089
5090 static void mdt_allow_cli(struct mdt_device *m, unsigned int flag)
5091 {
5092         if (flag & CONFIG_LOG)
5093                 m->mdt_fl_cfglog = 1;
5094
5095         /* also notify active event */
5096         if (flag & CONFIG_SYNC)
5097                 m->mdt_fl_synced = 1;
5098
5099         if (m->mdt_fl_cfglog && m->mdt_fl_synced)
5100                 /* Open for clients */
5101                 m->mdt_md_dev.md_lu_dev.ld_obd->obd_no_conn = 0;
5102 }
5103
5104 static int mdt_upcall(const struct lu_env *env, struct md_device *md,
5105                       enum md_upcall_event ev)
5106 {
5107         struct mdt_device *m = mdt_dev(&md->md_lu_dev);
5108         struct md_device  *next  = m->mdt_child;
5109         struct mdt_thread_info *mti;
5110         int rc = 0;
5111         ENTRY;
5112
5113         switch (ev) {
5114                 case MD_LOV_SYNC:
5115                         rc = next->md_ops->mdo_maxsize_get(env, next,
5116                                         &m->mdt_max_mdsize,
5117                                         &m->mdt_max_cookiesize);
5118                         CDEBUG(D_INFO, "get max mdsize %d max cookiesize %d\n",
5119                                      m->mdt_max_mdsize, m->mdt_max_cookiesize);
5120                         mdt_allow_cli(m, CONFIG_SYNC);
5121 #ifdef HAVE_QUOTA_SUPPORT
5122                         if (md->md_lu_dev.ld_obd->obd_recovering == 0)
5123                                 next->md_ops->mdo_quota.mqo_recovery(env, next);
5124 #endif
5125                         break;
5126                 case MD_NO_TRANS:
5127                         mti = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
5128                         mti->mti_no_need_trans = 1;
5129                         CDEBUG(D_INFO, "disable mdt trans for this thread\n");
5130                         break;
5131                 case MD_LOV_CONFIG:
5132                         /* Check that MDT is not yet configured */
5133                         LASSERT(!m->mdt_fl_cfglog);
5134                         break;
5135                 default:
5136                         CERROR("invalid event\n");
5137                         rc = -EINVAL;
5138                         break;
5139         }
5140         RETURN(rc);
5141 }
5142
5143 static int mdt_obd_notify(struct obd_device *host,
5144                           struct obd_device *watched,
5145                           enum obd_notify_event ev, void *data)
5146 {
5147         struct mdt_device *mdt = mdt_dev(host->obd_lu_dev);
5148 #ifdef HAVE_QUOTA_SUPPORT
5149         struct md_device *next = mdt->mdt_child;
5150 #endif
5151         ENTRY;
5152
5153         switch (ev) {
5154         case OBD_NOTIFY_CONFIG:
5155                 mdt_allow_cli(mdt, (unsigned long)data);
5156
5157 #ifdef HAVE_QUOTA_SUPPORT
5158                /* quota_type has been processed, we can now handle
5159                 * incoming quota requests */
5160                 next->md_ops->mdo_quota.mqo_notify(NULL, next);
5161 #endif
5162                 break;
5163         default:
5164                 CDEBUG(D_INFO, "Unhandled notification %#x\n", ev);
5165         }
5166         RETURN(0);
5167 }
5168
5169 static int mdt_ioc_fid2path(struct lu_env *env, struct mdt_device *mdt,
5170                             struct obd_ioctl_data *data)
5171 {
5172         struct lu_context  ioctl_session;
5173         struct mdt_object *obj;
5174         struct lu_fid     *fid;
5175         char  *path = NULL;
5176         __u64  recno;
5177         int    pathlen = data->ioc_plen1;
5178         int    linkno;
5179         int    rc;
5180         ENTRY;
5181
5182
5183         fid = (struct lu_fid *)data->ioc_inlbuf1;
5184         memcpy(&recno, data->ioc_inlbuf2, sizeof(recno));
5185         memcpy(&linkno, data->ioc_inlbuf3, sizeof(linkno));
5186         CDEBUG(D_IOCTL, "path get "DFID" from "LPU64" #%d\n",
5187                PFID(fid), recno, linkno);
5188
5189         if (!fid_is_sane(fid))
5190                 RETURN(-EINVAL);
5191
5192         if (pathlen < 3)
5193                 RETURN(-EOVERFLOW);
5194
5195         rc = lu_context_init(&ioctl_session, LCT_SESSION);
5196         if (rc)
5197                 RETURN(rc);
5198         ioctl_session.lc_thread = (struct ptlrpc_thread *)cfs_current();
5199         lu_context_enter(&ioctl_session);
5200         env->le_ses = &ioctl_session;
5201
5202         OBD_ALLOC(path, pathlen);
5203         if (path == NULL)
5204                 GOTO(out_context, rc = -ENOMEM);
5205
5206         obj = mdt_object_find(env, mdt, fid);
5207         if (obj == NULL || IS_ERR(obj)) {
5208                 CDEBUG(D_IOCTL, "no object "DFID": %ld\n", PFID(fid),
5209                        PTR_ERR(obj));
5210                 GOTO(out_free, rc = -EINVAL);
5211         }
5212
5213         rc = lu_object_exists(&obj->mot_obj.mo_lu);
5214         if (rc <= 0) {
5215                 if (rc == -1)
5216                         rc = -EREMOTE;
5217                 else
5218                         rc = -ENOENT;
5219                 mdt_object_put(env, obj);
5220                 CDEBUG(D_IOCTL, "nonlocal object "DFID": %d\n", PFID(fid),
5221                        rc);
5222                 GOTO(out_free, rc);
5223         }
5224
5225         rc = mo_path(env, md_object_next(&obj->mot_obj), path, pathlen, recno,
5226                      &linkno);
5227         mdt_object_put(env, obj);
5228         if (rc)
5229                GOTO(out_free, rc);
5230
5231         if (copy_to_user(data->ioc_pbuf1, path, pathlen))
5232                 rc = -EFAULT;
5233
5234         memcpy(data->ioc_inlbuf3, &linkno, sizeof(linkno));
5235
5236         EXIT;
5237 out_free:
5238         OBD_FREE(path, pathlen);
5239 out_context:
5240         lu_context_exit(&ioctl_session);
5241         lu_context_fini(&ioctl_session);
5242         return rc;
5243 }
5244
5245 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
5246                          void *karg, void *uarg)
5247 {
5248         struct lu_env      env;
5249         struct obd_device *obd = exp->exp_obd;
5250         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
5251         struct dt_device  *dt = mdt->mdt_bottom;
5252         int rc;
5253
5254         ENTRY;
5255         CDEBUG(D_IOCTL, "handling ioctl cmd %#x\n", cmd);
5256         rc = lu_env_init(&env, LCT_MD_THREAD);
5257         if (rc)
5258                 RETURN(rc);
5259
5260         switch (cmd) {
5261         case OBD_IOC_SYNC:
5262                 rc = mdt_device_sync(&env, mdt);
5263                 break;
5264         case OBD_IOC_SET_READONLY:
5265                 dt->dd_ops->dt_ro(&env, dt);
5266                 break;
5267         case OBD_IOC_ABORT_RECOVERY:
5268                 CERROR("Aborting recovery for device %s\n", obd->obd_name);
5269                 target_stop_recovery_thread(obd);
5270                 rc = 0;
5271                 break;
5272         case OBD_IOC_FID2PATH:
5273                 rc = mdt_ioc_fid2path(&env, mdt, karg);
5274                 break;
5275         default:
5276                 CERROR("Not supported cmd = %d for device %s\n",
5277                        cmd, obd->obd_name);
5278                 rc = -EOPNOTSUPP;
5279         }
5280
5281         lu_env_fini(&env);
5282         RETURN(rc);
5283 }
5284
5285 int mdt_postrecov(const struct lu_env *env, struct mdt_device *mdt)
5286 {
5287         struct lu_device *ld = md2lu_dev(mdt->mdt_child);
5288         struct obd_device *obd = mdt2obd_dev(mdt);
5289 #ifdef HAVE_QUOTA_SUPPORT
5290         struct md_device *next = mdt->mdt_child;
5291 #endif
5292         int rc, lost;
5293         ENTRY;
5294         /* if some clients didn't participate in recovery then we can possibly
5295          * lost sequence. Now we should increase sequence for safe value */
5296         lost = obd->obd_max_recoverable_clients - obd->obd_connected_clients;
5297         mdt_seq_adjust(env, mdt, lost);
5298
5299         rc = ld->ld_ops->ldo_recovery_complete(env, ld);
5300 #ifdef HAVE_QUOTA_SUPPORT
5301         next->md_ops->mdo_quota.mqo_recovery(env, next);
5302 #endif
5303         RETURN(rc);
5304 }
5305
5306 int mdt_obd_postrecov(struct obd_device *obd)
5307 {
5308         struct lu_env env;
5309         int rc;
5310
5311         rc = lu_env_init(&env, LCT_MD_THREAD);
5312         if (rc)
5313                 RETURN(rc);
5314         rc = mdt_postrecov(&env, mdt_dev(obd->obd_lu_dev));
5315         lu_env_fini(&env);
5316         return rc;
5317 }
5318
5319 static struct obd_ops mdt_obd_device_ops = {
5320         .o_owner          = THIS_MODULE,
5321         .o_set_info_async = mdt_obd_set_info_async,
5322         .o_connect        = mdt_obd_connect,
5323         .o_reconnect      = mdt_obd_reconnect,
5324         .o_disconnect     = mdt_obd_disconnect,
5325         .o_init_export    = mdt_init_export,
5326         .o_destroy_export = mdt_destroy_export,
5327         .o_iocontrol      = mdt_iocontrol,
5328         .o_postrecov      = mdt_obd_postrecov,
5329         .o_notify         = mdt_obd_notify
5330 };
5331
5332 static struct lu_device* mdt_device_fini(const struct lu_env *env,
5333                                          struct lu_device *d)
5334 {
5335         struct mdt_device *m = mdt_dev(d);
5336         ENTRY;
5337
5338         mdt_fini(env, m);
5339         RETURN(NULL);
5340 }
5341
5342 static struct lu_device *mdt_device_free(const struct lu_env *env,
5343                                          struct lu_device *d)
5344 {
5345         struct mdt_device *m = mdt_dev(d);
5346         ENTRY;
5347
5348         md_device_fini(&m->mdt_md_dev);
5349         OBD_FREE_PTR(m);
5350         RETURN(NULL);
5351 }
5352
5353 static struct lu_device *mdt_device_alloc(const struct lu_env *env,
5354                                           struct lu_device_type *t,
5355                                           struct lustre_cfg *cfg)
5356 {
5357         struct lu_device  *l;
5358         struct mdt_device *m;
5359
5360         OBD_ALLOC_PTR(m);
5361         if (m != NULL) {
5362                 int rc;
5363
5364                 l = &m->mdt_md_dev.md_lu_dev;
5365                 rc = mdt_init0(env, m, t, cfg);
5366                 if (rc != 0) {
5367                         mdt_device_free(env, l);
5368                         l = ERR_PTR(rc);
5369                         return l;
5370                 }
5371                 md_upcall_init(&m->mdt_md_dev, mdt_upcall);
5372         } else
5373                 l = ERR_PTR(-ENOMEM);
5374         return l;
5375 }
5376
5377 /* context key constructor/destructor: mdt_key_init, mdt_key_fini */
5378 LU_KEY_INIT_FINI(mdt, struct mdt_thread_info);
5379
5380 /* context key: mdt_thread_key */
5381 LU_CONTEXT_KEY_DEFINE(mdt, LCT_MD_THREAD);
5382
5383 /* context key constructor/destructor: mdt_txn_key_init, mdt_txn_key_fini */
5384 LU_KEY_INIT_FINI(mdt_txn, struct mdt_txn_info);
5385
5386 struct lu_context_key mdt_txn_key = {
5387         .lct_tags = LCT_TX_HANDLE,
5388         .lct_init = mdt_txn_key_init,
5389         .lct_fini = mdt_txn_key_fini
5390 };
5391
5392 struct md_ucred *mdt_ucred(const struct mdt_thread_info *info)
5393 {
5394         return md_ucred(info->mti_env);
5395 }
5396
5397 /**
5398  * Enable/disable COS.
5399  *
5400  * Set/Clear the COS flag in mdt options.
5401  *
5402  * \param mdt mdt device
5403  * \param val 0 disables COS, other values enable COS
5404  */
5405 void mdt_enable_cos(struct mdt_device *mdt, int val)
5406 {
5407         struct lu_env env;
5408         int rc;
5409
5410         mdt->mdt_opts.mo_cos = !!val;
5411         rc = lu_env_init(&env, LCT_MD_THREAD);
5412         if (unlikely(rc != 0)) {
5413                 CWARN("lu_env initialization failed with rc = %d,"
5414                       "cannot sync\n", rc);
5415                 return;
5416         }
5417         mdt_device_sync(&env, mdt);
5418         lu_env_fini(&env);
5419 }
5420
5421 /**
5422  * Check COS status.
5423  *
5424  * Return COS flag status/
5425  *
5426  * \param mdt mdt device
5427  */
5428 int mdt_cos_is_enabled(struct mdt_device *mdt)
5429 {
5430         return mdt->mdt_opts.mo_cos != 0;
5431 }
5432
5433 /* type constructor/destructor: mdt_type_init, mdt_type_fini */
5434 LU_TYPE_INIT_FINI(mdt, &mdt_thread_key, &mdt_txn_key);
5435
5436 static struct lu_device_type_operations mdt_device_type_ops = {
5437         .ldto_init = mdt_type_init,
5438         .ldto_fini = mdt_type_fini,
5439
5440         .ldto_start = mdt_type_start,
5441         .ldto_stop  = mdt_type_stop,
5442
5443         .ldto_device_alloc = mdt_device_alloc,
5444         .ldto_device_free  = mdt_device_free,
5445         .ldto_device_fini  = mdt_device_fini
5446 };
5447
5448 static struct lu_device_type mdt_device_type = {
5449         .ldt_tags     = LU_DEVICE_MD,
5450         .ldt_name     = LUSTRE_MDT_NAME,
5451         .ldt_ops      = &mdt_device_type_ops,
5452         .ldt_ctx_tags = LCT_MD_THREAD
5453 };
5454
5455 static struct lu_local_obj_desc mdt_last_recv = {
5456         .llod_name      = LAST_RCVD,
5457         .llod_oid       = MDT_LAST_RECV_OID,
5458         .llod_is_index  = 0,
5459 };
5460
5461 static int __init mdt_mod_init(void)
5462 {
5463         struct lprocfs_static_vars lvars;
5464         int rc;
5465
5466         llo_local_obj_register(&mdt_last_recv);
5467
5468         mdt_num_threads = MDT_NUM_THREADS;
5469         lprocfs_mdt_init_vars(&lvars);
5470         rc = class_register_type(&mdt_obd_device_ops, NULL,
5471                                  lvars.module_vars, LUSTRE_MDT_NAME,
5472                                  &mdt_device_type);
5473
5474         return rc;
5475 }
5476
5477 static void __exit mdt_mod_exit(void)
5478 {
5479         llo_local_obj_unregister(&mdt_last_recv);
5480         class_unregister_type(LUSTRE_MDT_NAME);
5481 }
5482
5483
5484 #define DEF_HNDL(prefix, base, suffix, flags, opc, fn, fmt)             \
5485 [prefix ## _ ## opc - prefix ## _ ## base] = {                          \
5486         .mh_name    = #opc,                                             \
5487         .mh_fail_id = OBD_FAIL_ ## prefix ## _  ## opc ## suffix,       \
5488         .mh_opc     = prefix ## _  ## opc,                              \
5489         .mh_flags   = flags,                                            \
5490         .mh_act     = fn,                                               \
5491         .mh_fmt     = fmt                                               \
5492 }
5493
5494 #define DEF_MDT_HNDL(flags, name, fn, fmt)                                  \
5495         DEF_HNDL(MDS, GETATTR, _NET, flags, name, fn, fmt)
5496
5497 #define DEF_SEQ_HNDL(flags, name, fn, fmt)                      \
5498         DEF_HNDL(SEQ, QUERY, _NET, flags, name, fn, fmt)
5499
5500 #define DEF_FLD_HNDL(flags, name, fn, fmt)                      \
5501         DEF_HNDL(FLD, QUERY, _NET, flags, name, fn, fmt)
5502 /*
5503  * Request with a format known in advance
5504  */
5505 #define DEF_MDT_HNDL_F(flags, name, fn)                                 \
5506         DEF_HNDL(MDS, GETATTR, _NET, flags, name, fn, &RQF_MDS_ ## name)
5507
5508 #define DEF_SEQ_HNDL_F(flags, name, fn)                                 \
5509         DEF_HNDL(SEQ, QUERY, _NET, flags, name, fn, &RQF_SEQ_ ## name)
5510
5511 #define DEF_FLD_HNDL_F(flags, name, fn)                                 \
5512         DEF_HNDL(FLD, QUERY, _NET, flags, name, fn, &RQF_FLD_ ## name)
5513 /*
5514  * Request with a format we do not yet know
5515  */
5516 #define DEF_MDT_HNDL_0(flags, name, fn)                                 \
5517         DEF_HNDL(MDS, GETATTR, _NET, flags, name, fn, NULL)
5518
5519 static struct mdt_handler mdt_mds_ops[] = {
5520 DEF_MDT_HNDL_F(0,                         CONNECT,      mdt_connect),
5521 DEF_MDT_HNDL_F(0,                         DISCONNECT,   mdt_disconnect),
5522 DEF_MDT_HNDL_F(0,                         SET_INFO,     mdt_set_info),
5523 DEF_MDT_HNDL_F(0           |HABEO_REFERO, GETSTATUS,    mdt_getstatus),
5524 DEF_MDT_HNDL_F(HABEO_CORPUS,              GETATTR,      mdt_getattr),
5525 DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, GETATTR_NAME, mdt_getattr_name),
5526 DEF_MDT_HNDL_F(HABEO_CORPUS,              GETXATTR,     mdt_getxattr),
5527 DEF_MDT_HNDL_F(0           |HABEO_REFERO, STATFS,       mdt_statfs),
5528 DEF_MDT_HNDL_F(0           |MUTABOR,      REINT,        mdt_reint),
5529 DEF_MDT_HNDL_F(HABEO_CORPUS,              CLOSE,        mdt_close),
5530 DEF_MDT_HNDL_F(HABEO_CORPUS,              DONE_WRITING, mdt_done_writing),
5531 DEF_MDT_HNDL_F(0           |HABEO_REFERO, PIN,          mdt_pin),
5532 DEF_MDT_HNDL_0(0,                         SYNC,         mdt_sync),
5533 DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, IS_SUBDIR,    mdt_is_subdir),
5534 #ifdef HAVE_QUOTA_SUPPORT
5535 DEF_MDT_HNDL_F(0,                         QUOTACHECK,   mdt_quotacheck_handle),
5536 DEF_MDT_HNDL_F(0,                         QUOTACTL,     mdt_quotactl_handle)
5537 #endif
5538 };
5539
5540 #define DEF_OBD_HNDL(flags, name, fn)                   \
5541         DEF_HNDL(OBD, PING, _NET, flags, name, fn, NULL)
5542
5543
5544 static struct mdt_handler mdt_obd_ops[] = {
5545         DEF_OBD_HNDL(0, PING,           mdt_obd_ping),
5546         DEF_OBD_HNDL(0, LOG_CANCEL,     mdt_obd_log_cancel),
5547         DEF_OBD_HNDL(0, QC_CALLBACK,    mdt_obd_qc_callback)
5548 };
5549
5550 #define DEF_DLM_HNDL_0(flags, name, fn)                   \
5551         DEF_HNDL(LDLM, ENQUEUE, , flags, name, fn, NULL)
5552 #define DEF_DLM_HNDL_F(flags, name, fn)                   \
5553         DEF_HNDL(LDLM, ENQUEUE, , flags, name, fn, &RQF_LDLM_ ## name)
5554
5555 static struct mdt_handler mdt_dlm_ops[] = {
5556         DEF_DLM_HNDL_F(HABEO_CLAVIS, ENQUEUE,        mdt_enqueue),
5557         DEF_DLM_HNDL_0(HABEO_CLAVIS, CONVERT,        mdt_convert),
5558         DEF_DLM_HNDL_0(0,            BL_CALLBACK,    mdt_bl_callback),
5559         DEF_DLM_HNDL_0(0,            CP_CALLBACK,    mdt_cp_callback)
5560 };
5561
5562 static struct mdt_handler mdt_llog_ops[] = {
5563 };
5564
5565 #define DEF_SEC_CTX_HNDL(name, fn)                      \
5566         DEF_HNDL(SEC_CTX, INIT, _NET, 0, name, fn, NULL)
5567
5568 static struct mdt_handler mdt_sec_ctx_ops[] = {
5569         DEF_SEC_CTX_HNDL(INIT,          mdt_sec_ctx_handle),
5570         DEF_SEC_CTX_HNDL(INIT_CONT,     mdt_sec_ctx_handle),
5571         DEF_SEC_CTX_HNDL(FINI,          mdt_sec_ctx_handle)
5572 };
5573
5574 static struct mdt_opc_slice mdt_regular_handlers[] = {
5575         {
5576                 .mos_opc_start = MDS_GETATTR,
5577                 .mos_opc_end   = MDS_LAST_OPC,
5578                 .mos_hs        = mdt_mds_ops
5579         },
5580         {
5581                 .mos_opc_start = OBD_PING,
5582                 .mos_opc_end   = OBD_LAST_OPC,
5583                 .mos_hs        = mdt_obd_ops
5584         },
5585         {
5586                 .mos_opc_start = LDLM_ENQUEUE,
5587                 .mos_opc_end   = LDLM_LAST_OPC,
5588                 .mos_hs        = mdt_dlm_ops
5589         },
5590         {
5591                 .mos_opc_start = LLOG_ORIGIN_HANDLE_CREATE,
5592                 .mos_opc_end   = LLOG_LAST_OPC,
5593                 .mos_hs        = mdt_llog_ops
5594         },
5595         {
5596                 .mos_opc_start = SEC_CTX_INIT,
5597                 .mos_opc_end   = SEC_LAST_OPC,
5598                 .mos_hs        = mdt_sec_ctx_ops
5599         },
5600         {
5601                 .mos_hs        = NULL
5602         }
5603 };
5604
5605 static struct mdt_handler mdt_readpage_ops[] = {
5606         DEF_MDT_HNDL_F(0,                         CONNECT,  mdt_connect),
5607         DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, READPAGE, mdt_readpage),
5608 #ifdef HAVE_SPLIT_SUPPORT
5609         DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, WRITEPAGE, mdt_writepage),
5610 #endif
5611
5612         /*
5613          * XXX: this is ugly and should be fixed one day, see mdc_close() for
5614          * detailed comments. --umka
5615          */
5616         DEF_MDT_HNDL_F(HABEO_CORPUS,              CLOSE,    mdt_close),
5617         DEF_MDT_HNDL_F(HABEO_CORPUS,              DONE_WRITING,    mdt_done_writing),
5618 };
5619
5620 static struct mdt_opc_slice mdt_readpage_handlers[] = {
5621         {
5622                 .mos_opc_start = MDS_GETATTR,
5623                 .mos_opc_end   = MDS_LAST_OPC,
5624                 .mos_hs        = mdt_readpage_ops
5625         },
5626         {
5627                 .mos_hs        = NULL
5628         }
5629 };
5630
5631 static struct mdt_handler mdt_xmds_ops[] = {
5632         DEF_MDT_HNDL_F(0,                         CONNECT,      mdt_connect),
5633         DEF_MDT_HNDL_F(HABEO_CORPUS             , GETATTR,      mdt_getattr),
5634         DEF_MDT_HNDL_F(0 | MUTABOR              , REINT,        mdt_reint),
5635         DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, IS_SUBDIR,    mdt_is_subdir),
5636 };
5637
5638 static struct mdt_opc_slice mdt_xmds_handlers[] = {
5639         {
5640                 .mos_opc_start = MDS_GETATTR,
5641                 .mos_opc_end   = MDS_LAST_OPC,
5642                 .mos_hs        = mdt_xmds_ops
5643         },
5644         {
5645                 .mos_opc_start = OBD_PING,
5646                 .mos_opc_end   = OBD_LAST_OPC,
5647                 .mos_hs        = mdt_obd_ops
5648         },
5649         {
5650                 .mos_opc_start = SEC_CTX_INIT,
5651                 .mos_opc_end   = SEC_LAST_OPC,
5652                 .mos_hs        = mdt_sec_ctx_ops
5653         },
5654         {
5655                 .mos_hs        = NULL
5656         }
5657 };
5658
5659 static struct mdt_handler mdt_seq_ops[] = {
5660         DEF_SEQ_HNDL_F(0, QUERY, (int (*)(struct mdt_thread_info *))seq_query)
5661 };
5662
5663 static struct mdt_opc_slice mdt_seq_handlers[] = {
5664         {
5665                 .mos_opc_start = SEQ_QUERY,
5666                 .mos_opc_end   = SEQ_LAST_OPC,
5667                 .mos_hs        = mdt_seq_ops
5668         },
5669         {
5670                 .mos_hs        = NULL
5671         }
5672 };
5673
5674 static struct mdt_handler mdt_fld_ops[] = {
5675         DEF_FLD_HNDL_F(0, QUERY, (int (*)(struct mdt_thread_info *))fld_query)
5676 };
5677
5678 static struct mdt_opc_slice mdt_fld_handlers[] = {
5679         {
5680                 .mos_opc_start = FLD_QUERY,
5681                 .mos_opc_end   = FLD_LAST_OPC,
5682                 .mos_hs        = mdt_fld_ops
5683         },
5684         {
5685                 .mos_hs        = NULL
5686         }
5687 };
5688
5689 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
5690 MODULE_DESCRIPTION("Lustre Meta-data Target ("LUSTRE_MDT_NAME")");
5691 MODULE_LICENSE("GPL");
5692
5693 CFS_MODULE_PARM(mdt_num_threads, "ul", ulong, 0444,
5694                 "number of mdt service threads to start");
5695
5696 cfs_module(mdt, "0.2.0", mdt_mod_init, mdt_mod_exit);