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