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