Whamcloud - gitweb
LU-16634 obdclass: improve iocontrol error messages
[fs/lustre-release.git] / lustre / lmv / lmv_obd.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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  */
31
32 #define DEBUG_SUBSYSTEM S_LMV
33
34 #include <linux/file.h>
35 #include <linux/module.h>
36 #include <linux/init.h>
37 #include <linux/user_namespace.h>
38 #include <linux/uidgid.h>
39 #include <linux/slab.h>
40 #include <linux/pagemap.h>
41 #include <linux/mm.h>
42 #include <linux/math64.h>
43 #include <linux/seq_file.h>
44 #include <linux/namei.h>
45
46 #include <obd_support.h>
47 #include <lustre_lib.h>
48 #include <lustre_net.h>
49 #include <obd_class.h>
50 #include <lustre_lmv.h>
51 #include <lprocfs_status.h>
52 #include <cl_object.h>
53 #include <lustre_fid.h>
54 #include <uapi/linux/lustre/lustre_ioctl.h>
55 #include <lustre_kernelcomm.h>
56 #include "lmv_internal.h"
57
58 static int lmv_check_connect(struct obd_device *obd);
59 static inline bool lmv_op_default_rr_mkdir(const struct md_op_data *op_data);
60
61 void lmv_activate_target(struct lmv_obd *lmv, struct lmv_tgt_desc *tgt,
62                          int activate)
63 {
64         if (tgt->ltd_active == activate)
65                 return;
66
67         tgt->ltd_active = activate;
68         lmv->lmv_mdt_descs.ltd_lmv_desc.ld_active_tgt_count +=
69                 (activate ? 1 : -1);
70
71         tgt->ltd_exp->exp_obd->obd_inactive = !activate;
72 }
73
74 /**
75  * Error codes:
76  *
77  *  -EINVAL  : UUID can't be found in the LMV's target list
78  *  -ENOTCONN: The UUID is found, but the target connection is bad (!)
79  *  -EBADF   : The UUID is found, but the OBD of the wrong type (!)
80  */
81 static int lmv_set_mdc_active(struct lmv_obd *lmv,
82                               const struct obd_uuid *uuid,
83                               int activate)
84 {
85         struct lu_tgt_desc *tgt = NULL;
86         struct obd_device *obd;
87         int rc = 0;
88
89         ENTRY;
90
91         CDEBUG(D_INFO, "Searching in lmv %p for uuid %s (activate=%d)\n",
92                         lmv, uuid->uuid, activate);
93
94         spin_lock(&lmv->lmv_lock);
95         lmv_foreach_connected_tgt(lmv, tgt) {
96                 CDEBUG(D_INFO, "Target idx %d is %s conn %#llx\n",
97                        tgt->ltd_index, tgt->ltd_uuid.uuid,
98                        tgt->ltd_exp->exp_handle.h_cookie);
99
100                 if (obd_uuid_equals(uuid, &tgt->ltd_uuid))
101                         break;
102         }
103
104         if (!tgt)
105                 GOTO(out_lmv_lock, rc = -EINVAL);
106
107         obd = class_exp2obd(tgt->ltd_exp);
108         if (obd == NULL)
109                 GOTO(out_lmv_lock, rc = -ENOTCONN);
110
111         CDEBUG(D_INFO, "Found OBD %s=%s device %d (%p) type %s at LMV idx %d\n",
112                obd->obd_name, obd->obd_uuid.uuid, obd->obd_minor, obd,
113                obd->obd_type->typ_name, tgt->ltd_index);
114         LASSERT(strcmp(obd->obd_type->typ_name, LUSTRE_MDC_NAME) == 0);
115
116         if (tgt->ltd_active == activate) {
117                 CDEBUG(D_INFO, "OBD %p already %sactive!\n", obd,
118                        activate ? "" : "in");
119                 GOTO(out_lmv_lock, rc);
120         }
121
122         CDEBUG(D_INFO, "Marking OBD %p %sactive\n", obd,
123                activate ? "" : "in");
124         lmv_activate_target(lmv, tgt, activate);
125         EXIT;
126
127  out_lmv_lock:
128         spin_unlock(&lmv->lmv_lock);
129         return rc;
130 }
131
132 static struct obd_uuid *lmv_get_uuid(struct obd_export *exp)
133 {
134         struct lmv_obd *lmv = &exp->exp_obd->u.lmv;
135         struct lmv_tgt_desc *tgt = lmv_tgt(lmv, 0);
136
137         return tgt ? obd_get_uuid(tgt->ltd_exp) : NULL;
138 }
139
140 static int lmv_notify(struct obd_device *obd, struct obd_device *watched,
141                       enum obd_notify_event ev)
142 {
143         struct obd_connect_data *conn_data;
144         struct lmv_obd          *lmv = &obd->u.lmv;
145         struct obd_uuid         *uuid;
146         int                      rc = 0;
147         ENTRY;
148
149         if (strcmp(watched->obd_type->typ_name, LUSTRE_MDC_NAME)) {
150                 CERROR("unexpected notification of %s %s!\n",
151                        watched->obd_type->typ_name,
152                        watched->obd_name);
153                 RETURN(-EINVAL);
154         }
155
156         uuid = &watched->u.cli.cl_target_uuid;
157         if (ev == OBD_NOTIFY_ACTIVE || ev == OBD_NOTIFY_INACTIVE) {
158                 /*
159                  * Set MDC as active before notifying the observer, so the
160                  * observer can use the MDC normally.
161                  */
162                 rc = lmv_set_mdc_active(lmv, uuid,
163                                         ev == OBD_NOTIFY_ACTIVE);
164                 if (rc) {
165                         CERROR("%sactivation of %s failed: %d\n",
166                                ev == OBD_NOTIFY_ACTIVE ? "" : "de",
167                                uuid->uuid, rc);
168                         RETURN(rc);
169                 }
170         } else if (ev == OBD_NOTIFY_OCD) {
171                 conn_data = &watched->u.cli.cl_import->imp_connect_data;
172                 /*
173                  * XXX: Make sure that ocd_connect_flags from all targets are
174                  * the same. Otherwise one of MDTs runs wrong version or
175                  * something like this.  --umka
176                  */
177                 obd->obd_self_export->exp_connect_data = *conn_data;
178         }
179
180         /*
181          * Pass the notification up the chain.
182          */
183         if (obd->obd_observer)
184                 rc = obd_notify(obd->obd_observer, watched, ev);
185
186         RETURN(rc);
187 }
188
189 static int lmv_connect(const struct lu_env *env,
190                        struct obd_export **pexp, struct obd_device *obd,
191                        struct obd_uuid *cluuid, struct obd_connect_data *data,
192                        void *localdata)
193 {
194         struct lmv_obd *lmv = &obd->u.lmv;
195         struct lustre_handle conn = { 0 };
196         struct obd_export *exp;
197         int rc;
198         ENTRY;
199
200         rc = class_connect(&conn, obd, cluuid);
201         if (rc) {
202                 CERROR("class_connection() returned %d\n", rc);
203                 RETURN(rc);
204         }
205
206         exp = class_conn2export(&conn);
207
208         lmv->connected = 0;
209         lmv->conn_data = *data;
210         lmv->lmv_cache = localdata;
211
212         lmv->lmv_tgts_kobj = kobject_create_and_add("target_obds",
213                                                     &obd->obd_kset.kobj);
214         if (!lmv->lmv_tgts_kobj) {
215                 CERROR("%s: cannot create /sys/fs/lustre/%s/%s/target_obds\n",
216                        obd->obd_name, obd->obd_type->typ_name, obd->obd_name);
217         }
218
219         rc = lmv_check_connect(obd);
220         if (rc != 0)
221                 GOTO(out_sysfs, rc);
222
223         *pexp = exp;
224
225         RETURN(rc);
226
227 out_sysfs:
228         if (lmv->lmv_tgts_kobj)
229                 kobject_put(lmv->lmv_tgts_kobj);
230
231         class_disconnect(exp);
232
233         return rc;
234 }
235
236 static int lmv_init_ea_size(struct obd_export *exp, __u32 easize,
237                             __u32 def_easize)
238 {
239         struct obd_device *obd = exp->exp_obd;
240         struct lmv_obd *lmv = &obd->u.lmv;
241         struct lmv_tgt_desc *tgt;
242         int change = 0;
243         int rc = 0;
244
245         ENTRY;
246
247         if (lmv->max_easize < easize) {
248                 lmv->max_easize = easize;
249                 change = 1;
250         }
251         if (lmv->max_def_easize < def_easize) {
252                 lmv->max_def_easize = def_easize;
253                 change = 1;
254         }
255
256         if (change == 0)
257                 RETURN(0);
258
259         if (lmv->connected == 0)
260                 RETURN(0);
261
262         lmv_foreach_connected_tgt(lmv, tgt) {
263                 if (!tgt->ltd_active)
264                         continue;
265
266                 rc = md_init_ea_size(tgt->ltd_exp, easize, def_easize);
267                 if (rc) {
268                         CERROR("%s: obd_init_ea_size() failed on MDT target %d:"
269                                " rc = %d\n", obd->obd_name, tgt->ltd_index, rc);
270                         break;
271                 }
272         }
273         RETURN(rc);
274 }
275
276 #define MAX_STRING_SIZE 128
277
278 static int lmv_connect_mdc(struct obd_device *obd, struct lmv_tgt_desc *tgt)
279 {
280         struct lmv_obd *lmv = &obd->u.lmv;
281         struct obd_device *mdc_obd;
282         struct obd_export *mdc_exp;
283         struct lu_fld_target target;
284         int  rc;
285         ENTRY;
286
287         mdc_obd = class_find_client_obd(&tgt->ltd_uuid, LUSTRE_MDC_NAME,
288                                         &obd->obd_uuid);
289         if (!mdc_obd) {
290                 CERROR("target %s not attached\n", tgt->ltd_uuid.uuid);
291                 RETURN(-EINVAL);
292         }
293
294         CDEBUG(D_CONFIG, "connect to %s(%s) - %s, %s\n",
295                mdc_obd->obd_name, mdc_obd->obd_uuid.uuid,
296                tgt->ltd_uuid.uuid, obd->obd_uuid.uuid);
297
298         if (!mdc_obd->obd_set_up) {
299                 CERROR("target %s is not set up\n", tgt->ltd_uuid.uuid);
300                 RETURN(-EINVAL);
301         }
302
303         rc = obd_connect(NULL, &mdc_exp, mdc_obd, &obd->obd_uuid,
304                          &lmv->conn_data, lmv->lmv_cache);
305         if (rc) {
306                 CERROR("target %s connect error %d\n", tgt->ltd_uuid.uuid, rc);
307                 RETURN(rc);
308         }
309
310         /*
311          * Init fid sequence client for this mdc and add new fld target.
312          */
313         rc = obd_fid_init(mdc_obd, mdc_exp, LUSTRE_SEQ_METADATA);
314         if (rc)
315                 RETURN(rc);
316
317         target.ft_srv = NULL;
318         target.ft_exp = mdc_exp;
319         target.ft_idx = tgt->ltd_index;
320
321         fld_client_add_target(&lmv->lmv_fld, &target);
322
323         rc = obd_register_observer(mdc_obd, obd);
324         if (rc) {
325                 obd_disconnect(mdc_exp);
326                 CERROR("target %s register_observer error %d\n",
327                        tgt->ltd_uuid.uuid, rc);
328                 RETURN(rc);
329         }
330
331         if (obd->obd_observer) {
332                 /*
333                  * Tell the observer about the new target.
334                  */
335                 rc = obd_notify(obd->obd_observer, mdc_exp->exp_obd,
336                                 OBD_NOTIFY_ACTIVE);
337                 if (rc) {
338                         obd_disconnect(mdc_exp);
339                         RETURN(rc);
340                 }
341         }
342
343         tgt->ltd_active = 1;
344         tgt->ltd_exp = mdc_exp;
345         lmv->lmv_mdt_descs.ltd_lmv_desc.ld_active_tgt_count++;
346
347         md_init_ea_size(tgt->ltd_exp, lmv->max_easize, lmv->max_def_easize);
348
349         rc = lu_qos_add_tgt(&lmv->lmv_qos, tgt);
350         if (rc) {
351                 obd_disconnect(mdc_exp);
352                 RETURN(rc);
353         }
354
355         CDEBUG(D_CONFIG, "Connected to %s(%s) successfully (%d)\n",
356                mdc_obd->obd_name, mdc_obd->obd_uuid.uuid,
357                atomic_read(&obd->obd_refcount));
358
359         lmv_statfs_check_update(obd, tgt);
360
361         if (lmv->lmv_tgts_kobj)
362                 /* Even if we failed to create the link, that's fine */
363                 rc = sysfs_create_link(lmv->lmv_tgts_kobj,
364                                        &mdc_obd->obd_kset.kobj,
365                                        mdc_obd->obd_name);
366         RETURN(0);
367 }
368
369 static void lmv_del_target(struct lmv_obd *lmv, struct lu_tgt_desc *tgt)
370 {
371         LASSERT(tgt);
372         ltd_del_tgt(&lmv->lmv_mdt_descs, tgt);
373         OBD_FREE_PTR(tgt);
374 }
375
376 static int lmv_add_target(struct obd_device *obd, struct obd_uuid *uuidp,
377                            __u32 index, int gen)
378 {
379         struct obd_device *mdc_obd;
380         struct lmv_obd *lmv = &obd->u.lmv;
381         struct lmv_tgt_desc *tgt;
382         struct lu_tgt_descs *ltd = &lmv->lmv_mdt_descs;
383         int rc = 0;
384
385         ENTRY;
386
387         CDEBUG(D_CONFIG, "Target uuid: %s. index %d\n", uuidp->uuid, index);
388         mdc_obd = class_find_client_obd(uuidp, LUSTRE_MDC_NAME,
389                                         &obd->obd_uuid);
390         if (!mdc_obd) {
391                 CERROR("%s: Target %s not attached: rc = %d\n",
392                        obd->obd_name, uuidp->uuid, -EINVAL);
393                 RETURN(-EINVAL);
394         }
395
396         OBD_ALLOC_PTR(tgt);
397         if (!tgt)
398                 RETURN(-ENOMEM);
399
400         mutex_init(&tgt->ltd_fid_mutex);
401         tgt->ltd_index = index;
402         tgt->ltd_uuid = *uuidp;
403         tgt->ltd_active = 0;
404
405         mutex_lock(&ltd->ltd_mutex);
406         rc = ltd_add_tgt(ltd, tgt);
407         mutex_unlock(&ltd->ltd_mutex);
408
409         if (rc)
410                 GOTO(out_tgt, rc);
411
412         if (!lmv->connected)
413                 /* lmv_check_connect() will connect this target. */
414                 RETURN(0);
415
416         rc = lmv_connect_mdc(obd, tgt);
417         if (!rc) {
418                 int easize = sizeof(struct lmv_stripe_md) +
419                         lmv->lmv_mdt_count * sizeof(struct lu_fid);
420
421                 lmv_init_ea_size(obd->obd_self_export, easize, 0);
422         }
423
424         RETURN(rc);
425
426 out_tgt:
427         OBD_FREE_PTR(tgt);
428         return rc;
429 }
430
431 static int lmv_check_connect(struct obd_device *obd)
432 {
433         struct lmv_obd *lmv = &obd->u.lmv;
434         struct lmv_tgt_desc *tgt;
435         int easize;
436         int rc;
437
438         ENTRY;
439
440         if (lmv->connected)
441                 RETURN(0);
442
443         mutex_lock(&lmv->lmv_mdt_descs.ltd_mutex);
444         if (lmv->connected)
445                 GOTO(unlock, rc = 0);
446
447         if (!lmv->lmv_mdt_count) {
448                 CERROR("%s: no targets configured: rc = -EINVAL\n",
449                        obd->obd_name);
450                 GOTO(unlock, rc = -EINVAL);
451         }
452
453         if (!lmv_mdt0_inited(lmv)) {
454                 CERROR("%s: no target configured for index 0: rc = -EINVAL.\n",
455                        obd->obd_name);
456                 GOTO(unlock, rc = -EINVAL);
457         }
458
459         CDEBUG(D_CONFIG, "Time to connect %s to %s\n",
460                obd->obd_uuid.uuid, obd->obd_name);
461
462         lmv_foreach_tgt(lmv, tgt) {
463                 rc = lmv_connect_mdc(obd, tgt);
464                 if (rc)
465                         GOTO(out_disc, rc);
466         }
467
468         lmv->connected = 1;
469         easize = lmv_mds_md_size(lmv->lmv_mdt_count, LMV_MAGIC);
470         lmv_init_ea_size(obd->obd_self_export, easize, 0);
471         EXIT;
472 unlock:
473         mutex_unlock(&lmv->lmv_mdt_descs.ltd_mutex);
474
475         return rc;
476
477 out_disc:
478         lmv_foreach_tgt(lmv, tgt) {
479                 tgt->ltd_active = 0;
480                 if (!tgt->ltd_exp)
481                         continue;
482
483                 --lmv->lmv_mdt_descs.ltd_lmv_desc.ld_active_tgt_count;
484                 obd_disconnect(tgt->ltd_exp);
485         }
486
487         goto unlock;
488 }
489
490 static int lmv_disconnect_mdc(struct obd_device *obd, struct lmv_tgt_desc *tgt)
491 {
492         struct lmv_obd *lmv = &obd->u.lmv;
493         struct obd_device *mdc_obd;
494         int rc;
495         ENTRY;
496
497         LASSERT(tgt != NULL);
498         LASSERT(obd != NULL);
499
500         mdc_obd = class_exp2obd(tgt->ltd_exp);
501
502         if (mdc_obd) {
503                 mdc_obd->obd_force = obd->obd_force;
504                 mdc_obd->obd_fail = obd->obd_fail;
505                 mdc_obd->obd_no_recov = obd->obd_no_recov;
506
507                 if (lmv->lmv_tgts_kobj)
508                         sysfs_remove_link(lmv->lmv_tgts_kobj,
509                                           mdc_obd->obd_name);
510         }
511
512         rc = lu_qos_del_tgt(&lmv->lmv_qos, tgt);
513         if (rc)
514                 CERROR("%s: Can't del target from QoS table: rc = %d\n",
515                        tgt->ltd_exp->exp_obd->obd_name, rc);
516
517         rc = fld_client_del_target(&lmv->lmv_fld, tgt->ltd_index);
518         if (rc)
519                 CERROR("%s: Can't del fld targets: rc = %d\n",
520                        tgt->ltd_exp->exp_obd->obd_name, rc);
521
522         rc = obd_fid_fini(tgt->ltd_exp->exp_obd);
523         if (rc)
524                 CERROR("%s: Can't finalize fids factory: rc = %d\n",
525                        tgt->ltd_exp->exp_obd->obd_name, rc);
526
527         CDEBUG(D_INFO, "Disconnected from %s(%s) successfully\n",
528                tgt->ltd_exp->exp_obd->obd_name,
529                tgt->ltd_exp->exp_obd->obd_uuid.uuid);
530
531         lmv_activate_target(lmv, tgt, 0);
532         obd_register_observer(tgt->ltd_exp->exp_obd, NULL);
533         rc = obd_disconnect(tgt->ltd_exp);
534         if (rc) {
535                 CERROR("%s: Target %s disconnect error: rc = %d\n",
536                        tgt->ltd_exp->exp_obd->obd_name,
537                        tgt->ltd_uuid.uuid, rc);
538         }
539         tgt->ltd_exp = NULL;
540         RETURN(0);
541 }
542
543 static int lmv_disconnect(struct obd_export *exp)
544 {
545         struct obd_device *obd = class_exp2obd(exp);
546         struct lmv_obd *lmv = &obd->u.lmv;
547         struct lmv_tgt_desc *tgt;
548         int rc;
549
550         ENTRY;
551
552         lmv_foreach_connected_tgt(lmv, tgt)
553                 lmv_disconnect_mdc(obd, tgt);
554
555         if (lmv->lmv_tgts_kobj)
556                 kobject_put(lmv->lmv_tgts_kobj);
557
558         lmv->connected = 0;
559         rc = class_disconnect(exp);
560
561         RETURN(rc);
562 }
563
564 static int lmv_fid2path(struct obd_export *exp, int len, void *karg,
565                         void __user *uarg)
566 {
567         struct obd_device *obd = class_exp2obd(exp);
568         struct lmv_obd *lmv = &obd->u.lmv;
569         struct getinfo_fid2path *gf;
570         struct lmv_tgt_desc *tgt;
571         struct getinfo_fid2path *remote_gf = NULL;
572         struct lu_fid root_fid;
573         int remote_gf_size = 0;
574         int currentisenc = 0;
575         int globalisenc = 0;
576         int rc;
577
578         gf = karg;
579         tgt = lmv_fid2tgt(lmv, &gf->gf_fid);
580         if (IS_ERR(tgt))
581                 RETURN(PTR_ERR(tgt));
582
583         root_fid = *gf->gf_u.gf_root_fid;
584         LASSERT(fid_is_sane(&root_fid));
585
586 repeat_fid2path:
587         rc = obd_iocontrol(OBD_IOC_FID2PATH, tgt->ltd_exp, len, gf, uarg);
588         if (rc != 0 && rc != -EREMOTE)
589                 GOTO(out_fid2path, rc);
590
591         if (gf->gf_u.gf_path[0] == '/') {
592                 /* by convention, server side (mdt_path_current()) puts
593                  * a leading '/' to tell client that we are dealing with
594                  * an encrypted file
595                  */
596                 currentisenc = 1;
597                 globalisenc = 1;
598         } else {
599                 currentisenc = 0;
600         }
601
602         /* If remote_gf != NULL, it means just building the
603          * path on the remote MDT, copy this path segment to gf.
604          */
605         if (remote_gf != NULL) {
606                 struct getinfo_fid2path *ori_gf;
607                 int oldisenc = 0;
608                 char *ptr;
609                 int len;
610
611                 ori_gf = (struct getinfo_fid2path *)karg;
612                 if (strlen(ori_gf->gf_u.gf_path) + 1 +
613                     strlen(gf->gf_u.gf_path) + 1 > ori_gf->gf_pathlen)
614                         GOTO(out_fid2path, rc = -EOVERFLOW);
615
616                 ptr = ori_gf->gf_u.gf_path;
617                 oldisenc = ptr[0] == '/';
618
619                 len = strlen(gf->gf_u.gf_path);
620                 if (len) {
621                         /* move the current path to the right to release space
622                          * for closer-to-root part
623                          */
624                         memmove(ptr + len - currentisenc + 1 + globalisenc,
625                                 ptr + oldisenc,
626                                 strlen(ori_gf->gf_u.gf_path) - oldisenc + 1);
627                         if (globalisenc)
628                                 *(ptr++) = '/';
629                         memcpy(ptr, gf->gf_u.gf_path + currentisenc,
630                                len - currentisenc);
631                         ptr[len - currentisenc] = '/';
632                 }
633         }
634
635         CDEBUG(D_INFO, "%s: get path %s "DFID" rec: %llu ln: %u\n",
636                tgt->ltd_exp->exp_obd->obd_name,
637                gf->gf_u.gf_path, PFID(&gf->gf_fid), gf->gf_recno,
638                gf->gf_linkno);
639
640         if (rc == 0)
641                 GOTO(out_fid2path, rc);
642
643         /* sigh, has to go to another MDT to do path building further */
644         if (remote_gf == NULL) {
645                 remote_gf_size = sizeof(*remote_gf) + len - sizeof(*gf);
646                 OBD_ALLOC(remote_gf, remote_gf_size);
647                 if (remote_gf == NULL)
648                         GOTO(out_fid2path, rc = -ENOMEM);
649                 remote_gf->gf_pathlen = len - sizeof(*gf);
650         }
651
652         if (!fid_is_sane(&gf->gf_fid)) {
653                 CERROR("%s: invalid FID "DFID": rc = %d\n",
654                        tgt->ltd_exp->exp_obd->obd_name,
655                        PFID(&gf->gf_fid), -EINVAL);
656                 GOTO(out_fid2path, rc = -EINVAL);
657         }
658
659         tgt = lmv_fid2tgt(lmv, &gf->gf_fid);
660         if (IS_ERR(tgt))
661                 GOTO(out_fid2path, rc = -EINVAL);
662
663         remote_gf->gf_fid = gf->gf_fid;
664         remote_gf->gf_recno = -1;
665         remote_gf->gf_linkno = -1;
666         memset(remote_gf->gf_u.gf_path, 0, remote_gf->gf_pathlen);
667         *remote_gf->gf_u.gf_root_fid = root_fid;
668         gf = remote_gf;
669         goto repeat_fid2path;
670
671 out_fid2path:
672         if (remote_gf != NULL)
673                 OBD_FREE(remote_gf, remote_gf_size);
674         RETURN(rc);
675 }
676
677 static int lmv_hsm_req_count(struct lmv_obd *lmv,
678                              const struct hsm_user_request *hur,
679                              const struct lmv_tgt_desc *tgt_mds)
680 {
681         struct lmv_tgt_desc *curr_tgt;
682         __u32 i;
683         int nr = 0;
684
685         /* count how many requests must be sent to the given target */
686         for (i = 0; i < hur->hur_request.hr_itemcount; i++) {
687                 curr_tgt = lmv_fid2tgt(lmv, &hur->hur_user_item[i].hui_fid);
688                 if (IS_ERR(curr_tgt))
689                         RETURN(PTR_ERR(curr_tgt));
690                 if (obd_uuid_equals(&curr_tgt->ltd_uuid, &tgt_mds->ltd_uuid))
691                         nr++;
692         }
693         return nr;
694 }
695
696 static int lmv_hsm_req_build(struct lmv_obd *lmv,
697                               struct hsm_user_request *hur_in,
698                               const struct lmv_tgt_desc *tgt_mds,
699                               struct hsm_user_request *hur_out)
700 {
701         __u32 i, nr_out;
702         struct lmv_tgt_desc *curr_tgt;
703
704         /* build the hsm_user_request for the given target */
705         hur_out->hur_request = hur_in->hur_request;
706         nr_out = 0;
707         for (i = 0; i < hur_in->hur_request.hr_itemcount; i++) {
708                 curr_tgt = lmv_fid2tgt(lmv, &hur_in->hur_user_item[i].hui_fid);
709                 if (IS_ERR(curr_tgt))
710                         RETURN(PTR_ERR(curr_tgt));
711                 if (obd_uuid_equals(&curr_tgt->ltd_uuid, &tgt_mds->ltd_uuid)) {
712                         hur_out->hur_user_item[nr_out] =
713                                                 hur_in->hur_user_item[i];
714                         nr_out++;
715                 }
716         }
717         hur_out->hur_request.hr_itemcount = nr_out;
718         memcpy(hur_data(hur_out), hur_data(hur_in),
719                hur_in->hur_request.hr_data_len);
720
721         RETURN(0);
722 }
723
724 static int lmv_hsm_ct_unregister(struct obd_device *obd, unsigned int cmd,
725                                  int len, struct lustre_kernelcomm *lk,
726                                  void __user *uarg)
727 {
728         struct lmv_obd *lmv = &obd->u.lmv;
729         struct lu_tgt_desc *tgt;
730         int rc;
731
732         ENTRY;
733
734         /* unregister request (call from llapi_hsm_copytool_fini) */
735         lmv_foreach_connected_tgt(lmv, tgt)
736                 /* best effort: try to clean as much as possible
737                  * (continue on error) */
738                 obd_iocontrol(cmd, tgt->ltd_exp, len, lk, uarg);
739
740         /* Whatever the result, remove copytool from kuc groups.
741          * Unreached coordinators will get EPIPE on next requests
742          * and will unregister automatically.
743          */
744         rc = libcfs_kkuc_group_rem(&obd->obd_uuid, lk->lk_uid, lk->lk_group);
745
746         RETURN(rc);
747 }
748
749 static int lmv_hsm_ct_register(struct obd_device *obd, unsigned int cmd,
750                                int len, struct lustre_kernelcomm *lk,
751                                void __user *uarg)
752 {
753         struct lmv_obd *lmv = &obd->u.lmv;
754         struct file *filp;
755         bool any_set = false;
756         struct kkuc_ct_data *kcd;
757         size_t kcd_size;
758         struct lu_tgt_desc *tgt;
759         __u32 i;
760         int err;
761         int rc = 0;
762
763         ENTRY;
764
765         filp = fget(lk->lk_wfd);
766         if (!filp)
767                 RETURN(-EBADF);
768
769         if (lk->lk_flags & LK_FLG_DATANR)
770                 kcd_size = offsetof(struct kkuc_ct_data,
771                                     kcd_archives[lk->lk_data_count]);
772         else
773                 kcd_size = sizeof(*kcd);
774
775         OBD_ALLOC(kcd, kcd_size);
776         if (kcd == NULL)
777                 GOTO(err_fput, rc = -ENOMEM);
778
779         kcd->kcd_nr_archives = lk->lk_data_count;
780         if (lk->lk_flags & LK_FLG_DATANR) {
781                 kcd->kcd_magic = KKUC_CT_DATA_ARRAY_MAGIC;
782                 if (lk->lk_data_count > 0)
783                         memcpy(kcd->kcd_archives, lk->lk_data,
784                                sizeof(*kcd->kcd_archives) * lk->lk_data_count);
785         } else {
786                 kcd->kcd_magic = KKUC_CT_DATA_BITMAP_MAGIC;
787         }
788
789         rc = libcfs_kkuc_group_add(filp, &obd->obd_uuid, lk->lk_uid,
790                                    lk->lk_group, kcd, kcd_size);
791         OBD_FREE(kcd, kcd_size);
792         if (rc)
793                 GOTO(err_fput, rc);
794
795         /* All or nothing: try to register to all MDS.
796          * In case of failure, unregister from previous MDS,
797          * except if it because of inactive target. */
798         lmv_foreach_connected_tgt(lmv, tgt) {
799                 err = obd_iocontrol(cmd, tgt->ltd_exp, len, lk, uarg);
800                 if (err) {
801                         if (tgt->ltd_active) {
802                                 /* permanent error */
803                                 CERROR("%s: iocontrol MDC %s on MDT"
804                                        " idx %d cmd %x: err = %d\n",
805                                        lmv2obd_dev(lmv)->obd_name,
806                                        tgt->ltd_uuid.uuid, tgt->ltd_index, cmd,
807                                        err);
808                                 rc = err;
809                                 lk->lk_flags |= LK_FLG_STOP;
810                                 i = tgt->ltd_index;
811                                 /* unregister from previous MDS */
812                                 lmv_foreach_connected_tgt(lmv, tgt) {
813                                         if (tgt->ltd_index >= i)
814                                                 break;
815
816                                         obd_iocontrol(cmd, tgt->ltd_exp, len,
817                                                       lk, uarg);
818                                 }
819                                 GOTO(err_kkuc_rem, rc);
820                         }
821                         /* else: transient error.
822                          * kuc will register to the missing MDT
823                          * when it is back */
824                 } else {
825                         any_set = true;
826                 }
827         }
828
829         if (!any_set)
830                 /* no registration done: return error */
831                 GOTO(err_kkuc_rem, rc = -ENOTCONN);
832
833         RETURN(0);
834
835 err_kkuc_rem:
836         libcfs_kkuc_group_rem(&obd->obd_uuid, lk->lk_uid, lk->lk_group);
837
838 err_fput:
839         fput(filp);
840         return rc;
841 }
842
843 static int lmv_iocontrol(unsigned int cmd, struct obd_export *exp,
844                          int len, void *karg, void __user *uarg)
845 {
846         struct obd_device *obd = class_exp2obd(exp);
847         struct lmv_obd *lmv = &obd->u.lmv;
848         struct lu_tgt_desc *tgt = NULL;
849         int set = 0;
850         __u32 count = lmv->lmv_mdt_count;
851         int rc = 0;
852
853         ENTRY;
854         CDEBUG(D_IOCTL, "%s: cmd=%x len=%u karg=%pK uarg=%pK\n",
855                exp->exp_obd->obd_name, cmd, len, karg, uarg);
856
857         if (count == 0)
858                 RETURN(-ENOTTY);
859
860         switch (cmd) {
861         case IOC_OBD_STATFS: {
862                 struct obd_ioctl_data *data = karg;
863                 struct obd_device *mdc_obd;
864                 struct obd_statfs stat_buf = {0};
865                 __u32 index;
866
867                 memcpy(&index, data->ioc_inlbuf2, sizeof(__u32));
868
869                 if (index >= lmv->lmv_mdt_descs.ltd_tgts_size)
870                         RETURN(-ENODEV);
871
872                 tgt = lmv_tgt(lmv, index);
873                 if (!tgt)
874                         RETURN(-EAGAIN);
875
876                 if (!tgt->ltd_active)
877                         RETURN(-ENODATA);
878
879                 mdc_obd = class_exp2obd(tgt->ltd_exp);
880                 if (!mdc_obd)
881                         RETURN(-EINVAL);
882
883                 /* copy UUID */
884                 if (copy_to_user(data->ioc_pbuf2, obd2cli_tgt(mdc_obd),
885                                  min((int) data->ioc_plen2,
886                                      (int) sizeof(struct obd_uuid))))
887                         RETURN(-EFAULT);
888
889                 rc = obd_statfs(NULL, tgt->ltd_exp, &stat_buf,
890                                 ktime_get_seconds() - OBD_STATFS_CACHE_SECONDS,
891                                 0);
892                 if (rc)
893                         RETURN(rc);
894                 if (copy_to_user(data->ioc_pbuf1, &stat_buf,
895                                  min((int) data->ioc_plen1,
896                                      (int) sizeof(stat_buf))))
897                         RETURN(-EFAULT);
898                 break;
899         }
900         case OBD_IOC_QUOTACTL: {
901                 struct if_quotactl *qctl = karg;
902                 struct obd_quotactl *oqctl;
903                 struct obd_import *imp;
904
905                 if (qctl->qc_valid == QC_MDTIDX) {
906                         tgt = lmv_tgt(lmv, qctl->qc_idx);
907                 } else if (qctl->qc_valid == QC_UUID) {
908                         lmv_foreach_tgt(lmv, tgt) {
909                                 if (!obd_uuid_equals(&tgt->ltd_uuid,
910                                                      &qctl->obd_uuid))
911                                         continue;
912
913                                 if (!tgt->ltd_exp)
914                                         RETURN(-EINVAL);
915
916                                 break;
917                         }
918                 } else {
919                         RETURN(-EINVAL);
920                 }
921
922                 if (!tgt)
923                         RETURN(-ENODEV);
924
925                 if (!tgt->ltd_exp)
926                         RETURN(-EINVAL);
927
928                 imp = class_exp2cliimp(tgt->ltd_exp);
929                 if (!tgt->ltd_active && imp->imp_state != LUSTRE_IMP_IDLE) {
930                         qctl->qc_valid = QC_MDTIDX;
931                         qctl->obd_uuid = tgt->ltd_uuid;
932                         RETURN(-ENODATA);
933                 }
934
935                 OBD_ALLOC_PTR(oqctl);
936                 if (!oqctl)
937                         RETURN(-ENOMEM);
938
939                 QCTL_COPY(oqctl, qctl);
940                 rc = obd_quotactl(tgt->ltd_exp, oqctl);
941                 if (rc == 0) {
942                         QCTL_COPY(qctl, oqctl);
943                         qctl->qc_valid = QC_MDTIDX;
944                         qctl->obd_uuid = tgt->ltd_uuid;
945                 }
946                 OBD_FREE_PTR(oqctl);
947                 break;
948         }
949         case LL_IOC_GET_CONNECT_FLAGS: {
950                 tgt = lmv_tgt(lmv, 0);
951                 rc = -ENODATA;
952                 if (tgt && tgt->ltd_exp)
953                         rc = obd_iocontrol(cmd, tgt->ltd_exp, len, karg, uarg);
954                 break;
955         }
956         case LL_IOC_FID2MDTIDX: {
957                 struct lu_fid *fid = karg;
958                 int             mdt_index;
959
960                 rc = lmv_fld_lookup(lmv, fid, &mdt_index);
961                 if (rc != 0)
962                         RETURN(rc);
963
964                 /* Note: this is from llite(see ll_dir_ioctl()), @uarg does not
965                  * point to user space memory for FID2MDTIDX. */
966                 *(__u32 *)uarg = mdt_index;
967                 break;
968         }
969         case OBD_IOC_FID2PATH: {
970                 rc = lmv_fid2path(exp, len, karg, uarg);
971                 break;
972         }
973         case LL_IOC_HSM_STATE_GET:
974         case LL_IOC_HSM_STATE_SET:
975         case LL_IOC_HSM_ACTION: {
976                 struct md_op_data *op_data = karg;
977
978                 tgt = lmv_fid2tgt(lmv, &op_data->op_fid1);
979                 if (IS_ERR(tgt))
980                         RETURN(PTR_ERR(tgt));
981
982                 if (tgt->ltd_exp == NULL)
983                         RETURN(-EINVAL);
984
985                 rc = obd_iocontrol(cmd, tgt->ltd_exp, len, karg, uarg);
986                 break;
987         }
988         case LL_IOC_HSM_PROGRESS: {
989                 const struct hsm_progress_kernel *hpk = karg;
990
991                 tgt = lmv_fid2tgt(lmv, &hpk->hpk_fid);
992                 if (IS_ERR(tgt))
993                         RETURN(PTR_ERR(tgt));
994                 rc = obd_iocontrol(cmd, tgt->ltd_exp, len, karg, uarg);
995                 break;
996         }
997         case LL_IOC_HSM_REQUEST: {
998                 struct hsm_user_request *hur = karg;
999                 unsigned int reqcount = hur->hur_request.hr_itemcount;
1000
1001                 if (reqcount == 0)
1002                         RETURN(0);
1003
1004                 /* if the request is about a single fid
1005                  * or if there is a single MDS, no need to split
1006                  * the request. */
1007                 if (reqcount == 1 || count == 1) {
1008                         tgt = lmv_fid2tgt(lmv, &hur->hur_user_item[0].hui_fid);
1009                         if (IS_ERR(tgt))
1010                                 RETURN(PTR_ERR(tgt));
1011                         rc = obd_iocontrol(cmd, tgt->ltd_exp, len, karg, uarg);
1012                 } else {
1013                         /* split fid list to their respective MDS */
1014                         lmv_foreach_connected_tgt(lmv, tgt) {
1015                                 int nr, rc1;
1016                                 size_t reqlen;
1017                                 struct hsm_user_request *req;
1018
1019                                 nr = lmv_hsm_req_count(lmv, hur, tgt);
1020                                 if (nr < 0)
1021                                         RETURN(nr);
1022                                 if (nr == 0) /* nothing for this MDS */
1023                                         continue;
1024
1025                                 /* build a request with fids for this MDS */
1026                                 reqlen = offsetof(typeof(*hur),
1027                                                   hur_user_item[nr])
1028                                                 + hur->hur_request.hr_data_len;
1029                                 OBD_ALLOC_LARGE(req, reqlen);
1030                                 if (req == NULL)
1031                                         RETURN(-ENOMEM);
1032                                 rc1 = lmv_hsm_req_build(lmv, hur, tgt, req);
1033                                 if (rc1 < 0)
1034                                         GOTO(hsm_req_err, rc1);
1035                                 rc1 = obd_iocontrol(cmd, tgt->ltd_exp, reqlen,
1036                                                     req, uarg);
1037 hsm_req_err:
1038                                 if (rc1 != 0 && rc == 0)
1039                                         rc = rc1;
1040                                 OBD_FREE_LARGE(req, reqlen);
1041                         }
1042                 }
1043                 break;
1044         }
1045         case LL_IOC_LOV_SWAP_LAYOUTS: {
1046                 struct md_op_data *op_data = karg;
1047                 struct lmv_tgt_desc *tgt1, *tgt2;
1048
1049                 tgt1 = lmv_fid2tgt(lmv, &op_data->op_fid1);
1050                 if (IS_ERR(tgt1))
1051                         RETURN(PTR_ERR(tgt1));
1052
1053                 tgt2 = lmv_fid2tgt(lmv, &op_data->op_fid2);
1054                 if (IS_ERR(tgt2))
1055                         RETURN(PTR_ERR(tgt2));
1056
1057                 if ((tgt1->ltd_exp == NULL) || (tgt2->ltd_exp == NULL))
1058                         RETURN(-EINVAL);
1059
1060                 /* only files on same MDT can have their layouts swapped */
1061                 if (tgt1->ltd_index != tgt2->ltd_index)
1062                         RETURN(-EPERM);
1063
1064                 rc = obd_iocontrol(cmd, tgt1->ltd_exp, len, karg, uarg);
1065                 break;
1066         }
1067         case LL_IOC_HSM_CT_START: {
1068                 struct lustre_kernelcomm *lk = karg;
1069
1070                 if (lk->lk_flags & LK_FLG_STOP)
1071                         rc = lmv_hsm_ct_unregister(obd, cmd, len, lk, uarg);
1072                 else
1073                         rc = lmv_hsm_ct_register(obd, cmd, len, lk, uarg);
1074                 break;
1075         }
1076         default:
1077                 lmv_foreach_connected_tgt(lmv, tgt) {
1078                         struct obd_device *mdc_obd;
1079                         int err;
1080
1081                         /* ll_umount_begin() sets force flag but for lmv, not
1082                          * mdc. Let's pass it through */
1083                         mdc_obd = class_exp2obd(tgt->ltd_exp);
1084                         mdc_obd->obd_force = obd->obd_force;
1085                         err = obd_iocontrol(cmd, tgt->ltd_exp, len, karg, uarg);
1086                         if (err) {
1087                                 if (tgt->ltd_active) {
1088                                         OBD_IOC_ERROR(obd->obd_name, cmd,
1089                                                       tgt->ltd_uuid.uuid, err);
1090                                         if (!rc)
1091                                                 rc = err;
1092                                 }
1093                         } else
1094                                 set = 1;
1095                 }
1096                 if (!set && !rc)
1097                         rc = -EIO;
1098         }
1099         RETURN(rc);
1100 }
1101
1102 int lmv_fid_alloc(const struct lu_env *env, struct obd_export *exp,
1103                   struct lu_fid *fid, struct md_op_data *op_data)
1104 {
1105         struct obd_device *obd = class_exp2obd(exp);
1106         struct lmv_obd *lmv = &obd->u.lmv;
1107         struct lmv_tgt_desc *tgt;
1108         int rc;
1109
1110         ENTRY;
1111
1112         LASSERT(op_data);
1113         LASSERT(fid);
1114
1115         tgt = lmv_tgt(lmv, op_data->op_mds);
1116         if (!tgt)
1117                 RETURN(-ENODEV);
1118
1119         if (!tgt->ltd_active || !tgt->ltd_exp)
1120                 RETURN(-ENODEV);
1121
1122         /*
1123          * New seq alloc and FLD setup should be atomic. Otherwise we may find
1124          * on server that seq in new allocated fid is not yet known.
1125          */
1126         mutex_lock(&tgt->ltd_fid_mutex);
1127         rc = obd_fid_alloc(NULL, tgt->ltd_exp, fid, NULL);
1128         mutex_unlock(&tgt->ltd_fid_mutex);
1129         if (rc > 0) {
1130                 LASSERT(fid_is_sane(fid));
1131                 rc = 0;
1132         }
1133
1134         RETURN(rc);
1135 }
1136
1137 static int lmv_setup(struct obd_device *obd, struct lustre_cfg *lcfg)
1138 {
1139         struct lmv_obd *lmv = &obd->u.lmv;
1140         struct lmv_desc *desc;
1141         struct lnet_processid lnet_id;
1142         int i = 0;
1143         int rc;
1144
1145         ENTRY;
1146
1147         if (LUSTRE_CFG_BUFLEN(lcfg, 1) < 1) {
1148                 CERROR("LMV setup requires a descriptor\n");
1149                 RETURN(-EINVAL);
1150         }
1151
1152         desc = (struct lmv_desc *)lustre_cfg_buf(lcfg, 1);
1153         if (sizeof(*desc) > LUSTRE_CFG_BUFLEN(lcfg, 1)) {
1154                 CERROR("Lmv descriptor size wrong: %d > %d\n",
1155                        (int)sizeof(*desc), LUSTRE_CFG_BUFLEN(lcfg, 1));
1156                 RETURN(-EINVAL);
1157         }
1158
1159         obd_str2uuid(&lmv->lmv_mdt_descs.ltd_lmv_desc.ld_uuid,
1160                      desc->ld_uuid.uuid);
1161         lmv->lmv_mdt_descs.ltd_lmv_desc.ld_tgt_count = 0;
1162         lmv->lmv_mdt_descs.ltd_lmv_desc.ld_active_tgt_count = 0;
1163         lmv->lmv_mdt_descs.ltd_lmv_desc.ld_qos_maxage =
1164                 LMV_DESC_QOS_MAXAGE_DEFAULT;
1165         lmv->max_def_easize = 0;
1166         lmv->max_easize = 0;
1167
1168         spin_lock_init(&lmv->lmv_lock);
1169
1170         /*
1171          * initialize rr_index to lower 32bit of netid, so that client
1172          * can distribute subdirs evenly from the beginning.
1173          */
1174         while (LNetGetId(i++, &lnet_id) != -ENOENT) {
1175                 if (!nid_is_lo0(&lnet_id.nid)) {
1176                         lmv->lmv_qos_rr_index = ntohl(lnet_id.nid.nid_addr[0]);
1177                         break;
1178                 }
1179         }
1180
1181         rc = lmv_tunables_init(obd);
1182         if (rc)
1183                 CWARN("%s: error adding LMV sysfs/debugfs files: rc = %d\n",
1184                       obd->obd_name, rc);
1185
1186         rc = fld_client_init(&lmv->lmv_fld, obd->obd_name,
1187                              LUSTRE_CLI_FLD_HASH_DHT);
1188         if (rc)
1189                 CERROR("Can't init FLD, err %d\n", rc);
1190
1191         rc = lu_tgt_descs_init(&lmv->lmv_mdt_descs, true);
1192         if (rc)
1193                 CWARN("%s: error initialize target table: rc = %d\n",
1194                       obd->obd_name, rc);
1195
1196         RETURN(rc);
1197 }
1198
1199 static int lmv_cleanup(struct obd_device *obd)
1200 {
1201         struct lmv_obd *lmv = &obd->u.lmv;
1202         struct lu_tgt_desc *tgt;
1203         struct lu_tgt_desc *tmp;
1204
1205         ENTRY;
1206
1207         fld_client_fini(&lmv->lmv_fld);
1208         fld_client_debugfs_fini(&lmv->lmv_fld);
1209
1210         lprocfs_obd_cleanup(obd);
1211         lprocfs_free_md_stats(obd);
1212
1213         lmv_foreach_tgt_safe(lmv, tgt, tmp)
1214                 lmv_del_target(lmv, tgt);
1215         lu_tgt_descs_fini(&lmv->lmv_mdt_descs);
1216
1217         RETURN(0);
1218 }
1219
1220 static int lmv_process_config(struct obd_device *obd, size_t len, void *buf)
1221 {
1222         struct lustre_cfg       *lcfg = buf;
1223         struct obd_uuid         obd_uuid;
1224         int                     gen;
1225         __u32                   index;
1226         int                     rc;
1227         ENTRY;
1228
1229         switch (lcfg->lcfg_command) {
1230         case LCFG_ADD_MDC:
1231                 /* modify_mdc_tgts add 0:lustre-clilmv  1:lustre-MDT0000_UUID
1232                  * 2:0  3:1  4:lustre-MDT0000-mdc_UUID */
1233                 if (LUSTRE_CFG_BUFLEN(lcfg, 1) > sizeof(obd_uuid.uuid))
1234                         GOTO(out, rc = -EINVAL);
1235
1236                 obd_str2uuid(&obd_uuid,  lustre_cfg_buf(lcfg, 1));
1237
1238                 if (sscanf(lustre_cfg_buf(lcfg, 2), "%u", &index) != 1)
1239                         GOTO(out, rc = -EINVAL);
1240                 if (sscanf(lustre_cfg_buf(lcfg, 3), "%d", &gen) != 1)
1241                         GOTO(out, rc = -EINVAL);
1242                 rc = lmv_add_target(obd, &obd_uuid, index, gen);
1243                 GOTO(out, rc);
1244         default:
1245                 CERROR("Unknown command: %d\n", lcfg->lcfg_command);
1246                 GOTO(out, rc = -EINVAL);
1247         }
1248 out:
1249         RETURN(rc);
1250 }
1251
1252 static int lmv_select_statfs_mdt(struct lmv_obd *lmv, __u32 flags)
1253 {
1254         int i;
1255
1256         if (flags & OBD_STATFS_FOR_MDT0)
1257                 return 0;
1258
1259         if (lmv->lmv_statfs_start || lmv->lmv_mdt_count == 1)
1260                 return lmv->lmv_statfs_start;
1261
1262         /* choose initial MDT for this client */
1263         for (i = 0;; i++) {
1264                 struct lnet_processid lnet_id;
1265                 if (LNetGetId(i, &lnet_id) == -ENOENT)
1266                         break;
1267
1268                 if (!nid_is_lo0(&lnet_id.nid)) {
1269                         /* We dont need a full 64-bit modulus, just enough
1270                          * to distribute the requests across MDTs evenly.
1271                          */
1272                         lmv->lmv_statfs_start = nidhash(&lnet_id.nid) %
1273                                                 lmv->lmv_mdt_count;
1274                         break;
1275                 }
1276         }
1277
1278         return lmv->lmv_statfs_start;
1279 }
1280
1281 static int lmv_statfs(const struct lu_env *env, struct obd_export *exp,
1282                       struct obd_statfs *osfs, time64_t max_age, __u32 flags)
1283 {
1284         struct obd_device *obd = class_exp2obd(exp);
1285         struct lmv_obd *lmv = &obd->u.lmv;
1286         struct obd_statfs *temp;
1287         struct lu_tgt_desc *tgt;
1288         __u32 i;
1289         __u32 idx;
1290         int rc = 0;
1291         int err = 0;
1292
1293         ENTRY;
1294
1295         OBD_ALLOC(temp, sizeof(*temp));
1296         if (temp == NULL)
1297                 RETURN(-ENOMEM);
1298
1299         /* distribute statfs among MDTs */
1300         idx = lmv_select_statfs_mdt(lmv, flags);
1301
1302         for (i = 0; i < lmv->lmv_mdt_descs.ltd_tgts_size; i++, idx++) {
1303                 idx = idx % lmv->lmv_mdt_descs.ltd_tgts_size;
1304                 tgt = lmv_tgt(lmv, idx);
1305                 if (!tgt || !tgt->ltd_exp)
1306                         continue;
1307
1308                 rc = obd_statfs(env, tgt->ltd_exp, temp, max_age,
1309                                 flags | OBD_STATFS_NESTED);
1310                 if (rc) {
1311                         CERROR("%s: can't stat MDS #%d: rc = %d\n",
1312                                tgt->ltd_exp->exp_obd->obd_name, i, rc);
1313                         err = rc;
1314                         /* Try another MDT */
1315                         if (flags & OBD_STATFS_SUM)
1316                                 continue;
1317                         GOTO(out_free_temp, rc);
1318                 }
1319
1320                 if (temp->os_state & OS_STATFS_SUM ||
1321                     flags == OBD_STATFS_FOR_MDT0) {
1322                         /* reset to the last aggregated values
1323                          * and don't sum with non-aggrated data */
1324                         /* If the statfs is from mount, it needs to retrieve
1325                          * necessary information from MDT0. i.e. mount does
1326                          * not need the merged osfs from all of MDT. Also
1327                          * clients can be mounted as long as MDT0 is in
1328                          * service */
1329                         *osfs = *temp;
1330                         GOTO(out_free_temp, rc);
1331                 }
1332
1333                 if (i == 0) {
1334                         *osfs = *temp;
1335                 } else {
1336                         osfs->os_bavail += temp->os_bavail;
1337                         osfs->os_blocks += temp->os_blocks;
1338                         osfs->os_ffree += temp->os_ffree;
1339                         osfs->os_files += temp->os_files;
1340                         osfs->os_granted += temp->os_granted;
1341                 }
1342         }
1343         /* There is no stats from some MDTs, data incomplete */
1344         if (err)
1345                 rc = err;
1346 out_free_temp:
1347         OBD_FREE(temp, sizeof(*temp));
1348         RETURN(rc);
1349 }
1350
1351 static int lmv_statfs_update(void *cookie, int rc)
1352 {
1353         struct obd_info *oinfo = cookie;
1354         struct obd_device *obd = oinfo->oi_obd;
1355         struct lmv_obd *lmv = &obd->u.lmv;
1356         struct lmv_tgt_desc *tgt = oinfo->oi_tgt;
1357         struct obd_statfs *osfs = oinfo->oi_osfs;
1358
1359         /*
1360          * NB: don't deactivate TGT upon error, because we may not trigger async
1361          * statfs any longer, then there is no chance to activate TGT.
1362          */
1363         if (!rc) {
1364                 spin_lock(&lmv->lmv_lock);
1365                 tgt->ltd_statfs = *osfs;
1366                 tgt->ltd_statfs_age = ktime_get_seconds();
1367                 spin_unlock(&lmv->lmv_lock);
1368                 set_bit(LQ_DIRTY, &lmv->lmv_qos.lq_flags);
1369         }
1370
1371         return rc;
1372 }
1373
1374 /* update tgt statfs async if it's ld_qos_maxage old */
1375 int lmv_statfs_check_update(struct obd_device *obd, struct lmv_tgt_desc *tgt)
1376 {
1377         struct obd_info oinfo = {
1378                 .oi_obd = obd,
1379                 .oi_tgt = tgt,
1380                 .oi_cb_up = lmv_statfs_update,
1381         };
1382         int rc;
1383
1384         if (ktime_get_seconds() - tgt->ltd_statfs_age <
1385             obd->u.lmv.lmv_mdt_descs.ltd_lmv_desc.ld_qos_maxage)
1386                 return 0;
1387
1388         rc = obd_statfs_async(tgt->ltd_exp, &oinfo, 0, NULL);
1389
1390         return rc;
1391 }
1392
1393 static int lmv_get_root(struct obd_export *exp, const char *fileset,
1394                         struct lu_fid *fid)
1395 {
1396         struct obd_device *obd = exp->exp_obd;
1397         struct lmv_obd *lmv = &obd->u.lmv;
1398         struct lu_tgt_desc *tgt = lmv_tgt(lmv, 0);
1399         int rc;
1400
1401         ENTRY;
1402
1403         if (!tgt)
1404                 RETURN(-ENODEV);
1405
1406         rc = md_get_root(tgt->ltd_exp, fileset, fid);
1407         RETURN(rc);
1408 }
1409
1410 static int lmv_getxattr(struct obd_export *exp, const struct lu_fid *fid,
1411                         u64 obd_md_valid, const char *name, size_t buf_size,
1412                         struct ptlrpc_request **req)
1413 {
1414         struct obd_device *obd = exp->exp_obd;
1415         struct lmv_obd *lmv = &obd->u.lmv;
1416         struct lmv_tgt_desc *tgt;
1417         int rc;
1418
1419         ENTRY;
1420
1421         tgt = lmv_fid2tgt(lmv, fid);
1422         if (IS_ERR(tgt))
1423                 RETURN(PTR_ERR(tgt));
1424
1425         rc = md_getxattr(tgt->ltd_exp, fid, obd_md_valid, name, buf_size, req);
1426
1427         RETURN(rc);
1428 }
1429
1430 static int lmv_setxattr(struct obd_export *exp, const struct lu_fid *fid,
1431                         u64 obd_md_valid, const char *name,
1432                         const void *value, size_t value_size,
1433                         unsigned int xattr_flags, u32 suppgid,
1434                         struct ptlrpc_request **req)
1435 {
1436         struct obd_device *obd = exp->exp_obd;
1437         struct lmv_obd *lmv = &obd->u.lmv;
1438         struct lmv_tgt_desc *tgt;
1439         int rc;
1440
1441         ENTRY;
1442
1443         tgt = lmv_fid2tgt(lmv, fid);
1444         if (IS_ERR(tgt))
1445                 RETURN(PTR_ERR(tgt));
1446
1447         rc = md_setxattr(tgt->ltd_exp, fid, obd_md_valid, name,
1448                          value, value_size, xattr_flags, suppgid, req);
1449
1450         RETURN(rc);
1451 }
1452
1453 static int lmv_getattr(struct obd_export *exp, struct md_op_data *op_data,
1454                        struct ptlrpc_request **request)
1455 {
1456         struct obd_device *obd = exp->exp_obd;
1457         struct lmv_obd *lmv = &obd->u.lmv;
1458         struct lmv_tgt_desc *tgt;
1459         int rc;
1460
1461         ENTRY;
1462
1463         tgt = lmv_fid2tgt(lmv, &op_data->op_fid1);
1464         if (IS_ERR(tgt))
1465                 RETURN(PTR_ERR(tgt));
1466
1467         if (op_data->op_flags & MF_GET_MDT_IDX) {
1468                 op_data->op_mds = tgt->ltd_index;
1469                 RETURN(0);
1470         }
1471
1472         rc = md_getattr(tgt->ltd_exp, op_data, request);
1473
1474         RETURN(rc);
1475 }
1476
1477 static int lmv_null_inode(struct obd_export *exp, const struct lu_fid *fid)
1478 {
1479         struct obd_device *obd = exp->exp_obd;
1480         struct lmv_obd *lmv = &obd->u.lmv;
1481         struct lu_tgt_desc *tgt;
1482
1483         ENTRY;
1484
1485         CDEBUG(D_INODE, "CBDATA for "DFID"\n", PFID(fid));
1486
1487         /*
1488          * With DNE every object can have two locks in different namespaces:
1489          * lookup lock in space of MDT storing direntry and update/open lock in
1490          * space of MDT storing inode.
1491          */
1492         lmv_foreach_connected_tgt(lmv, tgt)
1493                 md_null_inode(tgt->ltd_exp, fid);
1494
1495         RETURN(0);
1496 }
1497
1498 static int lmv_close(struct obd_export *exp, struct md_op_data *op_data,
1499                      struct md_open_data *mod, struct ptlrpc_request **request)
1500 {
1501         struct obd_device *obd = exp->exp_obd;
1502         struct lmv_obd *lmv = &obd->u.lmv;
1503         struct lmv_tgt_desc *tgt;
1504         int rc;
1505
1506         ENTRY;
1507
1508         tgt = lmv_fid2tgt(lmv, &op_data->op_fid1);
1509         if (IS_ERR(tgt))
1510                 RETURN(PTR_ERR(tgt));
1511
1512         CDEBUG(D_INODE, "CLOSE "DFID"\n", PFID(&op_data->op_fid1));
1513         rc = md_close(tgt->ltd_exp, op_data, mod, request);
1514         RETURN(rc);
1515 }
1516
1517 static struct lu_tgt_desc *lmv_locate_tgt_qos(struct lmv_obd *lmv,
1518                                               struct md_op_data *op_data)
1519 {
1520         struct lu_tgt_desc *tgt, *cur = NULL;
1521         __u64 total_avail = 0;
1522         __u64 total_weight = 0;
1523         __u64 cur_weight = 0;
1524         int total_usable = 0;
1525         __u64 rand;
1526         int rc;
1527
1528         ENTRY;
1529
1530         if (!ltd_qos_is_usable(&lmv->lmv_mdt_descs))
1531                 RETURN(ERR_PTR(-EAGAIN));
1532
1533         down_write(&lmv->lmv_qos.lq_rw_sem);
1534
1535         if (!ltd_qos_is_usable(&lmv->lmv_mdt_descs))
1536                 GOTO(unlock, tgt = ERR_PTR(-EAGAIN));
1537
1538         rc = ltd_qos_penalties_calc(&lmv->lmv_mdt_descs);
1539         if (rc)
1540                 GOTO(unlock, tgt = ERR_PTR(rc));
1541
1542         lmv_foreach_tgt(lmv, tgt) {
1543                 if (!tgt->ltd_exp || !tgt->ltd_active) {
1544                         tgt->ltd_qos.ltq_usable = 0;
1545                         continue;
1546                 }
1547
1548                 tgt->ltd_qos.ltq_usable = 1;
1549                 lu_tgt_qos_weight_calc(tgt, true);
1550                 if (tgt->ltd_index == op_data->op_mds)
1551                         cur = tgt;
1552                 total_avail += tgt->ltd_qos.ltq_avail;
1553                 total_weight += tgt->ltd_qos.ltq_weight;
1554                 total_usable++;
1555         }
1556
1557         /* If current MDT has above-average space and dir is not aleady using
1558          * round-robin to spread across more MDTs, stay on the parent MDT
1559          * to avoid creating needless remote MDT directories.  Remote dirs
1560          * close to the root balance space more effectively than bottom dirs,
1561          * so prefer to create remote dirs at top level of directory tree.
1562          * "16 / (dir_depth + 10)" is the factor to make it less likely
1563          * for top-level directories to stay local unless they have more than
1564          * average free space, while deep dirs prefer local until more full.
1565          *    depth=0 -> 160%, depth=3 -> 123%, depth=6 -> 100%,
1566          *    depth=9 -> 84%, depth=12 -> 73%, depth=15 -> 64%
1567          */
1568         if (!lmv_op_default_rr_mkdir(op_data)) {
1569                 rand = total_avail * 16 /
1570                         (total_usable * (op_data->op_dir_depth + 10));
1571                 if (cur && cur->ltd_qos.ltq_avail >= rand) {
1572                         tgt = cur;
1573                         GOTO(unlock, tgt);
1574                 }
1575         }
1576
1577         rand = lu_prandom_u64_max(total_weight);
1578
1579         lmv_foreach_connected_tgt(lmv, tgt) {
1580                 if (!tgt->ltd_qos.ltq_usable)
1581                         continue;
1582
1583                 cur_weight += tgt->ltd_qos.ltq_weight;
1584                 if (cur_weight < rand)
1585                         continue;
1586
1587                 ltd_qos_update(&lmv->lmv_mdt_descs, tgt, &total_weight);
1588                 GOTO(unlock, tgt);
1589         }
1590
1591         /* no proper target found */
1592         GOTO(unlock, tgt = ERR_PTR(-EAGAIN));
1593 unlock:
1594         up_write(&lmv->lmv_qos.lq_rw_sem);
1595
1596         return tgt;
1597 }
1598
1599 static struct lu_tgt_desc *lmv_locate_tgt_rr(struct lmv_obd *lmv)
1600 {
1601         struct lu_tgt_desc *tgt;
1602         int i;
1603         int index;
1604
1605         ENTRY;
1606
1607         spin_lock(&lmv->lmv_lock);
1608         for (i = 0; i < lmv->lmv_mdt_descs.ltd_tgts_size; i++) {
1609                 index = (i + lmv->lmv_qos_rr_index) %
1610                         lmv->lmv_mdt_descs.ltd_tgts_size;
1611                 tgt = lmv_tgt(lmv, index);
1612                 if (!tgt || !tgt->ltd_exp || !tgt->ltd_active)
1613                         continue;
1614
1615                 lmv->lmv_qos_rr_index = (tgt->ltd_index + 1) %
1616                                         lmv->lmv_mdt_descs.ltd_tgts_size;
1617                 spin_unlock(&lmv->lmv_lock);
1618
1619                 RETURN(tgt);
1620         }
1621         spin_unlock(&lmv->lmv_lock);
1622
1623         RETURN(ERR_PTR(-ENODEV));
1624 }
1625
1626 /* locate MDT which is less full (avoid the most full MDT) */
1627 static struct lu_tgt_desc *lmv_locate_tgt_lf(struct lmv_obd *lmv)
1628 {
1629         struct lu_tgt_desc *min = NULL;
1630         struct lu_tgt_desc *tgt;
1631         __u64 avail = 0;
1632         __u64 rand;
1633
1634         ENTRY;
1635
1636         if (!ltd_qos_is_usable(&lmv->lmv_mdt_descs))
1637                 RETURN(ERR_PTR(-EAGAIN));
1638
1639         down_write(&lmv->lmv_qos.lq_rw_sem);
1640
1641         if (!ltd_qos_is_usable(&lmv->lmv_mdt_descs))
1642                 GOTO(unlock, tgt = ERR_PTR(-EAGAIN));
1643
1644         lmv_foreach_tgt(lmv, tgt) {
1645                 if (!tgt->ltd_exp || !tgt->ltd_active) {
1646                         tgt->ltd_qos.ltq_usable = 0;
1647                         continue;
1648                 }
1649
1650                 tgt->ltd_qos.ltq_usable = 1;
1651                 lu_tgt_qos_weight_calc(tgt, true);
1652                 avail += tgt->ltd_qos.ltq_avail;
1653                 if (!min || min->ltd_qos.ltq_avail > tgt->ltd_qos.ltq_avail)
1654                         min = tgt;
1655         }
1656
1657         /* avoid the most full MDT */
1658         if (min)
1659                 avail -= min->ltd_qos.ltq_avail;
1660
1661         rand = lu_prandom_u64_max(avail);
1662         avail = 0;
1663         lmv_foreach_connected_tgt(lmv, tgt) {
1664                 if (!tgt->ltd_qos.ltq_usable)
1665                         continue;
1666
1667                 if (tgt == min)
1668                         continue;
1669
1670                 avail += tgt->ltd_qos.ltq_avail;
1671                 if (avail < rand)
1672                         continue;
1673
1674                 GOTO(unlock, tgt);
1675         }
1676
1677         /* no proper target found */
1678         GOTO(unlock, tgt = ERR_PTR(-EAGAIN));
1679 unlock:
1680         up_write(&lmv->lmv_qos.lq_rw_sem);
1681
1682         RETURN(tgt);
1683 }
1684
1685 /* locate MDT by file name, for striped directory, the file name hash decides
1686  * which stripe its dirent is stored.
1687  */
1688 static struct lmv_tgt_desc *
1689 lmv_locate_tgt_by_name(struct lmv_obd *lmv, struct lmv_stripe_md *lsm,
1690                        const char *name, int namelen, struct lu_fid *fid,
1691                        __u32 *mds, bool new_layout)
1692 {
1693         struct lmv_tgt_desc *tgt;
1694         const struct lmv_oinfo *oinfo;
1695
1696         if (!lmv_dir_striped(lsm) || !namelen) {
1697                 tgt = lmv_fid2tgt(lmv, fid);
1698                 if (IS_ERR(tgt))
1699                         return tgt;
1700
1701                 *mds = tgt->ltd_index;
1702                 return tgt;
1703         }
1704
1705         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_NAME_HASH)) {
1706                 if (cfs_fail_val >= lsm->lsm_md_stripe_count)
1707                         return ERR_PTR(-EBADF);
1708                 oinfo = &lsm->lsm_md_oinfo[cfs_fail_val];
1709         } else {
1710                 oinfo = lsm_name_to_stripe_info(lsm, name, namelen, new_layout);
1711                 if (IS_ERR(oinfo))
1712                         return ERR_CAST(oinfo);
1713         }
1714
1715         /* check stripe FID is sane */
1716         if (!fid_is_sane(&oinfo->lmo_fid))
1717                 return ERR_PTR(-ENODEV);
1718
1719         *fid = oinfo->lmo_fid;
1720         *mds = oinfo->lmo_mds;
1721         tgt = lmv_tgt(lmv, oinfo->lmo_mds);
1722
1723         CDEBUG(D_INODE, "locate MDT %u parent "DFID"\n", *mds, PFID(fid));
1724
1725         return tgt ? tgt : ERR_PTR(-ENODEV);
1726 }
1727
1728 /**
1729  * Locate MDT of op_data->op_fid1
1730  *
1731  * For striped directory, it will locate the stripe by name hash, if hash_type
1732  * is unknown, it will return the stripe specified by 'op_data->op_stripe_index'
1733  * which is set outside, and if dir is migrating, 'op_data->op_new_layout'
1734  * indicates whether old or new layout is used to locate.
1735  *
1736  * For plain direcotry, it just locate the MDT of op_data->op_fid1.
1737  *
1738  * \param[in] lmv               LMV device
1739  * \param[in/out] op_data       client MD stack parameters, name, namelen etc,
1740  *                              op_mds and op_fid1 will be updated if op_mea1
1741  *                              indicates fid1 represents a striped directory.
1742  *
1743  * retval               pointer to the lmv_tgt_desc if succeed.
1744  *                      ERR_PTR(errno) if failed.
1745  */
1746 struct lmv_tgt_desc *
1747 lmv_locate_tgt(struct lmv_obd *lmv, struct md_op_data *op_data)
1748 {
1749         struct lmv_stripe_md *lsm = op_data->op_mea1;
1750         struct lmv_oinfo *oinfo;
1751         struct lmv_tgt_desc *tgt;
1752
1753         if (lmv_dir_foreign(lsm))
1754                 return ERR_PTR(-ENODATA);
1755
1756         /* During creating VOLATILE file, it should honor the mdt
1757          * index if the file under striped dir is being restored, see
1758          * ct_restore(). */
1759         if (op_data->op_bias & MDS_CREATE_VOLATILE &&
1760             op_data->op_mds != LMV_OFFSET_DEFAULT) {
1761                 tgt = lmv_tgt(lmv, op_data->op_mds);
1762                 if (!tgt)
1763                         return ERR_PTR(-ENODEV);
1764
1765                 if (lmv_dir_striped(lsm)) {
1766                         int i;
1767
1768                         /* refill the right parent fid */
1769                         for (i = 0; i < lsm->lsm_md_stripe_count; i++) {
1770                                 oinfo = &lsm->lsm_md_oinfo[i];
1771                                 if (oinfo->lmo_mds == op_data->op_mds) {
1772                                         op_data->op_fid1 = oinfo->lmo_fid;
1773                                         break;
1774                                 }
1775                         }
1776
1777                         if (i == lsm->lsm_md_stripe_count)
1778                                 op_data->op_fid1 = lsm->lsm_md_oinfo[0].lmo_fid;
1779                 }
1780         } else if (lmv_dir_bad_hash(lsm)) {
1781                 LASSERT(op_data->op_stripe_index < lsm->lsm_md_stripe_count);
1782                 oinfo = &lsm->lsm_md_oinfo[op_data->op_stripe_index];
1783
1784                 op_data->op_fid1 = oinfo->lmo_fid;
1785                 op_data->op_mds = oinfo->lmo_mds;
1786                 tgt = lmv_tgt(lmv, oinfo->lmo_mds);
1787                 if (!tgt)
1788                         return ERR_PTR(-ENODEV);
1789         } else {
1790                 tgt = lmv_locate_tgt_by_name(lmv, op_data->op_mea1,
1791                                 op_data->op_name, op_data->op_namelen,
1792                                 &op_data->op_fid1, &op_data->op_mds,
1793                                 op_data->op_new_layout);
1794         }
1795
1796         return tgt;
1797 }
1798
1799 /* Locate MDT of op_data->op_fid2 for link/rename */
1800 static struct lmv_tgt_desc *
1801 lmv_locate_tgt2(struct lmv_obd *lmv, struct md_op_data *op_data)
1802 {
1803         struct lmv_tgt_desc *tgt;
1804         int rc;
1805
1806         LASSERT(op_data->op_name);
1807         if (lmv_dir_layout_changing(op_data->op_mea2)) {
1808                 struct lu_fid fid1 = op_data->op_fid1;
1809                 struct lmv_stripe_md *lsm1 = op_data->op_mea1;
1810                 struct ptlrpc_request *request = NULL;
1811
1812                 /*
1813                  * avoid creating new file under old layout of migrating
1814                  * directory, check it here.
1815                  */
1816                 tgt = lmv_locate_tgt_by_name(lmv, op_data->op_mea2,
1817                                 op_data->op_name, op_data->op_namelen,
1818                                 &op_data->op_fid2, &op_data->op_mds, false);
1819                 if (IS_ERR(tgt))
1820                         RETURN(tgt);
1821
1822                 op_data->op_fid1 = op_data->op_fid2;
1823                 op_data->op_mea1 = op_data->op_mea2;
1824                 rc = md_getattr_name(tgt->ltd_exp, op_data, &request);
1825                 op_data->op_fid1 = fid1;
1826                 op_data->op_mea1 = lsm1;
1827                 if (!rc) {
1828                         ptlrpc_req_finished(request);
1829                         RETURN(ERR_PTR(-EEXIST));
1830                 }
1831
1832                 if (rc != -ENOENT)
1833                         RETURN(ERR_PTR(rc));
1834         }
1835
1836         return lmv_locate_tgt_by_name(lmv, op_data->op_mea2, op_data->op_name,
1837                                 op_data->op_namelen, &op_data->op_fid2,
1838                                 &op_data->op_mds, true);
1839 }
1840
1841 int lmv_old_layout_lookup(struct lmv_obd *lmv, struct md_op_data *op_data)
1842 {
1843         struct lu_tgt_desc *tgt;
1844         struct ptlrpc_request *request;
1845         int rc;
1846
1847         LASSERT(lmv_dir_layout_changing(op_data->op_mea1));
1848         LASSERT(!op_data->op_new_layout);
1849
1850         tgt = lmv_locate_tgt(lmv, op_data);
1851         if (IS_ERR(tgt))
1852                 return PTR_ERR(tgt);
1853
1854         rc = md_getattr_name(tgt->ltd_exp, op_data, &request);
1855         if (!rc) {
1856                 ptlrpc_req_finished(request);
1857                 return -EEXIST;
1858         }
1859
1860         return rc;
1861 }
1862
1863 /* mkdir by QoS upon 'lfs mkdir -i -1'.
1864  *
1865  * NB, mkdir by QoS only if parent is not striped, this is to avoid remote
1866  * directories under striped directory.
1867  */
1868 static inline bool lmv_op_user_qos_mkdir(const struct md_op_data *op_data)
1869 {
1870         const struct lmv_user_md *lum = op_data->op_data;
1871
1872         if (op_data->op_code != LUSTRE_OPC_MKDIR)
1873                 return false;
1874
1875         if (lmv_dir_striped(op_data->op_mea1))
1876                 return false;
1877
1878         return (op_data->op_cli_flags & CLI_SET_MEA) && lum &&
1879                le32_to_cpu(lum->lum_magic) == LMV_USER_MAGIC &&
1880                le32_to_cpu(lum->lum_stripe_offset) == LMV_OFFSET_DEFAULT;
1881 }
1882
1883 /* mkdir by QoS if either ROOT or parent default LMV is space balanced. */
1884 static inline bool lmv_op_default_qos_mkdir(const struct md_op_data *op_data)
1885 {
1886         const struct lmv_stripe_md *lsm = op_data->op_default_mea1;
1887
1888         if (op_data->op_code != LUSTRE_OPC_MKDIR)
1889                 return false;
1890
1891         if (lmv_dir_striped(op_data->op_mea1))
1892                 return false;
1893
1894         return (op_data->op_flags & MF_QOS_MKDIR) ||
1895                (lsm && lsm->lsm_md_master_mdt_index == LMV_OFFSET_DEFAULT);
1896 }
1897
1898 /* if parent default LMV is space balanced, and
1899  * 1. max_inherit_rr is set
1900  * 2. or parent is ROOT
1901  * mkdir roundrobin. Or if parent doesn't have default LMV, while ROOT default
1902  * LMV requests roundrobin mkdir, do the same.
1903  * NB, this needs to check server is balanced, which is done by caller.
1904  */
1905 static inline bool lmv_op_default_rr_mkdir(const struct md_op_data *op_data)
1906 {
1907         const struct lmv_stripe_md *lsm = op_data->op_default_mea1;
1908
1909         return (op_data->op_flags & MF_RR_MKDIR) ||
1910                (lsm && lsm->lsm_md_max_inherit_rr != LMV_INHERIT_RR_NONE) ||
1911                fid_is_root(&op_data->op_fid1);
1912 }
1913
1914 /* 'lfs mkdir -i <specific_MDT>' */
1915 static inline bool lmv_op_user_specific_mkdir(const struct md_op_data *op_data)
1916 {
1917         const struct lmv_user_md *lum = op_data->op_data;
1918
1919         return op_data->op_code == LUSTRE_OPC_MKDIR &&
1920                op_data->op_cli_flags & CLI_SET_MEA && lum &&
1921                (le32_to_cpu(lum->lum_magic) == LMV_USER_MAGIC ||
1922                 le32_to_cpu(lum->lum_magic) == LMV_USER_MAGIC_SPECIFIC) &&
1923                le32_to_cpu(lum->lum_stripe_offset) != LMV_OFFSET_DEFAULT;
1924 }
1925
1926 /* parent default LMV master_mdt_index is not -1. */
1927 static inline bool
1928 lmv_op_default_specific_mkdir(const struct md_op_data *op_data)
1929 {
1930         return op_data->op_code == LUSTRE_OPC_MKDIR &&
1931                op_data->op_default_mea1 &&
1932                op_data->op_default_mea1->lsm_md_master_mdt_index !=
1933                         LMV_OFFSET_DEFAULT;
1934 }
1935
1936 /* locate MDT by space usage */
1937 static struct lu_tgt_desc *lmv_locate_tgt_by_space(struct lmv_obd *lmv,
1938                                                    struct md_op_data *op_data,
1939                                                    struct lmv_tgt_desc *tgt)
1940 {
1941         struct lmv_tgt_desc *tmp = tgt;
1942
1943         tgt = lmv_locate_tgt_qos(lmv, op_data);
1944         if (tgt == ERR_PTR(-EAGAIN)) {
1945                 if (ltd_qos_is_balanced(&lmv->lmv_mdt_descs) &&
1946                     !lmv_op_default_rr_mkdir(op_data) &&
1947                     !lmv_op_user_qos_mkdir(op_data))
1948                         /* if not necessary, don't create remote directory. */
1949                         tgt = tmp;
1950                 else
1951                         tgt = lmv_locate_tgt_rr(lmv);
1952         }
1953
1954         /*
1955          * only update statfs after QoS mkdir, this means the cached statfs may
1956          * be stale, and current mkdir may not follow QoS accurately, but it's
1957          * not serious, and avoids periodic statfs when client doesn't mkdir by
1958          * QoS.
1959          */
1960         if (!IS_ERR(tgt)) {
1961                 op_data->op_mds = tgt->ltd_index;
1962                 lmv_statfs_check_update(lmv2obd_dev(lmv), tgt);
1963         }
1964
1965         return tgt;
1966 }
1967
1968 int lmv_create(struct obd_export *exp, struct md_op_data *op_data,
1969                 const void *data, size_t datalen, umode_t mode, uid_t uid,
1970                 gid_t gid, kernel_cap_t cap_effective, __u64 rdev,
1971                 struct ptlrpc_request **request)
1972 {
1973         struct obd_device *obd = exp->exp_obd;
1974         struct lmv_obd *lmv = &obd->u.lmv;
1975         struct lmv_tgt_desc *tgt;
1976         struct mdt_body *repbody;
1977         int rc;
1978
1979         ENTRY;
1980
1981         if (!lmv->lmv_mdt_descs.ltd_lmv_desc.ld_active_tgt_count)
1982                 RETURN(-EIO);
1983
1984         if (lmv_dir_bad_hash(op_data->op_mea1))
1985                 RETURN(-EBADF);
1986
1987         if (lmv_dir_layout_changing(op_data->op_mea1)) {
1988                 /*
1989                  * if parent is migrating, create() needs to lookup existing
1990                  * name in both old and new layout, check old layout on client.
1991                  */
1992                 rc = lmv_old_layout_lookup(lmv, op_data);
1993                 if (rc != -ENOENT)
1994                         RETURN(rc);
1995
1996                 op_data->op_new_layout = true;
1997         }
1998
1999         tgt = lmv_locate_tgt(lmv, op_data);
2000         if (IS_ERR(tgt))
2001                 RETURN(PTR_ERR(tgt));
2002
2003         /* the order to apply policy in mkdir:
2004          * 1. is "lfs mkdir -i N"? mkdir on MDT N.
2005          * 2. is "lfs mkdir -i -1"? mkdir by space usage.
2006          * 3. is starting MDT specified in default LMV? mkdir on MDT N.
2007          * 4. is default LMV space balanced? mkdir by space usage.
2008          */
2009         if (lmv_op_user_specific_mkdir(op_data)) {
2010                 struct lmv_user_md *lum = op_data->op_data;
2011
2012                 op_data->op_mds = le32_to_cpu(lum->lum_stripe_offset);
2013                 tgt = lmv_tgt(lmv, op_data->op_mds);
2014                 if (!tgt)
2015                         RETURN(-ENODEV);
2016         } else if (lmv_op_user_qos_mkdir(op_data)) {
2017                 tgt = lmv_locate_tgt_by_space(lmv, op_data, tgt);
2018                 if (IS_ERR(tgt))
2019                         RETURN(PTR_ERR(tgt));
2020         } else if (lmv_op_default_specific_mkdir(op_data)) {
2021                 op_data->op_mds =
2022                         op_data->op_default_mea1->lsm_md_master_mdt_index;
2023                 tgt = lmv_tgt(lmv, op_data->op_mds);
2024                 if (!tgt)
2025                         RETURN(-ENODEV);
2026         } else if (lmv_op_default_qos_mkdir(op_data)) {
2027                 tgt = lmv_locate_tgt_by_space(lmv, op_data, tgt);
2028                 if (IS_ERR(tgt))
2029                         RETURN(PTR_ERR(tgt));
2030         }
2031
2032 retry:
2033         rc = lmv_fid_alloc(NULL, exp, &op_data->op_fid2, op_data);
2034         if (rc)
2035                 RETURN(rc);
2036
2037         CDEBUG(D_INODE, "CREATE name '%.*s' "DFID" on "DFID" -> mds #%x\n",
2038                 (int)op_data->op_namelen, op_data->op_name,
2039                 PFID(&op_data->op_fid2), PFID(&op_data->op_fid1),
2040                 op_data->op_mds);
2041
2042         op_data->op_flags |= MF_MDC_CANCEL_FID1;
2043         rc = md_create(tgt->ltd_exp, op_data, data, datalen, mode, uid, gid,
2044                        cap_effective, rdev, request);
2045         if (rc == 0) {
2046                 if (*request == NULL)
2047                         RETURN(rc);
2048                 CDEBUG(D_INODE, "Created - "DFID"\n", PFID(&op_data->op_fid2));
2049         }
2050
2051         /* dir restripe needs to send to MDT where dir is located */
2052         if (rc != -EREMOTE ||
2053             !(exp_connect_flags2(exp) & OBD_CONNECT2_CRUSH))
2054                 RETURN(rc);
2055
2056         repbody = req_capsule_server_get(&(*request)->rq_pill, &RMF_MDT_BODY);
2057         if (repbody == NULL)
2058                 RETURN(-EPROTO);
2059
2060         /* Not cross-ref case, just get out of here. */
2061         if (likely(!(repbody->mbo_valid & OBD_MD_MDS)))
2062                 RETURN(rc);
2063
2064         op_data->op_fid2 = repbody->mbo_fid1;
2065         ptlrpc_req_finished(*request);
2066         *request = NULL;
2067
2068         tgt = lmv_fid2tgt(lmv, &op_data->op_fid2);
2069         if (IS_ERR(tgt))
2070                 RETURN(PTR_ERR(tgt));
2071
2072         op_data->op_mds = tgt->ltd_index;
2073         goto retry;
2074 }
2075
2076 static int
2077 lmv_enqueue(struct obd_export *exp, struct ldlm_enqueue_info *einfo,
2078             const union ldlm_policy_data *policy, struct md_op_data *op_data,
2079             struct lustre_handle *lockh, __u64 extra_lock_flags)
2080 {
2081         struct obd_device *obd = exp->exp_obd;
2082         struct lmv_obd *lmv = &obd->u.lmv;
2083         struct lmv_tgt_desc *tgt;
2084         int rc;
2085
2086         ENTRY;
2087
2088         CDEBUG(D_INODE, "ENQUEUE on "DFID"\n", PFID(&op_data->op_fid1));
2089
2090         tgt = lmv_fid2tgt(lmv, &op_data->op_fid1);
2091         if (IS_ERR(tgt))
2092                 RETURN(PTR_ERR(tgt));
2093
2094         CDEBUG(D_INODE, "ENQUEUE on "DFID" -> mds #%u\n",
2095                PFID(&op_data->op_fid1), tgt->ltd_index);
2096
2097         rc = md_enqueue(tgt->ltd_exp, einfo, policy, op_data, lockh,
2098                         extra_lock_flags);
2099
2100         RETURN(rc);
2101 }
2102
2103 int
2104 lmv_getattr_name(struct obd_export *exp,struct md_op_data *op_data,
2105                  struct ptlrpc_request **preq)
2106 {
2107         struct obd_device *obd = exp->exp_obd;
2108         struct lmv_obd *lmv = &obd->u.lmv;
2109         struct lmv_tgt_desc *tgt;
2110         struct mdt_body *body;
2111         int rc;
2112
2113         ENTRY;
2114
2115 retry:
2116         if (op_data->op_namelen == 2 &&
2117             op_data->op_name[0] == '.' && op_data->op_name[1] == '.')
2118                 tgt = lmv_fid2tgt(lmv, &op_data->op_fid1);
2119         else
2120                 tgt = lmv_locate_tgt(lmv, op_data);
2121         if (IS_ERR(tgt))
2122                 RETURN(PTR_ERR(tgt));
2123
2124         CDEBUG(D_INODE, "GETATTR_NAME for %*s on "DFID" -> mds #%d\n",
2125                 (int)op_data->op_namelen, op_data->op_name,
2126                 PFID(&op_data->op_fid1), tgt->ltd_index);
2127
2128         rc = md_getattr_name(tgt->ltd_exp, op_data, preq);
2129         if (rc == -ENOENT && lmv_dir_retry_check_update(op_data)) {
2130                 ptlrpc_req_finished(*preq);
2131                 *preq = NULL;
2132                 goto retry;
2133         }
2134
2135         if (rc)
2136                 RETURN(rc);
2137
2138         body = req_capsule_server_get(&(*preq)->rq_pill, &RMF_MDT_BODY);
2139         LASSERT(body != NULL);
2140
2141         if (body->mbo_valid & OBD_MD_MDS) {
2142                 op_data->op_fid1 = body->mbo_fid1;
2143                 op_data->op_valid |= OBD_MD_FLCROSSREF;
2144                 op_data->op_namelen = 0;
2145                 op_data->op_name = NULL;
2146
2147                 ptlrpc_req_finished(*preq);
2148                 *preq = NULL;
2149
2150                 goto retry;
2151         }
2152
2153         RETURN(rc);
2154 }
2155
2156 #define md_op_data_fid(op_data, fl)                     \
2157         (fl == MF_MDC_CANCEL_FID1 ? &op_data->op_fid1 : \
2158          fl == MF_MDC_CANCEL_FID2 ? &op_data->op_fid2 : \
2159          fl == MF_MDC_CANCEL_FID3 ? &op_data->op_fid3 : \
2160          fl == MF_MDC_CANCEL_FID4 ? &op_data->op_fid4 : \
2161          NULL)
2162
2163 static int lmv_early_cancel(struct obd_export *exp, struct lmv_tgt_desc *tgt,
2164                             struct md_op_data *op_data, __u32 op_tgt,
2165                             enum ldlm_mode mode, int bits, int flag)
2166 {
2167         struct lu_fid *fid = md_op_data_fid(op_data, flag);
2168         struct lmv_obd *lmv = &exp->exp_obd->u.lmv;
2169         union ldlm_policy_data policy = { { 0 } };
2170         int rc = 0;
2171         ENTRY;
2172
2173         if (!fid_is_sane(fid))
2174                 RETURN(0);
2175
2176         if (tgt == NULL) {
2177                 tgt = lmv_fid2tgt(lmv, fid);
2178                 if (IS_ERR(tgt))
2179                         RETURN(PTR_ERR(tgt));
2180         }
2181
2182         if (tgt->ltd_index != op_tgt) {
2183                 CDEBUG(D_INODE, "EARLY_CANCEL on "DFID"\n", PFID(fid));
2184                 policy.l_inodebits.bits = bits;
2185                 rc = md_cancel_unused(tgt->ltd_exp, fid, &policy,
2186                                       mode, LCF_ASYNC, NULL);
2187         } else {
2188                 CDEBUG(D_INODE,
2189                        "EARLY_CANCEL skip operation target %d on "DFID"\n",
2190                        op_tgt, PFID(fid));
2191                 op_data->op_flags |= flag;
2192                 rc = 0;
2193         }
2194
2195         RETURN(rc);
2196 }
2197
2198 /*
2199  * llite passes fid of an target inode in op_data->op_fid1 and id of directory in
2200  * op_data->op_fid2
2201  */
2202 static int lmv_link(struct obd_export *exp, struct md_op_data *op_data,
2203                     struct ptlrpc_request **request)
2204 {
2205         struct obd_device       *obd = exp->exp_obd;
2206         struct lmv_obd          *lmv = &obd->u.lmv;
2207         struct lmv_tgt_desc     *tgt;
2208         int                      rc;
2209         ENTRY;
2210
2211         LASSERT(op_data->op_namelen != 0);
2212
2213         CDEBUG(D_INODE, "LINK "DFID":%*s to "DFID"\n",
2214                PFID(&op_data->op_fid2), (int)op_data->op_namelen,
2215                op_data->op_name, PFID(&op_data->op_fid1));
2216
2217         op_data->op_fsuid = from_kuid(&init_user_ns, current_fsuid());
2218         op_data->op_fsgid = from_kgid(&init_user_ns, current_fsgid());
2219         op_data->op_cap = current_cap();
2220
2221         tgt = lmv_locate_tgt2(lmv, op_data);
2222         if (IS_ERR(tgt))
2223                 RETURN(PTR_ERR(tgt));
2224
2225         /*
2226          * Cancel UPDATE lock on child (fid1).
2227          */
2228         op_data->op_flags |= MF_MDC_CANCEL_FID2;
2229         rc = lmv_early_cancel(exp, NULL, op_data, tgt->ltd_index, LCK_EX,
2230                               MDS_INODELOCK_UPDATE, MF_MDC_CANCEL_FID1);
2231         if (rc != 0)
2232                 RETURN(rc);
2233
2234         rc = md_link(tgt->ltd_exp, op_data, request);
2235
2236         RETURN(rc);
2237 }
2238
2239 /* migrate the top directory */
2240 static inline bool lmv_op_topdir_migrate(const struct md_op_data *op_data)
2241 {
2242         if (!S_ISDIR(op_data->op_mode))
2243                 return false;
2244
2245         if (lmv_dir_layout_changing(op_data->op_mea1))
2246                 return false;
2247
2248         return true;
2249 }
2250
2251 /* migrate top dir to specific MDTs */
2252 static inline bool lmv_topdir_specific_migrate(const struct md_op_data *op_data)
2253 {
2254         const struct lmv_user_md *lum = op_data->op_data;
2255
2256         if (!lmv_op_topdir_migrate(op_data))
2257                 return false;
2258
2259         return le32_to_cpu(lum->lum_stripe_offset) != LMV_OFFSET_DEFAULT;
2260 }
2261
2262 /* migrate top dir in QoS mode if user issued "lfs migrate -m -1..." */
2263 static inline bool lmv_topdir_qos_migrate(const struct md_op_data *op_data)
2264 {
2265         const struct lmv_user_md *lum = op_data->op_data;
2266
2267         if (!lmv_op_topdir_migrate(op_data))
2268                 return false;
2269
2270         return le32_to_cpu(lum->lum_stripe_offset) == LMV_OFFSET_DEFAULT;
2271 }
2272
2273 static inline bool lmv_subdir_specific_migrate(const struct md_op_data *op_data)
2274 {
2275         const struct lmv_user_md *lum = op_data->op_data;
2276
2277         if (!S_ISDIR(op_data->op_mode))
2278                 return false;
2279
2280         if (!lmv_dir_layout_changing(op_data->op_mea1))
2281                 return false;
2282
2283         return le32_to_cpu(lum->lum_stripe_offset) != LMV_OFFSET_DEFAULT;
2284 }
2285
2286 static int lmv_migrate(struct obd_export *exp, struct md_op_data *op_data,
2287                         const char *name, size_t namelen,
2288                         struct ptlrpc_request **request)
2289 {
2290         struct obd_device *obd = exp->exp_obd;
2291         struct lmv_obd *lmv = &obd->u.lmv;
2292         struct lmv_stripe_md *lsm = op_data->op_mea1;
2293         struct lmv_tgt_desc *parent_tgt;
2294         struct lmv_tgt_desc *sp_tgt;
2295         struct lmv_tgt_desc *tp_tgt = NULL;
2296         struct lmv_tgt_desc *child_tgt;
2297         struct lmv_tgt_desc *tgt;
2298         struct lu_fid target_fid = { 0 };
2299         int rc;
2300
2301         ENTRY;
2302
2303         LASSERT(op_data->op_cli_flags & CLI_MIGRATE);
2304
2305         CDEBUG(D_INODE, "MIGRATE "DFID"/%.*s\n",
2306                PFID(&op_data->op_fid1), (int)namelen, name);
2307
2308         op_data->op_fsuid = from_kuid(&init_user_ns, current_fsuid());
2309         op_data->op_fsgid = from_kgid(&init_user_ns, current_fsgid());
2310         op_data->op_cap = current_cap();
2311
2312         parent_tgt = lmv_fid2tgt(lmv, &op_data->op_fid1);
2313         if (IS_ERR(parent_tgt))
2314                 RETURN(PTR_ERR(parent_tgt));
2315
2316         if (lmv_dir_striped(lsm)) {
2317                 const struct lmv_oinfo *oinfo;
2318
2319                 oinfo = lsm_name_to_stripe_info(lsm, name, namelen, false);
2320                 if (IS_ERR(oinfo))
2321                         RETURN(PTR_ERR(oinfo));
2322
2323                 /* save source stripe FID in fid4 temporarily for ELC */
2324                 op_data->op_fid4 = oinfo->lmo_fid;
2325                 sp_tgt = lmv_tgt(lmv, oinfo->lmo_mds);
2326                 if (!sp_tgt)
2327                         RETURN(-ENODEV);
2328
2329                 /*
2330                  * if parent is being migrated too, fill op_fid2 with target
2331                  * stripe fid, otherwise the target stripe is not created yet.
2332                  */
2333                 if (lmv_dir_layout_changing(lsm)) {
2334                         oinfo = lsm_name_to_stripe_info(lsm, name, namelen,
2335                                                         true);
2336                         if (IS_ERR(oinfo))
2337                                 RETURN(PTR_ERR(oinfo));
2338
2339                         op_data->op_fid2 = oinfo->lmo_fid;
2340                         tp_tgt = lmv_tgt(lmv, oinfo->lmo_mds);
2341                         if (!tp_tgt)
2342                                 RETURN(-ENODEV);
2343
2344                         /* parent unchanged and update namespace only */
2345                         if (lu_fid_eq(&op_data->op_fid4, &op_data->op_fid2) &&
2346                             op_data->op_bias & MDS_MIGRATE_NSONLY)
2347                                 RETURN(-EALREADY);
2348                 }
2349         } else {
2350                 sp_tgt = parent_tgt;
2351         }
2352
2353         child_tgt = lmv_fid2tgt(lmv, &op_data->op_fid3);
2354         if (IS_ERR(child_tgt))
2355                 RETURN(PTR_ERR(child_tgt));
2356
2357         if (lmv_topdir_specific_migrate(op_data)) {
2358                 struct lmv_user_md *lum = op_data->op_data;
2359
2360                 op_data->op_mds = le32_to_cpu(lum->lum_stripe_offset);
2361         } else if (lmv_topdir_qos_migrate(op_data)) {
2362                 tgt = lmv_locate_tgt_lf(lmv);
2363                 if (tgt == ERR_PTR(-EAGAIN))
2364                         tgt = lmv_locate_tgt_rr(lmv);
2365                 if (IS_ERR(tgt))
2366                         RETURN(PTR_ERR(tgt));
2367
2368                 op_data->op_mds = tgt->ltd_index;
2369         } else if (lmv_subdir_specific_migrate(op_data)) {
2370                 struct lmv_user_md *lum = op_data->op_data;
2371                 __u32 i;
2372
2373                 LASSERT(tp_tgt);
2374                 if (le32_to_cpu(lum->lum_magic) == LMV_USER_MAGIC_SPECIFIC) {
2375                         /* adjust MDTs in lum, since subdir is located on where
2376                          * its parent stripe is, not the first specified MDT.
2377                          */
2378                         for (i = 0; i < le32_to_cpu(lum->lum_stripe_count);
2379                              i++) {
2380                                 if (le32_to_cpu(lum->lum_objects[i].lum_mds) ==
2381                                     tp_tgt->ltd_index)
2382                                         break;
2383                         }
2384
2385                         if (i == le32_to_cpu(lum->lum_stripe_count))
2386                                 RETURN(-ENODEV);
2387
2388                         lum->lum_objects[i].lum_mds =
2389                                 lum->lum_objects[0].lum_mds;
2390                         lum->lum_objects[0].lum_mds =
2391                                 cpu_to_le32(tp_tgt->ltd_index);
2392                 }
2393                 /* NB, the above adjusts subdir migration for command like
2394                  * "lfs migrate -m 0,1,2 ...", but for migration like
2395                  * "lfs migrate -m 0 -c 2 ...", the top dir is migrated to MDT0
2396                  * and MDT1, however its subdir may be migrated to MDT1 and MDT2
2397                  */
2398
2399                 lum->lum_stripe_offset = cpu_to_le32(tp_tgt->ltd_index);
2400                 op_data->op_mds = tp_tgt->ltd_index;
2401         } else if (tp_tgt) {
2402                 op_data->op_mds = tp_tgt->ltd_index;
2403         } else {
2404                 op_data->op_mds = sp_tgt->ltd_index;
2405         }
2406
2407         rc = lmv_fid_alloc(NULL, exp, &target_fid, op_data);
2408         if (rc)
2409                 RETURN(rc);
2410
2411         /*
2412          * for directory, send migrate request to the MDT where the object will
2413          * be migrated to, because we can't create a striped directory remotely.
2414          *
2415          * otherwise, send to the MDT where source is located because regular
2416          * file may open lease.
2417          *
2418          * NB. if MDT doesn't support DIR_MIGRATE, send to source MDT too for
2419          * backward compatibility.
2420          */
2421         if (S_ISDIR(op_data->op_mode) &&
2422             (exp_connect_flags2(exp) & OBD_CONNECT2_DIR_MIGRATE)) {
2423                 tgt = lmv_fid2tgt(lmv, &target_fid);
2424                 if (IS_ERR(tgt))
2425                         RETURN(PTR_ERR(tgt));
2426         } else {
2427                 tgt = child_tgt;
2428         }
2429
2430         /* cancel UPDATE lock of parent master object */
2431         rc = lmv_early_cancel(exp, parent_tgt, op_data, tgt->ltd_index, LCK_EX,
2432                               MDS_INODELOCK_UPDATE, MF_MDC_CANCEL_FID1);
2433         if (rc)
2434                 RETURN(rc);
2435
2436         /* cancel UPDATE lock of source parent */
2437         if (sp_tgt != parent_tgt) {
2438                 /*
2439                  * migrate RPC packs master object FID, because we can only pack
2440                  * two FIDs in reint RPC, but MDS needs to know both source
2441                  * parent and target parent, and it will obtain them from master
2442                  * FID and LMV, the other FID in RPC is kept for target.
2443                  *
2444                  * since this FID is not passed to MDC, cancel it anyway.
2445                  */
2446                 rc = lmv_early_cancel(exp, sp_tgt, op_data, -1, LCK_EX,
2447                                       MDS_INODELOCK_UPDATE, MF_MDC_CANCEL_FID4);
2448                 if (rc)
2449                         RETURN(rc);
2450
2451                 op_data->op_flags &= ~MF_MDC_CANCEL_FID4;
2452         }
2453         op_data->op_fid4 = target_fid;
2454
2455         /* cancel UPDATE locks of target parent */
2456         rc = lmv_early_cancel(exp, tp_tgt, op_data, tgt->ltd_index, LCK_EX,
2457                               MDS_INODELOCK_UPDATE, MF_MDC_CANCEL_FID2);
2458         if (rc)
2459                 RETURN(rc);
2460
2461         /* cancel LOOKUP lock of source if source is remote object */
2462         if (child_tgt != sp_tgt) {
2463                 rc = lmv_early_cancel(exp, sp_tgt, op_data, tgt->ltd_index,
2464                                       LCK_EX, MDS_INODELOCK_LOOKUP,
2465                                       MF_MDC_CANCEL_FID3);
2466                 if (rc)
2467                         RETURN(rc);
2468         }
2469
2470         /* cancel ELC locks of source */
2471         rc = lmv_early_cancel(exp, child_tgt, op_data, tgt->ltd_index, LCK_EX,
2472                               MDS_INODELOCK_ELC, MF_MDC_CANCEL_FID3);
2473         if (rc)
2474                 RETURN(rc);
2475
2476         rc = md_rename(tgt->ltd_exp, op_data, name, namelen, NULL, 0, request);
2477
2478         RETURN(rc);
2479 }
2480
2481 static int lmv_rename(struct obd_export *exp, struct md_op_data *op_data,
2482                       const char *old, size_t oldlen,
2483                       const char *new, size_t newlen,
2484                       struct ptlrpc_request **request)
2485 {
2486         struct obd_device *obd = exp->exp_obd;
2487         struct lmv_obd *lmv = &obd->u.lmv;
2488         struct lmv_tgt_desc *sp_tgt;
2489         struct lmv_tgt_desc *tp_tgt = NULL;
2490         struct lmv_tgt_desc *src_tgt = NULL;
2491         struct lmv_tgt_desc *tgt;
2492         struct mdt_body *body;
2493         int rc;
2494
2495         ENTRY;
2496
2497         LASSERT(oldlen != 0);
2498
2499         if (op_data->op_cli_flags & CLI_MIGRATE) {
2500                 rc = lmv_migrate(exp, op_data, old, oldlen, request);
2501                 RETURN(rc);
2502         }
2503
2504         op_data->op_fsuid = from_kuid(&init_user_ns, current_fsuid());
2505         op_data->op_fsgid = from_kgid(&init_user_ns, current_fsgid());
2506         op_data->op_cap = current_cap();
2507
2508         op_data->op_name = new;
2509         op_data->op_namelen = newlen;
2510
2511         tp_tgt = lmv_locate_tgt2(lmv, op_data);
2512         if (IS_ERR(tp_tgt))
2513                 RETURN(PTR_ERR(tp_tgt));
2514
2515         /* Since the target child might be destroyed, and it might become
2516          * orphan, and we can only check orphan on the local MDT right now, so
2517          * we send rename request to the MDT where target child is located. If
2518          * target child does not exist, then it will send the request to the
2519          * target parent */
2520         if (fid_is_sane(&op_data->op_fid4)) {
2521                 tgt = lmv_fid2tgt(lmv, &op_data->op_fid4);
2522                 if (IS_ERR(tgt))
2523                         RETURN(PTR_ERR(tgt));
2524         } else {
2525                 tgt = tp_tgt;
2526         }
2527
2528         op_data->op_flags |= MF_MDC_CANCEL_FID4;
2529
2530         /* cancel UPDATE locks of target parent */
2531         rc = lmv_early_cancel(exp, tp_tgt, op_data, tgt->ltd_index, LCK_EX,
2532                               MDS_INODELOCK_UPDATE, MF_MDC_CANCEL_FID2);
2533         if (rc != 0)
2534                 RETURN(rc);
2535
2536         if (fid_is_sane(&op_data->op_fid4)) {
2537                 /* cancel LOOKUP lock of target on target parent */
2538                 if (tgt != tp_tgt) {
2539                         rc = lmv_early_cancel(exp, tp_tgt, op_data,
2540                                               tgt->ltd_index, LCK_EX,
2541                                               MDS_INODELOCK_LOOKUP,
2542                                               MF_MDC_CANCEL_FID4);
2543                         if (rc != 0)
2544                                 RETURN(rc);
2545                 }
2546         }
2547
2548         if (fid_is_sane(&op_data->op_fid3)) {
2549                 src_tgt = lmv_fid2tgt(lmv, &op_data->op_fid3);
2550                 if (IS_ERR(src_tgt))
2551                         RETURN(PTR_ERR(src_tgt));
2552
2553                 /* cancel ELC locks of source */
2554                 rc = lmv_early_cancel(exp, src_tgt, op_data, tgt->ltd_index,
2555                                       LCK_EX, MDS_INODELOCK_ELC,
2556                                       MF_MDC_CANCEL_FID3);
2557                 if (rc != 0)
2558                         RETURN(rc);
2559         }
2560
2561         op_data->op_name = old;
2562         op_data->op_namelen = oldlen;
2563 retry:
2564         sp_tgt = lmv_locate_tgt(lmv, op_data);
2565         if (IS_ERR(sp_tgt))
2566                 RETURN(PTR_ERR(sp_tgt));
2567
2568         /* cancel UPDATE locks of source parent */
2569         rc = lmv_early_cancel(exp, sp_tgt, op_data, tgt->ltd_index, LCK_EX,
2570                               MDS_INODELOCK_UPDATE, MF_MDC_CANCEL_FID1);
2571         if (rc != 0)
2572                 RETURN(rc);
2573
2574         if (fid_is_sane(&op_data->op_fid3)) {
2575                 /* cancel LOOKUP lock of source on source parent */
2576                 if (src_tgt != sp_tgt) {
2577                         rc = lmv_early_cancel(exp, sp_tgt, op_data,
2578                                               tgt->ltd_index, LCK_EX,
2579                                               MDS_INODELOCK_LOOKUP,
2580                                               MF_MDC_CANCEL_FID3);
2581                         if (rc != 0)
2582                                 RETURN(rc);
2583                 }
2584         }
2585
2586 rename:
2587         CDEBUG(D_INODE, "RENAME "DFID"/%.*s to "DFID"/%.*s\n",
2588                 PFID(&op_data->op_fid1), (int)oldlen, old,
2589                 PFID(&op_data->op_fid2), (int)newlen, new);
2590
2591         rc = md_rename(tgt->ltd_exp, op_data, old, oldlen, new, newlen,
2592                         request);
2593         if (rc == -ENOENT && lmv_dir_retry_check_update(op_data)) {
2594                 ptlrpc_req_finished(*request);
2595                 *request = NULL;
2596                 goto retry;
2597         }
2598
2599         if (rc && rc != -EXDEV)
2600                 RETURN(rc);
2601
2602         body = req_capsule_server_get(&(*request)->rq_pill, &RMF_MDT_BODY);
2603         if (body == NULL)
2604                 RETURN(-EPROTO);
2605
2606         /* Not cross-ref case, just get out of here. */
2607         if (likely(!(body->mbo_valid & OBD_MD_MDS)))
2608                 RETURN(rc);
2609
2610         op_data->op_fid4 = body->mbo_fid1;
2611
2612         ptlrpc_req_finished(*request);
2613         *request = NULL;
2614
2615         tgt = lmv_fid2tgt(lmv, &op_data->op_fid4);
2616         if (IS_ERR(tgt))
2617                 RETURN(PTR_ERR(tgt));
2618
2619         if (fid_is_sane(&op_data->op_fid4)) {
2620                 /* cancel LOOKUP lock of target on target parent */
2621                 if (tgt != tp_tgt) {
2622                         rc = lmv_early_cancel(exp, tp_tgt, op_data,
2623                                               tgt->ltd_index, LCK_EX,
2624                                               MDS_INODELOCK_LOOKUP,
2625                                               MF_MDC_CANCEL_FID4);
2626                         if (rc != 0)
2627                                 RETURN(rc);
2628                 }
2629         }
2630
2631         goto rename;
2632 }
2633
2634 static int lmv_setattr(struct obd_export *exp, struct md_op_data *op_data,
2635                        void *ea, size_t ealen, struct ptlrpc_request **request)
2636 {
2637         struct obd_device *obd = exp->exp_obd;
2638         struct lmv_obd *lmv = &obd->u.lmv;
2639         struct lmv_tgt_desc *tgt;
2640         int rc = 0;
2641
2642         ENTRY;
2643
2644         CDEBUG(D_INODE, "SETATTR for "DFID", valid 0x%x/0x%x\n",
2645                PFID(&op_data->op_fid1), op_data->op_attr.ia_valid,
2646                op_data->op_xvalid);
2647
2648         op_data->op_flags |= MF_MDC_CANCEL_FID1;
2649         tgt = lmv_fid2tgt(lmv, &op_data->op_fid1);
2650         if (IS_ERR(tgt))
2651                 RETURN(PTR_ERR(tgt));
2652
2653         rc = md_setattr(tgt->ltd_exp, op_data, ea, ealen, request);
2654
2655         RETURN(rc);
2656 }
2657
2658 static int lmv_fsync(struct obd_export *exp, const struct lu_fid *fid,
2659                      struct ptlrpc_request **request)
2660 {
2661         struct obd_device *obd = exp->exp_obd;
2662         struct lmv_obd *lmv = &obd->u.lmv;
2663         struct lmv_tgt_desc *tgt;
2664         int rc;
2665
2666         ENTRY;
2667
2668         tgt = lmv_fid2tgt(lmv, fid);
2669         if (IS_ERR(tgt))
2670                 RETURN(PTR_ERR(tgt));
2671
2672         rc = md_fsync(tgt->ltd_exp, fid, request);
2673         RETURN(rc);
2674 }
2675
2676 struct stripe_dirent {
2677         struct page             *sd_page;
2678         struct lu_dirpage       *sd_dp;
2679         struct lu_dirent        *sd_ent;
2680         bool                     sd_eof;
2681 };
2682
2683 struct lmv_dir_ctxt {
2684         struct lmv_obd          *ldc_lmv;
2685         struct md_op_data       *ldc_op_data;
2686         struct md_readdir_info  *ldc_mrinfo;
2687         __u64                    ldc_hash;
2688         int                      ldc_count;
2689         struct stripe_dirent     ldc_stripes[0];
2690 };
2691
2692 static inline void stripe_dirent_unload(struct stripe_dirent *stripe)
2693 {
2694         if (stripe->sd_page) {
2695                 kunmap(stripe->sd_page);
2696                 put_page(stripe->sd_page);
2697                 stripe->sd_page = NULL;
2698                 stripe->sd_ent = NULL;
2699         }
2700 }
2701
2702 static inline void put_lmv_dir_ctxt(struct lmv_dir_ctxt *ctxt)
2703 {
2704         int i;
2705
2706         for (i = 0; i < ctxt->ldc_count; i++)
2707                 stripe_dirent_unload(&ctxt->ldc_stripes[i]);
2708 }
2709
2710 /* if @ent is dummy, or . .., get next */
2711 static struct lu_dirent *stripe_dirent_get(struct lmv_dir_ctxt *ctxt,
2712                                            struct lu_dirent *ent,
2713                                            int stripe_index)
2714 {
2715         for (; ent; ent = lu_dirent_next(ent)) {
2716                 /* Skip dummy entry */
2717                 if (le16_to_cpu(ent->lde_namelen) == 0)
2718                         continue;
2719
2720                 /* skip . and .. for other stripes */
2721                 if (stripe_index &&
2722                     (strncmp(ent->lde_name, ".",
2723                              le16_to_cpu(ent->lde_namelen)) == 0 ||
2724                      strncmp(ent->lde_name, "..",
2725                              le16_to_cpu(ent->lde_namelen)) == 0))
2726                         continue;
2727
2728                 if (le64_to_cpu(ent->lde_hash) >= ctxt->ldc_hash)
2729                         break;
2730         }
2731
2732         return ent;
2733 }
2734
2735 static struct lu_dirent *stripe_dirent_load(struct lmv_dir_ctxt *ctxt,
2736                                             struct stripe_dirent *stripe,
2737                                             int stripe_index)
2738 {
2739         struct md_op_data *op_data = ctxt->ldc_op_data;
2740         struct lmv_oinfo *oinfo;
2741         struct lu_fid fid = op_data->op_fid1;
2742         struct inode *inode = op_data->op_data;
2743         struct lmv_tgt_desc *tgt;
2744         struct lu_dirent *ent = stripe->sd_ent;
2745         __u64 hash = ctxt->ldc_hash;
2746         int rc = 0;
2747
2748         ENTRY;
2749
2750         LASSERT(stripe == &ctxt->ldc_stripes[stripe_index]);
2751         LASSERT(!ent);
2752
2753         do {
2754                 if (stripe->sd_page) {
2755                         __u64 end = le64_to_cpu(stripe->sd_dp->ldp_hash_end);
2756
2757                         /* @hash should be the last dirent hash */
2758                         LASSERTF(hash <= end,
2759                                  "ctxt@%p stripe@%p hash %llx end %llx\n",
2760                                  ctxt, stripe, hash, end);
2761                         /* unload last page */
2762                         stripe_dirent_unload(stripe);
2763                         /* eof */
2764                         if (end == MDS_DIR_END_OFF) {
2765                                 stripe->sd_eof = true;
2766                                 break;
2767                         }
2768                         hash = end;
2769                 }
2770
2771                 oinfo = &op_data->op_mea1->lsm_md_oinfo[stripe_index];
2772                 if (!oinfo->lmo_root) {
2773                         rc = -ENOENT;
2774                         break;
2775                 }
2776
2777                 tgt = lmv_tgt(ctxt->ldc_lmv, oinfo->lmo_mds);
2778                 if (!tgt) {
2779                         rc = -ENODEV;
2780                         break;
2781                 }
2782
2783                 /* op_data is shared by stripes, reset after use */
2784                 op_data->op_fid1 = oinfo->lmo_fid;
2785                 op_data->op_fid2 = oinfo->lmo_fid;
2786                 op_data->op_data = oinfo->lmo_root;
2787
2788                 rc = md_read_page(tgt->ltd_exp, op_data, ctxt->ldc_mrinfo, hash,
2789                                   &stripe->sd_page);
2790
2791                 op_data->op_fid1 = fid;
2792                 op_data->op_fid2 = fid;
2793                 op_data->op_data = inode;
2794
2795                 if (rc)
2796                         break;
2797
2798                 stripe->sd_dp = page_address(stripe->sd_page);
2799                 ent = stripe_dirent_get(ctxt, lu_dirent_start(stripe->sd_dp),
2800                                         stripe_index);
2801                 /* in case a page filled with ., .. and dummy, read next */
2802         } while (!ent);
2803
2804         stripe->sd_ent = ent;
2805         if (rc) {
2806                 LASSERT(!ent);
2807                 /* treat error as eof, so dir can be partially accessed */
2808                 stripe->sd_eof = true;
2809                 ctxt->ldc_mrinfo->mr_partial_readdir_rc = rc;
2810                 LCONSOLE_WARN("dir "DFID" stripe %d readdir failed: %d, "
2811                               "directory is partially accessed!\n",
2812                               PFID(&ctxt->ldc_op_data->op_fid1), stripe_index,
2813                               rc);
2814         }
2815
2816         RETURN(ent);
2817 }
2818
2819 static int lmv_file_resync(struct obd_export *exp, struct md_op_data *data)
2820 {
2821         struct obd_device *obd = exp->exp_obd;
2822         struct lmv_obd *lmv = &obd->u.lmv;
2823         struct lmv_tgt_desc *tgt;
2824         int rc;
2825
2826         ENTRY;
2827
2828         rc = lmv_check_connect(obd);
2829         if (rc != 0)
2830                 RETURN(rc);
2831
2832         tgt = lmv_fid2tgt(lmv, &data->op_fid1);
2833         if (IS_ERR(tgt))
2834                 RETURN(PTR_ERR(tgt));
2835
2836         data->op_flags |= MF_MDC_CANCEL_FID1;
2837         rc = md_file_resync(tgt->ltd_exp, data);
2838         RETURN(rc);
2839 }
2840
2841 /**
2842  * Get dirent with the closest hash for striped directory
2843  *
2844  * This function will search the dir entry, whose hash value is the
2845  * closest(>=) to hash from all of sub-stripes, and it is only being called
2846  * for striped directory.
2847  *
2848  * \param[in] ctxt              dir read context
2849  *
2850  * \retval                      dirent get the entry successfully
2851  *                              NULL does not get the entry, normally it means
2852  *                              it reaches the end of the directory, while read
2853  *                              stripe dirent error is ignored to allow partial
2854  *                              access.
2855  */
2856 static struct lu_dirent *lmv_dirent_next(struct lmv_dir_ctxt *ctxt)
2857 {
2858         struct stripe_dirent *stripe;
2859         struct lu_dirent *ent = NULL;
2860         int i;
2861         int min = -1;
2862
2863         /* TODO: optimize with k-way merge sort */
2864         for (i = 0; i < ctxt->ldc_count; i++) {
2865                 stripe = &ctxt->ldc_stripes[i];
2866                 if (stripe->sd_eof)
2867                         continue;
2868
2869                 if (!stripe->sd_ent) {
2870                         stripe_dirent_load(ctxt, stripe, i);
2871                         if (!stripe->sd_ent) {
2872                                 LASSERT(stripe->sd_eof);
2873                                 continue;
2874                         }
2875                 }
2876
2877                 if (min == -1 ||
2878                     le64_to_cpu(ctxt->ldc_stripes[min].sd_ent->lde_hash) >
2879                     le64_to_cpu(stripe->sd_ent->lde_hash)) {
2880                         min = i;
2881                         if (le64_to_cpu(stripe->sd_ent->lde_hash) ==
2882                             ctxt->ldc_hash)
2883                                 break;
2884                 }
2885         }
2886
2887         if (min != -1) {
2888                 stripe = &ctxt->ldc_stripes[min];
2889                 ent = stripe->sd_ent;
2890                 /* pop found dirent */
2891                 stripe->sd_ent = stripe_dirent_get(ctxt, lu_dirent_next(ent),
2892                                                    min);
2893         }
2894
2895         return ent;
2896 }
2897
2898 /**
2899  * Build dir entry page for striped directory
2900  *
2901  * This function gets one entry by @offset from a striped directory. It will
2902  * read entries from all of stripes, and choose one closest to the required
2903  * offset(&offset). A few notes
2904  * 1. skip . and .. for non-zero stripes, because there can only have one .
2905  * and .. in a directory.
2906  * 2. op_data will be shared by all of stripes, instead of allocating new
2907  * one, so need to restore before reusing.
2908  *
2909  * \param[in] exp       obd export refer to LMV
2910  * \param[in] op_data   hold those MD parameters of read_entry
2911  * \param[in] mrinfo    ldlm callback being used in enqueue in mdc_read_entry,
2912  *                      and partial readdir result will be stored in it.
2913  * \param[in] offset    starting hash offset
2914  * \param[out] ppage    the page holding the entry. Note: because the entry
2915  *                      will be accessed in upper layer, so we need hold the
2916  *                      page until the usages of entry is finished, see
2917  *                      ll_dir_entry_next.
2918  *
2919  * retval               =0 if get entry successfully
2920  *                      <0 cannot get entry
2921  */
2922 static int lmv_striped_read_page(struct obd_export *exp,
2923                                  struct md_op_data *op_data,
2924                                  struct md_readdir_info *mrinfo, __u64 offset,
2925                                  struct page **ppage)
2926 {
2927         struct page *page = NULL;
2928         struct lu_dirpage *dp;
2929         void *start;
2930         struct lu_dirent *ent;
2931         struct lu_dirent *last_ent;
2932         int stripe_count;
2933         struct lmv_dir_ctxt *ctxt;
2934         struct lu_dirent *next = NULL;
2935         __u16 ent_size;
2936         size_t left_bytes;
2937         int rc = 0;
2938         ENTRY;
2939
2940         /* Allocate a page and read entries from all of stripes and fill
2941          * the page by hash order */
2942         page = alloc_page(GFP_KERNEL);
2943         if (!page)
2944                 RETURN(-ENOMEM);
2945
2946         /* Initialize the entry page */
2947         dp = kmap(page);
2948         memset(dp, 0, sizeof(*dp));
2949         dp->ldp_hash_start = cpu_to_le64(offset);
2950
2951         start = dp + 1;
2952         left_bytes = PAGE_SIZE - sizeof(*dp);
2953         ent = start;
2954         last_ent = ent;
2955
2956         /* initalize dir read context */
2957         stripe_count = op_data->op_mea1->lsm_md_stripe_count;
2958         OBD_ALLOC(ctxt, offsetof(typeof(*ctxt), ldc_stripes[stripe_count]));
2959         if (!ctxt)
2960                 GOTO(free_page, rc = -ENOMEM);
2961         ctxt->ldc_lmv = &exp->exp_obd->u.lmv;
2962         ctxt->ldc_op_data = op_data;
2963         ctxt->ldc_mrinfo = mrinfo;
2964         ctxt->ldc_hash = offset;
2965         ctxt->ldc_count = stripe_count;
2966
2967         while (1) {
2968                 next = lmv_dirent_next(ctxt);
2969
2970                 /* end of directory */
2971                 if (!next) {
2972                         ctxt->ldc_hash = MDS_DIR_END_OFF;
2973                         break;
2974                 }
2975                 ctxt->ldc_hash = le64_to_cpu(next->lde_hash);
2976
2977                 ent_size = le16_to_cpu(next->lde_reclen);
2978
2979                 /* the last entry lde_reclen is 0, but it might not be the last
2980                  * one of this temporay dir page */
2981                 if (!ent_size)
2982                         ent_size = lu_dirent_calc_size(
2983                                         le16_to_cpu(next->lde_namelen),
2984                                         le32_to_cpu(next->lde_attrs));
2985                 /* page full */
2986                 if (ent_size > left_bytes)
2987                         break;
2988
2989                 memcpy(ent, next, ent_size);
2990
2991                 /* Replace . with master FID and Replace .. with the parent FID
2992                  * of master object */
2993                 if (strncmp(ent->lde_name, ".",
2994                             le16_to_cpu(ent->lde_namelen)) == 0 &&
2995                     le16_to_cpu(ent->lde_namelen) == 1)
2996                         fid_cpu_to_le(&ent->lde_fid, &op_data->op_fid1);
2997                 else if (strncmp(ent->lde_name, "..",
2998                                    le16_to_cpu(ent->lde_namelen)) == 0 &&
2999                            le16_to_cpu(ent->lde_namelen) == 2)
3000                         fid_cpu_to_le(&ent->lde_fid, &op_data->op_fid3);
3001
3002                 CDEBUG(D_INODE, "entry %.*s hash %#llx\n",
3003                        le16_to_cpu(ent->lde_namelen), ent->lde_name,
3004                        le64_to_cpu(ent->lde_hash));
3005
3006                 left_bytes -= ent_size;
3007                 ent->lde_reclen = cpu_to_le16(ent_size);
3008                 last_ent = ent;
3009                 ent = (void *)ent + ent_size;
3010         };
3011
3012         last_ent->lde_reclen = 0;
3013
3014         if (ent == start)
3015                 dp->ldp_flags |= LDF_EMPTY;
3016         else if (ctxt->ldc_hash == le64_to_cpu(last_ent->lde_hash))
3017                 dp->ldp_flags |= LDF_COLLIDE;
3018         dp->ldp_flags = cpu_to_le32(dp->ldp_flags);
3019         dp->ldp_hash_end = cpu_to_le64(ctxt->ldc_hash);
3020
3021         put_lmv_dir_ctxt(ctxt);
3022         OBD_FREE(ctxt, offsetof(typeof(*ctxt), ldc_stripes[stripe_count]));
3023
3024         *ppage = page;
3025
3026         RETURN(0);
3027
3028 free_page:
3029         kunmap(page);
3030         __free_page(page);
3031
3032         return rc;
3033 }
3034
3035 static int lmv_read_page(struct obd_export *exp, struct md_op_data *op_data,
3036                          struct md_readdir_info *mrinfo, __u64 offset,
3037                          struct page **ppage)
3038 {
3039         struct obd_device *obd = exp->exp_obd;
3040         struct lmv_obd *lmv = &obd->u.lmv;
3041         struct lmv_tgt_desc *tgt;
3042         int rc;
3043
3044         ENTRY;
3045
3046         if (unlikely(lmv_dir_foreign(op_data->op_mea1)))
3047                 RETURN(-ENODATA);
3048
3049         if (unlikely(lmv_dir_striped(op_data->op_mea1))) {
3050                 rc = lmv_striped_read_page(exp, op_data, mrinfo, offset, ppage);
3051                 RETURN(rc);
3052         }
3053
3054         tgt = lmv_fid2tgt(lmv, &op_data->op_fid1);
3055         if (IS_ERR(tgt))
3056                 RETURN(PTR_ERR(tgt));
3057
3058         rc = md_read_page(tgt->ltd_exp, op_data, mrinfo, offset, ppage);
3059
3060         RETURN(rc);
3061 }
3062
3063 /**
3064  * Unlink a file/directory
3065  *
3066  * Unlink a file or directory under the parent dir. The unlink request
3067  * usually will be sent to the MDT where the child is located, but if
3068  * the client does not have the child FID then request will be sent to the
3069  * MDT where the parent is located.
3070  *
3071  * If the parent is a striped directory then it also needs to locate which
3072  * stripe the name of the child is located, and replace the parent FID
3073  * (@op->op_fid1) with the stripe FID. Note: if the stripe is unknown,
3074  * it will walk through all of sub-stripes until the child is being
3075  * unlinked finally.
3076  *
3077  * \param[in] exp       export refer to LMV
3078  * \param[in] op_data   different parameters transferred beween client
3079  *                      MD stacks, name, namelen, FIDs etc.
3080  *                      op_fid1 is the parent FID, op_fid2 is the child
3081  *                      FID.
3082  * \param[out] request  point to the request of unlink.
3083  *
3084  * retval               0 if succeed
3085  *                      negative errno if failed.
3086  */
3087 static int lmv_unlink(struct obd_export *exp, struct md_op_data *op_data,
3088                       struct ptlrpc_request **request)
3089 {
3090         struct obd_device *obd = exp->exp_obd;
3091         struct lmv_obd *lmv = &obd->u.lmv;
3092         struct lmv_tgt_desc *tgt;
3093         struct lmv_tgt_desc *parent_tgt;
3094         struct mdt_body *body;
3095         int rc;
3096
3097         ENTRY;
3098
3099         op_data->op_fsuid = from_kuid(&init_user_ns, current_fsuid());
3100         op_data->op_fsgid = from_kgid(&init_user_ns, current_fsgid());
3101         op_data->op_cap = current_cap();
3102
3103 retry:
3104         parent_tgt = lmv_locate_tgt(lmv, op_data);
3105         if (IS_ERR(parent_tgt))
3106                 RETURN(PTR_ERR(parent_tgt));
3107
3108         if (likely(!fid_is_zero(&op_data->op_fid2))) {
3109                 tgt = lmv_fid2tgt(lmv, &op_data->op_fid2);
3110                 if (IS_ERR(tgt))
3111                         RETURN(PTR_ERR(tgt));
3112         } else {
3113                 tgt = parent_tgt;
3114         }
3115
3116         /*
3117          * If child's fid is given, cancel unused locks for it if it is from
3118          * another export than parent.
3119          *
3120          * LOOKUP lock for child (fid3) should also be cancelled on parent
3121          * tgt_tgt in mdc_unlink().
3122          */
3123         op_data->op_flags |= MF_MDC_CANCEL_FID1 | MF_MDC_CANCEL_FID3;
3124
3125         if (parent_tgt != tgt)
3126                 rc = lmv_early_cancel(exp, parent_tgt, op_data, tgt->ltd_index,
3127                                       LCK_EX, MDS_INODELOCK_LOOKUP,
3128                                       MF_MDC_CANCEL_FID3);
3129
3130         rc = lmv_early_cancel(exp, NULL, op_data, tgt->ltd_index, LCK_EX,
3131                               MDS_INODELOCK_ELC, MF_MDC_CANCEL_FID3);
3132         if (rc)
3133                 RETURN(rc);
3134
3135         CDEBUG(D_INODE, "unlink with fid="DFID"/"DFID" -> mds #%u\n",
3136                PFID(&op_data->op_fid1), PFID(&op_data->op_fid2),
3137                tgt->ltd_index);
3138
3139         rc = md_unlink(tgt->ltd_exp, op_data, request);
3140         if (rc == -ENOENT && lmv_dir_retry_check_update(op_data)) {
3141                 ptlrpc_req_finished(*request);
3142                 *request = NULL;
3143                 goto retry;
3144         }
3145
3146         if (rc != -EREMOTE)
3147                 RETURN(rc);
3148
3149         body = req_capsule_server_get(&(*request)->rq_pill, &RMF_MDT_BODY);
3150         if (body == NULL)
3151                 RETURN(-EPROTO);
3152
3153         /* Not cross-ref case, just get out of here. */
3154         if (likely(!(body->mbo_valid & OBD_MD_MDS)))
3155                 RETURN(rc);
3156
3157         /* This is a remote object, try remote MDT. */
3158         op_data->op_fid2 = body->mbo_fid1;
3159         ptlrpc_req_finished(*request);
3160         *request = NULL;
3161
3162         tgt = lmv_fid2tgt(lmv, &op_data->op_fid2);
3163         if (IS_ERR(tgt))
3164                 RETURN(PTR_ERR(tgt));
3165
3166         goto retry;
3167 }
3168
3169 static int lmv_precleanup(struct obd_device *obd)
3170 {
3171         ENTRY;
3172         libcfs_kkuc_group_rem(&obd->obd_uuid, 0, KUC_GRP_HSM);
3173         RETURN(0);
3174 }
3175
3176 /**
3177  * Get by key a value associated with a LMV device.
3178  *
3179  * Dispatch request to lower-layer devices as needed.
3180  *
3181  * \param[in] env               execution environment for this thread
3182  * \param[in] exp               export for the LMV device
3183  * \param[in] keylen            length of key identifier
3184  * \param[in] key               identifier of key to get value for
3185  * \param[in] vallen            size of \a val
3186  * \param[out] val              pointer to storage location for value
3187  * \param[in] lsm               optional striping metadata of object
3188  *
3189  * \retval 0            on success
3190  * \retval negative     negated errno on failure
3191  */
3192 static int lmv_get_info(const struct lu_env *env, struct obd_export *exp,
3193                         __u32 keylen, void *key, __u32 *vallen, void *val)
3194 {
3195         struct obd_device *obd;
3196         struct lmv_obd *lmv;
3197         struct lu_tgt_desc *tgt;
3198         int rc = 0;
3199
3200         ENTRY;
3201
3202         obd = class_exp2obd(exp);
3203         if (obd == NULL) {
3204                 CDEBUG(D_IOCTL, "Invalid client cookie %#llx\n",
3205                        exp->exp_handle.h_cookie);
3206                 RETURN(-EINVAL);
3207         }
3208
3209         lmv = &obd->u.lmv;
3210         if (keylen >= strlen("remote_flag") && !strcmp(key, "remote_flag")) {
3211                 LASSERT(*vallen == sizeof(__u32));
3212                 lmv_foreach_connected_tgt(lmv, tgt) {
3213                         if (!obd_get_info(env, tgt->ltd_exp, keylen, key,
3214                                           vallen, val))
3215                                 RETURN(0);
3216                 }
3217                 RETURN(-EINVAL);
3218         } else if (KEY_IS(KEY_MAX_EASIZE) ||
3219                    KEY_IS(KEY_DEFAULT_EASIZE) ||
3220                    KEY_IS(KEY_CONN_DATA)) {
3221                 /*
3222                  * Forwarding this request to first MDS, it should know LOV
3223                  * desc.
3224                  */
3225                 tgt = lmv_tgt(lmv, 0);
3226                 if (!tgt)
3227                         RETURN(-ENODEV);
3228
3229                 rc = obd_get_info(env, tgt->ltd_exp, keylen, key, vallen, val);
3230                 if (!rc && KEY_IS(KEY_CONN_DATA))
3231                         exp->exp_connect_data = *(struct obd_connect_data *)val;
3232                 RETURN(rc);
3233         } else if (KEY_IS(KEY_TGT_COUNT)) {
3234                 *((int *)val) = lmv->lmv_mdt_descs.ltd_tgts_size;
3235                 RETURN(0);
3236         }
3237
3238         CDEBUG(D_IOCTL, "Invalid key\n");
3239         RETURN(-EINVAL);
3240 }
3241
3242 static int lmv_rmfid(struct obd_export *exp, struct fid_array *fa,
3243                      int *__rcs, struct ptlrpc_request_set *_set)
3244 {
3245         struct obd_device *obd = class_exp2obd(exp);
3246         struct ptlrpc_request_set *set = _set;
3247         struct lmv_obd *lmv = &obd->u.lmv;
3248         int tgt_count = lmv->lmv_mdt_count;
3249         struct lu_tgt_desc *tgt;
3250         struct fid_array *fat, **fas = NULL;
3251         int i, rc, **rcs = NULL;
3252
3253         if (!set) {
3254                 set = ptlrpc_prep_set();
3255                 if (!set)
3256                         RETURN(-ENOMEM);
3257         }
3258
3259         /* split FIDs by targets */
3260         OBD_ALLOC_PTR_ARRAY(fas, tgt_count);
3261         if (fas == NULL)
3262                 GOTO(out, rc = -ENOMEM);
3263         OBD_ALLOC_PTR_ARRAY(rcs, tgt_count);
3264         if (rcs == NULL)
3265                 GOTO(out_fas, rc = -ENOMEM);
3266
3267         for (i = 0; i < fa->fa_nr; i++) {
3268                 unsigned int idx;
3269
3270                 rc = lmv_fld_lookup(lmv, &fa->fa_fids[i], &idx);
3271                 if (rc) {
3272                         CDEBUG(D_OTHER, "can't lookup "DFID": rc = %d\n",
3273                                PFID(&fa->fa_fids[i]), rc);
3274                         continue;
3275                 }
3276                 LASSERT(idx < tgt_count);
3277                 if (!fas[idx])
3278                         OBD_ALLOC(fas[idx], offsetof(struct fid_array,
3279                                   fa_fids[fa->fa_nr]));
3280                 if (!fas[idx])
3281                         GOTO(out, rc = -ENOMEM);
3282                 if (!rcs[idx])
3283                         OBD_ALLOC_PTR_ARRAY(rcs[idx], fa->fa_nr);
3284                 if (!rcs[idx])
3285                         GOTO(out, rc = -ENOMEM);
3286
3287                 fat = fas[idx];
3288                 fat->fa_fids[fat->fa_nr++] = fa->fa_fids[i];
3289         }
3290
3291         lmv_foreach_connected_tgt(lmv, tgt) {
3292                 fat = fas[tgt->ltd_index];
3293                 if (!fat || fat->fa_nr == 0)
3294                         continue;
3295                 rc = md_rmfid(tgt->ltd_exp, fat, rcs[tgt->ltd_index], set);
3296         }
3297
3298         rc = ptlrpc_set_wait(NULL, set);
3299         if (rc == 0) {
3300                 int j = 0;
3301                 for (i = 0; i < tgt_count; i++) {
3302                         fat = fas[i];
3303                         if (!fat || fat->fa_nr == 0)
3304                                 continue;
3305                         /* copy FIDs back */
3306                         memcpy(fa->fa_fids + j, fat->fa_fids,
3307                                fat->fa_nr * sizeof(struct lu_fid));
3308                         /* copy rcs back */
3309                         memcpy(__rcs + j, rcs[i], fat->fa_nr * sizeof(**rcs));
3310                         j += fat->fa_nr;
3311                 }
3312         }
3313         if (set != _set)
3314                 ptlrpc_set_destroy(set);
3315
3316 out:
3317         for (i = 0; i < tgt_count; i++) {
3318                 if (fas && fas[i])
3319                         OBD_FREE(fas[i], offsetof(struct fid_array,
3320                                                 fa_fids[fa->fa_nr]));
3321                 if (rcs && rcs[i])
3322                         OBD_FREE_PTR_ARRAY(rcs[i], fa->fa_nr);
3323         }
3324         if (rcs)
3325                 OBD_FREE_PTR_ARRAY(rcs, tgt_count);
3326 out_fas:
3327         if (fas)
3328                 OBD_FREE_PTR_ARRAY(fas, tgt_count);
3329
3330         RETURN(rc);
3331 }
3332
3333 /**
3334  * Asynchronously set by key a value associated with a LMV device.
3335  *
3336  * Dispatch request to lower-layer devices as needed.
3337  *
3338  * \param[in] env       execution environment for this thread
3339  * \param[in] exp       export for the LMV device
3340  * \param[in] keylen    length of key identifier
3341  * \param[in] key       identifier of key to store value for
3342  * \param[in] vallen    size of value to store
3343  * \param[in] val       pointer to data to be stored
3344  * \param[in] set       optional list of related ptlrpc requests
3345  *
3346  * \retval 0            on success
3347  * \retval negative     negated errno on failure
3348  */
3349 static int lmv_set_info_async(const struct lu_env *env, struct obd_export *exp,
3350                               __u32 keylen, void *key, __u32 vallen, void *val,
3351                               struct ptlrpc_request_set *set)
3352 {
3353         struct lmv_tgt_desc *tgt;
3354         struct obd_device *obd;
3355         struct lmv_obd *lmv;
3356         int rc = 0;
3357         ENTRY;
3358
3359         obd = class_exp2obd(exp);
3360         if (obd == NULL) {
3361                 CDEBUG(D_IOCTL, "Invalid client cookie %#llx\n",
3362                        exp->exp_handle.h_cookie);
3363                 RETURN(-EINVAL);
3364         }
3365         lmv = &obd->u.lmv;
3366
3367         if (KEY_IS(KEY_READ_ONLY) || KEY_IS(KEY_FLUSH_CTX) ||
3368             KEY_IS(KEY_DEFAULT_EASIZE)) {
3369                 int err = 0;
3370
3371                 lmv_foreach_connected_tgt(lmv, tgt) {
3372                         err = obd_set_info_async(env, tgt->ltd_exp,
3373                                                  keylen, key, vallen, val, set);
3374                         if (err && rc == 0)
3375                                 rc = err;
3376                 }
3377
3378                 RETURN(rc);
3379         }
3380
3381         RETURN(-EINVAL);
3382 }
3383
3384 static int lmv_unpack_md_v1(struct obd_export *exp, struct lmv_stripe_md *lsm,
3385                             const struct lmv_mds_md_v1 *lmm1)
3386 {
3387         struct lmv_obd  *lmv = &exp->exp_obd->u.lmv;
3388         int             stripe_count;
3389         int             cplen;
3390         int             i;
3391         int             rc = 0;
3392         ENTRY;
3393
3394         lsm->lsm_md_magic = le32_to_cpu(lmm1->lmv_magic);
3395         lsm->lsm_md_stripe_count = le32_to_cpu(lmm1->lmv_stripe_count);
3396         lsm->lsm_md_master_mdt_index = le32_to_cpu(lmm1->lmv_master_mdt_index);
3397         if (CFS_FAIL_CHECK(OBD_FAIL_LMV_UNKNOWN_STRIPE))
3398                 lsm->lsm_md_hash_type = cfs_fail_val ?: LMV_HASH_TYPE_UNKNOWN;
3399         else
3400                 lsm->lsm_md_hash_type = le32_to_cpu(lmm1->lmv_hash_type);
3401         lsm->lsm_md_layout_version = le32_to_cpu(lmm1->lmv_layout_version);
3402         lsm->lsm_md_migrate_offset = le32_to_cpu(lmm1->lmv_migrate_offset);
3403         lsm->lsm_md_migrate_hash = le32_to_cpu(lmm1->lmv_migrate_hash);
3404         cplen = strlcpy(lsm->lsm_md_pool_name, lmm1->lmv_pool_name,
3405                         sizeof(lsm->lsm_md_pool_name));
3406
3407         if (cplen >= sizeof(lsm->lsm_md_pool_name))
3408                 RETURN(-E2BIG);
3409
3410         CDEBUG(D_INFO, "unpack lsm count %d/%d, master %d hash_type %#x/%#x "
3411                "layout_version %d\n", lsm->lsm_md_stripe_count,
3412                lsm->lsm_md_migrate_offset, lsm->lsm_md_master_mdt_index,
3413                lsm->lsm_md_hash_type, lsm->lsm_md_migrate_hash,
3414                lsm->lsm_md_layout_version);
3415
3416         stripe_count = le32_to_cpu(lmm1->lmv_stripe_count);
3417         for (i = 0; i < stripe_count; i++) {
3418                 fid_le_to_cpu(&lsm->lsm_md_oinfo[i].lmo_fid,
3419                               &lmm1->lmv_stripe_fids[i]);
3420                 /*
3421                  * set default value -1, so lmv_locate_tgt() knows this stripe
3422                  * target is not initialized.
3423                  */
3424                 lsm->lsm_md_oinfo[i].lmo_mds = LMV_OFFSET_DEFAULT;
3425                 if (!fid_is_sane(&lsm->lsm_md_oinfo[i].lmo_fid))
3426                         continue;
3427
3428                 rc = lmv_fld_lookup(lmv, &lsm->lsm_md_oinfo[i].lmo_fid,
3429                                     &lsm->lsm_md_oinfo[i].lmo_mds);
3430                 if (rc == -ENOENT)
3431                         continue;
3432
3433                 if (rc)
3434                         RETURN(rc);
3435
3436                 CDEBUG(D_INFO, "unpack fid #%d "DFID"\n", i,
3437                        PFID(&lsm->lsm_md_oinfo[i].lmo_fid));
3438         }
3439
3440         RETURN(rc);
3441 }
3442
3443 static inline int lmv_unpack_user_md(struct obd_export *exp,
3444                                      struct lmv_stripe_md *lsm,
3445                                      const struct lmv_user_md *lmu)
3446 {
3447         lsm->lsm_md_magic = le32_to_cpu(lmu->lum_magic);
3448         lsm->lsm_md_stripe_count = le32_to_cpu(lmu->lum_stripe_count);
3449         lsm->lsm_md_master_mdt_index = le32_to_cpu(lmu->lum_stripe_offset);
3450         lsm->lsm_md_hash_type = le32_to_cpu(lmu->lum_hash_type);
3451         lsm->lsm_md_max_inherit = lmu->lum_max_inherit;
3452         lsm->lsm_md_max_inherit_rr = lmu->lum_max_inherit_rr;
3453         lsm->lsm_md_pool_name[LOV_MAXPOOLNAME] = 0;
3454
3455         return 0;
3456 }
3457
3458 static int lmv_unpackmd(struct obd_export *exp, struct lmv_stripe_md **lsmp,
3459                         const union lmv_mds_md *lmm, size_t lmm_size)
3460 {
3461         struct lmv_stripe_md     *lsm;
3462         int                      lsm_size;
3463         int                      rc;
3464         bool                     allocated = false;
3465         ENTRY;
3466
3467         LASSERT(lsmp != NULL);
3468
3469         lsm = *lsmp;
3470         /* Free memmd */
3471         if (lsm != NULL && lmm == NULL) {
3472                 int i;
3473                 struct lmv_foreign_md *lfm = (struct lmv_foreign_md *)lsm;
3474
3475                 if (lfm->lfm_magic == LMV_MAGIC_FOREIGN) {
3476                         size_t lfm_size;
3477
3478                         lfm_size = lfm->lfm_length + offsetof(typeof(*lfm),
3479                                                               lfm_value[0]);
3480                         OBD_FREE_LARGE(lfm, lfm_size);
3481                         RETURN(0);
3482                 }
3483
3484                 if (lmv_dir_striped(lsm)) {
3485                         for (i = 0; i < lsm->lsm_md_stripe_count; i++)
3486                                 iput(lsm->lsm_md_oinfo[i].lmo_root);
3487                         lsm_size = lmv_stripe_md_size(lsm->lsm_md_stripe_count);
3488                 } else {
3489                         lsm_size = lmv_stripe_md_size(0);
3490                 }
3491                 OBD_FREE(lsm, lsm_size);
3492                 *lsmp = NULL;
3493                 RETURN(0);
3494         }
3495
3496         /* foreign lmv case */
3497         if (le32_to_cpu(lmm->lmv_magic) == LMV_MAGIC_FOREIGN) {
3498                 struct lmv_foreign_md *lfm = (struct lmv_foreign_md *)lsm;
3499
3500                 if (lfm == NULL) {
3501                         OBD_ALLOC_LARGE(lfm, lmm_size);
3502                         if (lfm == NULL)
3503                                 RETURN(-ENOMEM);
3504                         *lsmp = (struct lmv_stripe_md *)lfm;
3505                 }
3506                 lfm->lfm_magic = le32_to_cpu(lmm->lmv_foreign_md.lfm_magic);
3507                 lfm->lfm_length = le32_to_cpu(lmm->lmv_foreign_md.lfm_length);
3508                 lfm->lfm_type = le32_to_cpu(lmm->lmv_foreign_md.lfm_type);
3509                 lfm->lfm_flags = le32_to_cpu(lmm->lmv_foreign_md.lfm_flags);
3510                 memcpy(&lfm->lfm_value, &lmm->lmv_foreign_md.lfm_value,
3511                        lfm->lfm_length);
3512                 RETURN(lmm_size);
3513         }
3514
3515         if (le32_to_cpu(lmm->lmv_magic) == LMV_MAGIC_STRIPE)
3516                 RETURN(-EPERM);
3517
3518         /* Unpack memmd */
3519         if (le32_to_cpu(lmm->lmv_magic) != LMV_MAGIC_V1 &&
3520             le32_to_cpu(lmm->lmv_magic) != LMV_USER_MAGIC) {
3521                 CERROR("%s: invalid lmv magic %x: rc = %d\n",
3522                        exp->exp_obd->obd_name, le32_to_cpu(lmm->lmv_magic),
3523                        -EIO);
3524                 RETURN(-EIO);
3525         }
3526
3527         if (le32_to_cpu(lmm->lmv_magic) == LMV_MAGIC_V1)
3528                 lsm_size = lmv_stripe_md_size(lmv_mds_md_stripe_count_get(lmm));
3529         else
3530                 /**
3531                  * Unpack default dirstripe(lmv_user_md) to lmv_stripe_md,
3532                  * stripecount should be 0 then.
3533                  */
3534                 lsm_size = lmv_stripe_md_size(0);
3535
3536         if (lsm == NULL) {
3537                 OBD_ALLOC(lsm, lsm_size);
3538                 if (lsm == NULL)
3539                         RETURN(-ENOMEM);
3540                 allocated = true;
3541                 *lsmp = lsm;
3542         }
3543
3544         switch (le32_to_cpu(lmm->lmv_magic)) {
3545         case LMV_MAGIC_V1:
3546                 rc = lmv_unpack_md_v1(exp, lsm, &lmm->lmv_md_v1);
3547                 break;
3548         case LMV_USER_MAGIC:
3549                 rc = lmv_unpack_user_md(exp, lsm, &lmm->lmv_user_md);
3550                 break;
3551         default:
3552                 CERROR("%s: unrecognized magic %x\n", exp->exp_obd->obd_name,
3553                        le32_to_cpu(lmm->lmv_magic));
3554                 rc = -EINVAL;
3555                 break;
3556         }
3557
3558         if (rc != 0 && allocated) {
3559                 OBD_FREE(lsm, lsm_size);
3560                 *lsmp = NULL;
3561                 lsm_size = rc;
3562         }
3563         RETURN(lsm_size);
3564 }
3565
3566 void lmv_free_memmd(struct lmv_stripe_md *lsm)
3567 {
3568         lmv_unpackmd(NULL, &lsm, NULL, 0);
3569 }
3570 EXPORT_SYMBOL(lmv_free_memmd);
3571
3572 static int lmv_cancel_unused(struct obd_export *exp, const struct lu_fid *fid,
3573                              union ldlm_policy_data *policy,
3574                              enum ldlm_mode mode, enum ldlm_cancel_flags flags,
3575                              void *opaque)
3576 {
3577         struct lmv_obd *lmv = &exp->exp_obd->u.lmv;
3578         struct lu_tgt_desc *tgt;
3579         int err;
3580         int rc = 0;
3581
3582         ENTRY;
3583
3584         LASSERT(fid != NULL);
3585
3586         lmv_foreach_connected_tgt(lmv, tgt) {
3587                 if (!tgt->ltd_active)
3588                         continue;
3589
3590                 err = md_cancel_unused(tgt->ltd_exp, fid, policy, mode, flags,
3591                                        opaque);
3592                 if (!rc)
3593                         rc = err;
3594         }
3595         RETURN(rc);
3596 }
3597
3598 static int lmv_set_lock_data(struct obd_export *exp,
3599                              const struct lustre_handle *lockh,
3600                              void *data, __u64 *bits)
3601 {
3602         struct lmv_obd *lmv = &exp->exp_obd->u.lmv;
3603         struct lmv_tgt_desc *tgt = lmv_tgt(lmv, 0);
3604         int rc;
3605
3606         ENTRY;
3607
3608         if (tgt == NULL || tgt->ltd_exp == NULL)
3609                 RETURN(-EINVAL);
3610         rc =  md_set_lock_data(tgt->ltd_exp, lockh, data, bits);
3611         RETURN(rc);
3612 }
3613
3614 static enum ldlm_mode
3615 lmv_lock_match(struct obd_export *exp, __u64 flags,
3616                const struct lu_fid *fid, enum ldlm_type type,
3617                union ldlm_policy_data *policy,
3618                enum ldlm_mode mode, struct lustre_handle *lockh)
3619 {
3620         struct obd_device *obd = exp->exp_obd;
3621         struct lmv_obd *lmv = &obd->u.lmv;
3622         struct lu_tgt_desc *tgt;
3623         __u64 bits = policy->l_inodebits.bits;
3624         enum ldlm_mode rc = LCK_MINMODE;
3625         int index;
3626         int i;
3627
3628         /* only one bit is set */
3629         LASSERT(bits && !(bits & (bits - 1)));
3630         /* With DNE every object can have two locks in different namespaces:
3631          * lookup lock in space of MDT storing direntry and update/open lock in
3632          * space of MDT storing inode.  Try the MDT that the FID maps to first,
3633          * since this can be easily found, and only try others if that fails.
3634          */
3635         if (bits == MDS_INODELOCK_LOOKUP) {
3636                 for (i = 0, index = lmv_fid2tgt_index(lmv, fid);
3637                      i < lmv->lmv_mdt_descs.ltd_tgts_size; i++,
3638                      index = (index + 1) % lmv->lmv_mdt_descs.ltd_tgts_size) {
3639                         if (index < 0) {
3640                                 CDEBUG(D_HA,
3641                                        "%s: "DFID" is inaccessible: rc = %d\n",
3642                                        obd->obd_name, PFID(fid), index);
3643                                 index = 0;
3644                         }
3645                         tgt = lmv_tgt(lmv, index);
3646                         if (!tgt || !tgt->ltd_exp || !tgt->ltd_active)
3647                                 continue;
3648                         rc = md_lock_match(tgt->ltd_exp, flags, fid, type,
3649                                            policy, mode, lockh);
3650                         if (rc)
3651                                 break;
3652                 }
3653         } else {
3654                 tgt = lmv_fid2tgt(lmv, fid);
3655                 if (!IS_ERR(tgt) && tgt->ltd_exp && tgt->ltd_active)
3656                         rc = md_lock_match(tgt->ltd_exp, flags, fid, type,
3657                                            policy, mode, lockh);
3658         }
3659
3660         CDEBUG(D_INODE, "Lock match for "DFID": %d\n", PFID(fid), rc);
3661
3662         return rc;
3663 }
3664
3665 static int
3666 lmv_get_lustre_md(struct obd_export *exp, struct req_capsule *pill,
3667                   struct obd_export *dt_exp, struct obd_export *md_exp,
3668                   struct lustre_md *md)
3669 {
3670         struct lmv_obd *lmv = &exp->exp_obd->u.lmv;
3671         struct lmv_tgt_desc *tgt = lmv_tgt(lmv, 0);
3672
3673         if (!tgt || !tgt->ltd_exp)
3674                 return -EINVAL;
3675
3676         return md_get_lustre_md(tgt->ltd_exp, pill, dt_exp, md_exp, md);
3677 }
3678
3679 static int lmv_free_lustre_md(struct obd_export *exp, struct lustre_md *md)
3680 {
3681         struct obd_device *obd = exp->exp_obd;
3682         struct lmv_obd *lmv = &obd->u.lmv;
3683         struct lmv_tgt_desc *tgt = lmv_tgt(lmv, 0);
3684
3685         ENTRY;
3686
3687         if (md->default_lmv) {
3688                 lmv_free_memmd(md->default_lmv);
3689                 md->default_lmv = NULL;
3690         }
3691         if (md->lmv != NULL) {
3692                 lmv_free_memmd(md->lmv);
3693                 md->lmv = NULL;
3694         }
3695         if (!tgt || !tgt->ltd_exp)
3696                 RETURN(-EINVAL);
3697         RETURN(md_free_lustre_md(tgt->ltd_exp, md));
3698 }
3699
3700 static int lmv_set_open_replay_data(struct obd_export *exp,
3701                                     struct obd_client_handle *och,
3702                                     struct lookup_intent *it)
3703 {
3704         struct obd_device *obd = exp->exp_obd;
3705         struct lmv_obd *lmv = &obd->u.lmv;
3706         struct lmv_tgt_desc *tgt;
3707
3708         ENTRY;
3709
3710         tgt = lmv_fid2tgt(lmv, &och->och_fid);
3711         if (IS_ERR(tgt))
3712                 RETURN(PTR_ERR(tgt));
3713
3714         RETURN(md_set_open_replay_data(tgt->ltd_exp, och, it));
3715 }
3716
3717 static int lmv_clear_open_replay_data(struct obd_export *exp,
3718                                       struct obd_client_handle *och)
3719 {
3720         struct obd_device *obd = exp->exp_obd;
3721         struct lmv_obd *lmv = &obd->u.lmv;
3722         struct lmv_tgt_desc *tgt;
3723
3724         ENTRY;
3725
3726         tgt = lmv_fid2tgt(lmv, &och->och_fid);
3727         if (IS_ERR(tgt))
3728                 RETURN(PTR_ERR(tgt));
3729
3730         RETURN(md_clear_open_replay_data(tgt->ltd_exp, och));
3731 }
3732
3733 static int lmv_intent_getattr_async(struct obd_export *exp,
3734                                     struct md_op_item *item)
3735 {
3736         struct md_op_data *op_data = &item->mop_data;
3737         struct obd_device *obd = exp->exp_obd;
3738         struct lmv_obd *lmv = &obd->u.lmv;
3739         struct lmv_tgt_desc *ptgt;
3740         struct lmv_tgt_desc *ctgt;
3741         int rc;
3742
3743         ENTRY;
3744
3745         if (!fid_is_sane(&op_data->op_fid2))
3746                 RETURN(-EINVAL);
3747
3748         ptgt = lmv_locate_tgt(lmv, op_data);
3749         if (IS_ERR(ptgt))
3750                 RETURN(PTR_ERR(ptgt));
3751
3752         ctgt = lmv_fid2tgt(lmv, &op_data->op_fid2);
3753         if (IS_ERR(ctgt))
3754                 RETURN(PTR_ERR(ctgt));
3755
3756         /*
3757          * remote object needs two RPCs to lookup and getattr, considering the
3758          * complexity don't support statahead for now.
3759          */
3760         if (ctgt != ptgt)
3761                 RETURN(-EREMOTE);
3762
3763         rc = md_intent_getattr_async(ptgt->ltd_exp, item);
3764
3765         RETURN(rc);
3766 }
3767
3768 static int lmv_revalidate_lock(struct obd_export *exp, struct lookup_intent *it,
3769                                struct lu_fid *fid, __u64 *bits)
3770 {
3771         struct obd_device *obd = exp->exp_obd;
3772         struct lmv_obd *lmv = &obd->u.lmv;
3773         struct lmv_tgt_desc *tgt;
3774         int rc;
3775
3776         ENTRY;
3777
3778         tgt = lmv_fid2tgt(lmv, fid);
3779         if (IS_ERR(tgt))
3780                 RETURN(PTR_ERR(tgt));
3781
3782         rc = md_revalidate_lock(tgt->ltd_exp, it, fid, bits);
3783         RETURN(rc);
3784 }
3785
3786 static int lmv_get_fid_from_lsm(struct obd_export *exp,
3787                                 const struct lmv_stripe_md *lsm,
3788                                 const char *name, int namelen,
3789                                 struct lu_fid *fid)
3790 {
3791         const struct lmv_oinfo *oinfo;
3792
3793         if (!lmv_dir_striped(lsm))
3794                 RETURN(-ESTALE);
3795
3796         oinfo = lsm_name_to_stripe_info(lsm, name, namelen, false);
3797         if (IS_ERR(oinfo))
3798                 return PTR_ERR(oinfo);
3799
3800         *fid = oinfo->lmo_fid;
3801
3802         RETURN(0);
3803 }
3804
3805 /**
3806  * For lmv, only need to send request to master MDT, and the master MDT will
3807  * process with other slave MDTs. The only exception is Q_GETOQUOTA for which
3808  * we directly fetch data from the slave MDTs.
3809  */
3810 static int lmv_quotactl(struct obd_device *unused, struct obd_export *exp,
3811                         struct obd_quotactl *oqctl)
3812 {
3813         struct obd_device *obd = class_exp2obd(exp);
3814         struct lmv_obd *lmv = &obd->u.lmv;
3815         struct lmv_tgt_desc *tgt = lmv_tgt(lmv, 0);
3816         __u64 curspace, curinodes;
3817         int rc = 0;
3818
3819         ENTRY;
3820
3821         if (!tgt || !tgt->ltd_exp || !tgt->ltd_active) {
3822                 CERROR("master lmv inactive\n");
3823                 RETURN(-EIO);
3824         }
3825
3826         if (oqctl->qc_cmd != Q_GETOQUOTA) {
3827                 rc = obd_quotactl(tgt->ltd_exp, oqctl);
3828                 RETURN(rc);
3829         }
3830
3831         curspace = curinodes = 0;
3832         lmv_foreach_connected_tgt(lmv, tgt) {
3833                 int err;
3834
3835                 if (!tgt->ltd_active)
3836                         continue;
3837
3838                 err = obd_quotactl(tgt->ltd_exp, oqctl);
3839                 if (err) {
3840                         CERROR("getquota on mdt %d failed. %d\n",
3841                                tgt->ltd_index, err);
3842                         if (!rc)
3843                                 rc = err;
3844                 } else {
3845                         curspace += oqctl->qc_dqblk.dqb_curspace;
3846                         curinodes += oqctl->qc_dqblk.dqb_curinodes;
3847                 }
3848         }
3849         oqctl->qc_dqblk.dqb_curspace = curspace;
3850         oqctl->qc_dqblk.dqb_curinodes = curinodes;
3851
3852         RETURN(rc);
3853 }
3854
3855 static int lmv_merge_attr(struct obd_export *exp,
3856                           const struct lmv_stripe_md *lsm,
3857                           struct cl_attr *attr,
3858                           ldlm_blocking_callback cb_blocking)
3859 {
3860         int rc;
3861         int i;
3862
3863         if (!lmv_dir_striped(lsm))
3864                 return 0;
3865
3866         rc = lmv_revalidate_slaves(exp, lsm, cb_blocking, 0);
3867         if (rc < 0)
3868                 return rc;
3869
3870         for (i = 0; i < lsm->lsm_md_stripe_count; i++) {
3871                 struct inode *inode = lsm->lsm_md_oinfo[i].lmo_root;
3872
3873                 if (!inode)
3874                         continue;
3875
3876                 CDEBUG(D_INFO,
3877                        "" DFID " size %llu, blocks %llu nlink %u, atime %lld ctime %lld, mtime %lld.\n",
3878                        PFID(&lsm->lsm_md_oinfo[i].lmo_fid),
3879                        i_size_read(inode), (unsigned long long)inode->i_blocks,
3880                        inode->i_nlink, (s64)inode->i_atime.tv_sec,
3881                        (s64)inode->i_ctime.tv_sec, (s64)inode->i_mtime.tv_sec);
3882
3883                 /* for slave stripe, it needs to subtract nlink for . and .. */
3884                 if (i != 0)
3885                         attr->cat_nlink += inode->i_nlink - 2;
3886                 else
3887                         attr->cat_nlink = inode->i_nlink;
3888
3889                 attr->cat_size += i_size_read(inode);
3890                 attr->cat_blocks += inode->i_blocks;
3891
3892                 if (attr->cat_atime < inode->i_atime.tv_sec)
3893                         attr->cat_atime = inode->i_atime.tv_sec;
3894
3895                 if (attr->cat_ctime < inode->i_ctime.tv_sec)
3896                         attr->cat_ctime = inode->i_ctime.tv_sec;
3897
3898                 if (attr->cat_mtime < inode->i_mtime.tv_sec)
3899                         attr->cat_mtime = inode->i_mtime.tv_sec;
3900         }
3901         return 0;
3902 }
3903
3904 static struct lu_batch *lmv_batch_create(struct obd_export *exp,
3905                                          enum lu_batch_flags flags,
3906                                          __u32 max_count)
3907 {
3908         struct lu_batch *bh;
3909         struct lmv_batch *lbh;
3910
3911         ENTRY;
3912         OBD_ALLOC_PTR(lbh);
3913         if (!lbh)
3914                 RETURN(ERR_PTR(-ENOMEM));
3915
3916         bh = &lbh->lbh_super;
3917         bh->lbt_flags = flags;
3918         bh->lbt_max_count = max_count;
3919
3920         if (flags & BATCH_FL_RQSET) {
3921                 bh->lbt_rqset = ptlrpc_prep_set();
3922                 if (bh->lbt_rqset == NULL) {
3923                         OBD_FREE_PTR(lbh);
3924                         RETURN(ERR_PTR(-ENOMEM));
3925                 }
3926         }
3927
3928         INIT_LIST_HEAD(&lbh->lbh_sub_batch_list);
3929         RETURN(bh);
3930 }
3931
3932 static int lmv_batch_stop(struct obd_export *exp, struct lu_batch *bh)
3933 {
3934         struct lmv_batch *lbh;
3935         struct lmvsub_batch *sub;
3936         struct lmvsub_batch *tmp;
3937         int rc = 0;
3938
3939         ENTRY;
3940
3941         lbh = container_of(bh, struct lmv_batch, lbh_super);
3942         list_for_each_entry_safe(sub, tmp, &lbh->lbh_sub_batch_list,
3943                                  sbh_sub_item) {
3944                 list_del(&sub->sbh_sub_item);
3945                 rc = md_batch_stop(sub->sbh_tgt->ltd_exp, sub->sbh_sub);
3946                 if (rc < 0) {
3947                         CERROR("%s: stop batch processing failed: rc = %d\n",
3948                                exp->exp_obd->obd_name, rc);
3949                         if (bh->lbt_result == 0)
3950                                 bh->lbt_result = rc;
3951                 }
3952                 OBD_FREE_PTR(sub);
3953         }
3954
3955         if (bh->lbt_flags & BATCH_FL_RQSET) {
3956                 rc = ptlrpc_set_wait(NULL, bh->lbt_rqset);
3957                 ptlrpc_set_destroy(bh->lbt_rqset);
3958         }
3959
3960         OBD_FREE_PTR(lbh);
3961         RETURN(rc);
3962 }
3963
3964 static int lmv_batch_flush(struct obd_export *exp, struct lu_batch *bh,
3965                            bool wait)
3966 {
3967         struct lmv_batch *lbh;
3968         struct lmvsub_batch *sub;
3969         int rc = 0;
3970         int rc1;
3971
3972         ENTRY;
3973
3974         lbh = container_of(bh, struct lmv_batch, lbh_super);
3975         list_for_each_entry(sub, &lbh->lbh_sub_batch_list, sbh_sub_item) {
3976                 rc1 = md_batch_flush(sub->sbh_tgt->ltd_exp, sub->sbh_sub, wait);
3977                 if (rc1 < 0) {
3978                         CERROR("%s: stop batch processing failed: rc = %d\n",
3979                                exp->exp_obd->obd_name, rc);
3980                         if (bh->lbt_result == 0)
3981                                 bh->lbt_result = rc;
3982
3983                         if (rc == 0)
3984                                 rc = rc1;
3985                 }
3986         }
3987
3988         if (wait && bh->lbt_flags & BATCH_FL_RQSET) {
3989                 rc1 = ptlrpc_set_wait(NULL, bh->lbt_rqset);
3990                 if (rc == 0)
3991                         rc = rc1;
3992         }
3993
3994         RETURN(rc);
3995 }
3996
3997 static inline struct lmv_tgt_desc *
3998 lmv_batch_locate_tgt(struct lmv_obd *lmv, struct md_op_item *item)
3999 {
4000         struct lmv_tgt_desc *tgt;
4001
4002         switch (item->mop_opc) {
4003         default:
4004                 tgt = ERR_PTR(-ENOTSUPP);
4005         }
4006
4007         return tgt;
4008 }
4009
4010 struct lu_batch *lmv_batch_lookup_sub(struct lmv_batch *lbh,
4011                                       struct lmv_tgt_desc *tgt)
4012 {
4013         struct lmvsub_batch *sub;
4014
4015         list_for_each_entry(sub, &lbh->lbh_sub_batch_list, sbh_sub_item) {
4016                 if (sub->sbh_tgt == tgt)
4017                         return sub->sbh_sub;
4018         }
4019
4020         return NULL;
4021 }
4022
4023 struct lu_batch *lmv_batch_get_sub(struct lmv_batch *lbh,
4024                                    struct lmv_tgt_desc *tgt)
4025 {
4026         struct lmvsub_batch *sbh;
4027         struct lu_batch *child_bh;
4028         struct lu_batch *bh;
4029
4030         ENTRY;
4031
4032         child_bh = lmv_batch_lookup_sub(lbh, tgt);
4033         if (child_bh != NULL)
4034                 RETURN(child_bh);
4035
4036         OBD_ALLOC_PTR(sbh);
4037         if (sbh == NULL)
4038                 RETURN(ERR_PTR(-ENOMEM));
4039
4040         INIT_LIST_HEAD(&sbh->sbh_sub_item);
4041         sbh->sbh_tgt = tgt;
4042
4043         bh = &lbh->lbh_super;
4044         child_bh = md_batch_create(tgt->ltd_exp, bh->lbt_flags,
4045                                    bh->lbt_max_count);
4046         if (IS_ERR(child_bh)) {
4047                 OBD_FREE_PTR(sbh);
4048                 RETURN(child_bh);
4049         }
4050
4051         child_bh->lbt_rqset = bh->lbt_rqset;
4052         sbh->sbh_sub = child_bh;
4053         list_add(&sbh->sbh_sub_item, &lbh->lbh_sub_batch_list);
4054         RETURN(child_bh);
4055 }
4056
4057 static int lmv_batch_add(struct obd_export *exp, struct lu_batch *bh,
4058                          struct md_op_item *item)
4059 {
4060         struct obd_device *obd = exp->exp_obd;
4061         struct lmv_obd *lmv = &obd->u.lmv;
4062         struct lmv_tgt_desc *tgt;
4063         struct lmv_batch *lbh;
4064         struct lu_batch *child_bh;
4065         int rc;
4066
4067         ENTRY;
4068
4069         tgt = lmv_batch_locate_tgt(lmv, item);
4070         if (IS_ERR(tgt))
4071                 RETURN(PTR_ERR(tgt));
4072
4073         lbh = container_of(bh, struct lmv_batch, lbh_super);
4074         child_bh = lmv_batch_get_sub(lbh, tgt);
4075         if (IS_ERR(child_bh))
4076                 RETURN(PTR_ERR(child_bh));
4077
4078         rc = md_batch_add(tgt->ltd_exp, child_bh, item);
4079         RETURN(rc);
4080 }
4081
4082 static const struct obd_ops lmv_obd_ops = {
4083         .o_owner                = THIS_MODULE,
4084         .o_setup                = lmv_setup,
4085         .o_cleanup              = lmv_cleanup,
4086         .o_precleanup           = lmv_precleanup,
4087         .o_process_config       = lmv_process_config,
4088         .o_connect              = lmv_connect,
4089         .o_disconnect           = lmv_disconnect,
4090         .o_statfs               = lmv_statfs,
4091         .o_get_info             = lmv_get_info,
4092         .o_set_info_async       = lmv_set_info_async,
4093         .o_notify               = lmv_notify,
4094         .o_get_uuid             = lmv_get_uuid,
4095         .o_fid_alloc            = lmv_fid_alloc,
4096         .o_iocontrol            = lmv_iocontrol,
4097         .o_quotactl             = lmv_quotactl
4098 };
4099
4100 static const struct md_ops lmv_md_ops = {
4101         .m_get_root             = lmv_get_root,
4102         .m_null_inode           = lmv_null_inode,
4103         .m_close                = lmv_close,
4104         .m_create               = lmv_create,
4105         .m_enqueue              = lmv_enqueue,
4106         .m_getattr              = lmv_getattr,
4107         .m_getxattr             = lmv_getxattr,
4108         .m_getattr_name         = lmv_getattr_name,
4109         .m_intent_lock          = lmv_intent_lock,
4110         .m_link                 = lmv_link,
4111         .m_rename               = lmv_rename,
4112         .m_setattr              = lmv_setattr,
4113         .m_setxattr             = lmv_setxattr,
4114         .m_fsync                = lmv_fsync,
4115         .m_file_resync          = lmv_file_resync,
4116         .m_read_page            = lmv_read_page,
4117         .m_unlink               = lmv_unlink,
4118         .m_init_ea_size         = lmv_init_ea_size,
4119         .m_cancel_unused        = lmv_cancel_unused,
4120         .m_set_lock_data        = lmv_set_lock_data,
4121         .m_lock_match           = lmv_lock_match,
4122         .m_get_lustre_md        = lmv_get_lustre_md,
4123         .m_free_lustre_md       = lmv_free_lustre_md,
4124         .m_merge_attr           = lmv_merge_attr,
4125         .m_set_open_replay_data = lmv_set_open_replay_data,
4126         .m_clear_open_replay_data = lmv_clear_open_replay_data,
4127         .m_intent_getattr_async = lmv_intent_getattr_async,
4128         .m_revalidate_lock      = lmv_revalidate_lock,
4129         .m_get_fid_from_lsm     = lmv_get_fid_from_lsm,
4130         .m_unpackmd             = lmv_unpackmd,
4131         .m_rmfid                = lmv_rmfid,
4132         .m_batch_create         = lmv_batch_create,
4133         .m_batch_add            = lmv_batch_add,
4134         .m_batch_stop           = lmv_batch_stop,
4135         .m_batch_flush          = lmv_batch_flush,
4136 };
4137
4138 static int __init lmv_init(void)
4139 {
4140         return class_register_type(&lmv_obd_ops, &lmv_md_ops, true,
4141                                    LUSTRE_LMV_NAME, NULL);
4142 }
4143
4144 static void __exit lmv_exit(void)
4145 {
4146         class_unregister_type(LUSTRE_LMV_NAME);
4147 }
4148
4149 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
4150 MODULE_DESCRIPTION("Lustre Logical Metadata Volume");
4151 MODULE_VERSION(LUSTRE_VERSION_STRING);
4152 MODULE_LICENSE("GPL");
4153
4154 module_init(lmv_init);
4155 module_exit(lmv_exit);