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