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