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