Whamcloud - gitweb
LU-16529 test: verify the grant > 0 before test
[fs/lustre-release.git] / lustre / lod / lod_qos.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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright  2009 Sun Microsystems, Inc. All rights reserved
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/lod/lod_qos.c
32  *
33  * Implementation of different allocation algorithm used
34  * to distribute objects and data among OSTs.
35  */
36
37 #define DEBUG_SUBSYSTEM S_LOV
38
39 #include <asm/div64.h>
40 #include <linux/random.h>
41
42 #include <libcfs/libcfs.h>
43 #include <uapi/linux/lustre/lustre_idl.h>
44 #include <lustre_swab.h>
45 #include <obd_class.h>
46
47 #include "lod_internal.h"
48
49 /*
50  * force QoS policy (not RR) to be used for testing purposes
51  */
52 #define FORCE_QOS_
53
54 #define D_QOS   D_OTHER
55
56 #define QOS_DEBUG(fmt, ...)     CDEBUG(D_QOS, fmt, ## __VA_ARGS__)
57 #define QOS_CONSOLE(fmt, ...)   LCONSOLE(D_QOS, fmt, ## __VA_ARGS__)
58
59 #define TGT_BAVAIL(i) (OST_TGT(lod,i)->ltd_statfs.os_bavail * \
60                        OST_TGT(lod,i)->ltd_statfs.os_bsize)
61
62 static inline int lod_statfs_check(struct lu_tgt_descs *ltd,
63                                    struct lu_tgt_desc *tgt)
64 {
65         struct obd_statfs *sfs = &tgt->ltd_statfs;
66
67         if (((sfs->os_state & OS_STATFS_ENOSPC) ||
68             (!ltd->ltd_is_mdt && sfs->os_state & OS_STATFS_ENOINO &&
69              sfs->os_fprecreated == 0)))
70                 return -ENOSPC;
71
72         /* If the OST is readonly then we can't allocate objects there */
73         if (sfs->os_state & OS_STATFS_READONLY)
74                 return -EROFS;
75
76         /* object precreation is skipped on the OST with max_create_count=0 */
77         if (!ltd->ltd_is_mdt && sfs->os_state & OS_STATFS_NOPRECREATE)
78                 return -ENOBUFS;
79
80         return 0;
81 }
82
83 /**
84  * Check whether the target is available for new objects.
85  *
86  * Request statfs data from the given target and verify it's active and not
87  * read-only. If so, then it can be used to place new objects. This
88  * function also maintains the number of active/inactive targets and sets
89  * dirty flags if those numbers change so others can run re-balance procedures.
90  * No external locking is required.
91  *
92  * \param[in] env       execution environment for this thread
93  * \param[in] d         LOD device
94  * \param[in] ltd       target table
95  * \param[in] tgt       target
96  *
97  * \retval 0            if the target is good
98  * \retval negative     negated errno on error
99  */
100 static int lod_statfs_and_check(const struct lu_env *env, struct lod_device *d,
101                                 struct lu_tgt_descs *ltd,
102                                 struct lu_tgt_desc *tgt, __u64 reserve)
103 {
104         struct obd_statfs_info info = { 0 };
105         struct lov_desc *desc = &ltd->ltd_lov_desc;
106         int rc;
107         ENTRY;
108
109         LASSERT(d);
110         LASSERT(tgt);
111
112         info.os_enable_pre = 1;
113         rc = dt_statfs_info(env, tgt->ltd_tgt, &tgt->ltd_statfs, &info);
114         if (rc && rc != -ENOTCONN)
115                 CERROR("%s: statfs: rc = %d\n", lod2obd(d)->obd_name, rc);
116
117         if (!rc) {
118                 rc = lod_statfs_check(ltd, tgt);
119                 if (rc == -ENOSPC)
120                         return rc;
121         }
122
123         if (reserve &&
124             (reserve + (info.os_reserved_mb_low << 20) >
125              tgt->ltd_statfs.os_bavail * tgt->ltd_statfs.os_bsize))
126                 return -ENOSPC;
127
128         /* check whether device has changed state (active, inactive) */
129         if (rc != 0 && tgt->ltd_active) {
130                 /* turned inactive? */
131                 spin_lock(&d->lod_lock);
132                 if (tgt->ltd_active) {
133                         tgt->ltd_active = 0;
134                         if (rc == -ENOTCONN)
135                                 tgt->ltd_connecting = 1;
136
137                         LASSERT(desc->ld_active_tgt_count > 0);
138                         desc->ld_active_tgt_count--;
139                         set_bit(LQ_DIRTY, &ltd->ltd_qos.lq_flags);
140                         CDEBUG(D_CONFIG, "%s: turns inactive\n",
141                                tgt->ltd_exp->exp_obd->obd_name);
142                 }
143                 spin_unlock(&d->lod_lock);
144         } else if (rc == 0 && tgt->ltd_active == 0) {
145                 /* turned active? */
146                 LASSERTF(desc->ld_active_tgt_count < desc->ld_tgt_count,
147                          "active tgt count %d, tgt nr %d\n",
148                          desc->ld_active_tgt_count, desc->ld_tgt_count);
149                 spin_lock(&d->lod_lock);
150                 if (tgt->ltd_active == 0) {
151                         tgt->ltd_active = 1;
152                         tgt->ltd_connecting = 0;
153                         desc->ld_active_tgt_count++;
154                         set_bit(LQ_DIRTY, &ltd->ltd_qos.lq_flags);
155                         CDEBUG(D_CONFIG, "%s: turns active\n",
156                                tgt->ltd_exp->exp_obd->obd_name);
157                 }
158                 spin_unlock(&d->lod_lock);
159         }
160         if (rc == -ENOTCONN) {
161                 /* In case that the ENOTCONN for inactive OST state is
162                  * mistreated as MDT disconnection state by the client,
163                  * this error should be changed to someone else.
164                  */
165                 rc = -EREMOTEIO;
166         }
167
168         RETURN(rc);
169 }
170
171 static int lod_is_tgt_usable(struct lu_tgt_descs *ltd, struct lu_tgt_desc *tgt)
172 {
173         int rc;
174
175         rc = lod_statfs_check(ltd, tgt);
176         if (rc)
177                 return rc;
178
179         if (!tgt->ltd_active)
180                 return -ENOTCONN;
181
182         return 0;
183 }
184
185 /**
186  * Maintain per-target statfs data.
187  *
188  * The function refreshes statfs data for all the targets every N seconds.
189  * The actual N is controlled via procfs and set to LOV_DESC_QOS_MAXAGE_DEFAULT
190  * initially.
191  *
192  * \param[in] env       execution environment for this thread
193  * \param[in] lod       LOD device
194  * \param[in] ltd       tgt table
195  */
196 void lod_qos_statfs_update(const struct lu_env *env, struct lod_device *lod,
197                            struct lu_tgt_descs *ltd)
198 {
199         struct obd_device *obd = lod2obd(lod);
200         struct lu_tgt_desc *tgt;
201         time64_t max_age;
202         u64 avail;
203         ENTRY;
204
205         max_age = ktime_get_seconds() - 2 * ltd->ltd_lov_desc.ld_qos_maxage;
206
207         if (obd->obd_osfs_age > max_age)
208                 /* statfs data are quite recent, don't need to refresh it */
209                 RETURN_EXIT;
210
211         if (test_and_set_bit(LQ_SF_PROGRESS, &ltd->ltd_qos.lq_flags))
212                 RETURN_EXIT;
213
214         if (obd->obd_osfs_age > max_age) {
215                 /* statfs data are quite recent, don't need to refresh it */
216                 clear_bit(LQ_SF_PROGRESS, &ltd->ltd_qos.lq_flags);
217                 RETURN_EXIT;
218         }
219         lod_getref(ltd);
220         ltd_foreach_tgt(ltd, tgt) {
221                 avail = tgt->ltd_statfs.os_bavail;
222                 if (lod_statfs_and_check(env, lod, ltd, tgt, 0))
223                         continue;
224
225                 if (tgt->ltd_statfs.os_bavail != avail)
226                         /* recalculate weigths */
227                         set_bit(LQ_DIRTY, &ltd->ltd_qos.lq_flags);
228         }
229         lod_putref(lod, ltd);
230         obd->obd_osfs_age = ktime_get_seconds();
231
232         clear_bit(LQ_SF_PROGRESS, &ltd->ltd_qos.lq_flags);
233         EXIT;
234 }
235
236 #define LOV_QOS_EMPTY ((__u32)-1)
237
238 /**
239  * Calculate optimal round-robin order with regard to OSSes.
240  *
241  * Place all the OSTs from pool \a src_pool in a special array to be used for
242  * round-robin (RR) stripe allocation.  The placement algorithm interleaves
243  * OSTs from the different OSSs so that RR allocation can balance OSSs evenly.
244  * Resorts the targets when the number of active targets changes (because of
245  * a new target or activation/deactivation).
246  *
247  * \param[in] lod       LOD device
248  * \param[in] ltd       tgt table
249  * \param[in] src_pool  tgt pool
250  * \param[in] lqr       round-robin list
251  *
252  * \retval 0            on success
253  * \retval -ENOMEM      fails to allocate the array
254  */
255 static int lod_qos_calc_rr(struct lod_device *lod, struct lu_tgt_descs *ltd,
256                            const struct lu_tgt_pool *src_pool,
257                            struct lu_qos_rr *lqr)
258 {
259         struct lu_svr_qos  *svr;
260         struct lu_tgt_desc *tgt;
261         unsigned placed, real_count;
262         unsigned int i;
263         int rc;
264         ENTRY;
265
266         if (!test_bit(LQ_DIRTY, &lqr->lqr_flags)) {
267                 LASSERT(lqr->lqr_pool.op_size);
268                 RETURN(0);
269         }
270
271         /* Do actual allocation. */
272         down_write(&ltd->ltd_qos.lq_rw_sem);
273
274         /*
275          * Check again. While we were sleeping on @lq_rw_sem something could
276          * change.
277          */
278         if (!test_bit(LQ_DIRTY, &lqr->lqr_flags)) {
279                 LASSERT(lqr->lqr_pool.op_size);
280                 up_write(&ltd->ltd_qos.lq_rw_sem);
281                 RETURN(0);
282         }
283
284         real_count = src_pool->op_count;
285
286         /* Zero the pool array */
287         /* alloc_rr is holding a read lock on the pool, so nobody is adding/
288            deleting from the pool. The lq_rw_sem insures that nobody else
289            is reading. */
290         lqr->lqr_pool.op_count = real_count;
291         rc = lu_tgt_pool_extend(&lqr->lqr_pool, real_count);
292         if (rc) {
293                 up_write(&ltd->ltd_qos.lq_rw_sem);
294                 RETURN(rc);
295         }
296         for (i = 0; i < lqr->lqr_pool.op_count; i++)
297                 lqr->lqr_pool.op_array[i] = LOV_QOS_EMPTY;
298
299         /* Place all the tgts from 1 svr at the same time. */
300         placed = 0;
301         list_for_each_entry(svr, &ltd->ltd_qos.lq_svr_list, lsq_svr_list) {
302                 int j = 0;
303
304                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
305                         int next;
306
307                         if (!test_bit(src_pool->op_array[i],
308                                       ltd->ltd_tgt_bitmap))
309                                 continue;
310
311                         tgt = LTD_TGT(ltd, src_pool->op_array[i]);
312                         LASSERT(tgt && tgt->ltd_tgt);
313                         if (tgt->ltd_qos.ltq_svr != svr)
314                                 continue;
315
316                         /* Evenly space these tgts across arrayspace */
317                         next = j * lqr->lqr_pool.op_count / svr->lsq_tgt_count;
318                         while (lqr->lqr_pool.op_array[next] != LOV_QOS_EMPTY)
319                                 next = (next + 1) % lqr->lqr_pool.op_count;
320
321                         lqr->lqr_pool.op_array[next] = src_pool->op_array[i];
322                         j++;
323                         placed++;
324                 }
325         }
326
327         clear_bit(LQ_DIRTY, &lqr->lqr_flags);
328         up_write(&ltd->ltd_qos.lq_rw_sem);
329
330         if (placed != real_count) {
331                 /* This should never happen */
332                 LCONSOLE_ERROR_MSG(0x14e, "Failed to place all tgts in the "
333                                    "round-robin list (%d of %d).\n",
334                                    placed, real_count);
335                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
336                         LCONSOLE(D_WARNING, "rr #%d tgt idx=%d\n", i,
337                                  lqr->lqr_pool.op_array[i]);
338                 }
339                 set_bit(LQ_DIRTY, &lqr->lqr_flags);
340                 RETURN(-EAGAIN);
341         }
342
343 #if 0
344         for (i = 0; i < lqr->lqr_pool.op_count; i++)
345                 QOS_CONSOLE("rr #%d ost idx=%d\n", i, lqr->lqr_pool.op_array[i]);
346 #endif
347
348         RETURN(0);
349 }
350
351 /**
352  * Instantiate and declare creation of a new object.
353  *
354  * The function instantiates LU representation for a new object on the
355  * specified device. Also it declares an intention to create that
356  * object on the storage target.
357  *
358  * Note lu_object_anon() is used which is a trick with regard to LU/OSD
359  * infrastructure - in the existing precreation framework we can't assign FID
360  * at this moment, we do this later once a transaction is started. So the
361  * special method instantiates FID-less object in the cache and later it
362  * will get a FID and proper placement in LU cache.
363  *
364  * \param[in] env       execution environment for this thread
365  * \param[in] d         LOD device
366  * \param[in] ost_idx   OST target index where the object is being created
367  * \param[in] th        transaction handle
368  *
369  * \retval              object ptr on success, ERR_PTR() otherwise
370  */
371 static struct dt_object *lod_qos_declare_object_on(const struct lu_env *env,
372                                                    struct lod_device *d,
373                                                    __u32 ost_idx,
374                                                    bool can_block,
375                                                    struct thandle *th)
376 {
377         struct dt_allocation_hint *ah = &lod_env_info(env)->lti_ah;
378         struct lod_tgt_desc *ost;
379         struct lu_object *o, *n;
380         struct lu_device *nd;
381         struct dt_object *dt;
382         int               rc;
383         ENTRY;
384
385         LASSERT(d);
386         LASSERT(ost_idx < d->lod_ost_descs.ltd_tgts_size);
387         ost = OST_TGT(d,ost_idx);
388         LASSERT(ost);
389         LASSERT(ost->ltd_tgt);
390
391         nd = &ost->ltd_tgt->dd_lu_dev;
392
393         /*
394          * allocate anonymous object with zero fid, real fid
395          * will be assigned by OSP within transaction
396          * XXX: to be fixed with fully-functional OST fids
397          */
398         o = lu_object_anon(env, nd, NULL);
399         if (IS_ERR(o))
400                 GOTO(out, dt = ERR_CAST(o));
401
402         n = lu_object_locate(o->lo_header, nd->ld_type);
403         if (unlikely(n == NULL)) {
404                 CERROR("can't find slice\n");
405                 lu_object_put(env, o);
406                 GOTO(out, dt = ERR_PTR(-EINVAL));
407         }
408
409         dt = container_of(n, struct dt_object, do_lu);
410
411         ah->dah_can_block = can_block;
412         rc = lod_sub_declare_create(env, dt, NULL, ah, NULL, th);
413         if (rc < 0) {
414                 CDEBUG(D_OTHER, "can't declare creation on #%u: %d\n",
415                        ost_idx, rc);
416                 lu_object_put(env, o);
417                 dt = ERR_PTR(rc);
418         }
419
420 out:
421         RETURN(dt);
422 }
423
424 /**
425  * Calculate a minimum acceptable stripe count.
426  *
427  * Return an acceptable stripe count depending on flag LOV_USES_DEFAULT_STRIPE:
428  * all stripes or 3/4 of stripes.
429  *
430  * \param[in] stripe_count      number of stripes requested
431  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
432  *
433  * \retval                      acceptable stripecount
434  */
435 static int min_stripe_count(__u32 stripe_count, int flags)
436 {
437         return (flags & LOV_USES_DEFAULT_STRIPE ?
438                 stripe_count - (stripe_count / 4) : stripe_count);
439 }
440
441 #define LOV_CREATE_RESEED_MULT 30
442 #define LOV_CREATE_RESEED_MIN  2000
443
444 /**
445  * Initialize temporary tgt-in-use array.
446  *
447  * Allocate or extend the array used to mark targets already assigned to a new
448  * striping so they are not used more than once.
449  *
450  * \param[in] env       execution environment for this thread
451  * \param[in] stripes   number of items needed in the array
452  *
453  * \retval 0            on success
454  * \retval -ENOMEM      on error
455  */
456 static inline int lod_qos_tgt_in_use_clear(const struct lu_env *env,
457                                            __u32 stripes)
458 {
459         struct lod_thread_info *info = lod_env_info(env);
460
461         if (info->lti_ea_store_size < sizeof(int) * stripes)
462                 lod_ea_store_resize(info, stripes * sizeof(int));
463         if (info->lti_ea_store_size < sizeof(int) * stripes) {
464                 CERROR("can't allocate memory for tgt-in-use array\n");
465                 return -ENOMEM;
466         }
467         memset(info->lti_ea_store, -1, sizeof(int) * stripes);
468         return 0;
469 }
470
471 /**
472  * Remember a target in the array of used targets.
473  *
474  * Mark the given target as used for a new striping being created. The status
475  * of an tgt in a striping can be checked with lod_qos_is_tgt_used().
476  *
477  * \param[in] env       execution environment for this thread
478  * \param[in] idx       index in the array
479  * \param[in] tgt_idx   target index to mark as used
480  */
481 static inline void lod_qos_tgt_in_use(const struct lu_env *env,
482                                       int idx, int tgt_idx)
483 {
484         struct lod_thread_info *info = lod_env_info(env);
485         int *tgts = info->lti_ea_store;
486
487         LASSERT(info->lti_ea_store_size >= idx * sizeof(int));
488         tgts[idx] = tgt_idx;
489 }
490
491 /**
492  * Check is tgt used in a striping.
493  *
494  * Checks whether tgt with the given index is marked as used in the temporary
495  * array (see lod_qos_tgt_in_use()).
496  *
497  * \param[in] env       execution environment for this thread
498  * \param[in] tgt_idx   target index to check
499  * \param[in] stripes   the number of items used in the array already
500  *
501  * \retval 0            not used
502  * \retval 1            used
503  */
504 static int lod_qos_is_tgt_used(const struct lu_env *env, int tgt_idx,
505                                __u32 stripes)
506 {
507         struct lod_thread_info *info = lod_env_info(env);
508         int *tgts = info->lti_ea_store;
509         __u32 j;
510
511         for (j = 0; j < stripes; j++) {
512                 if (tgts[j] == tgt_idx)
513                         return 1;
514         }
515         return 0;
516 }
517
518 static inline bool
519 lod_obj_is_ost_use_skip_cb(const struct lu_env *env, struct lod_object *lo,
520                            int comp_idx, struct lod_obj_stripe_cb_data *data)
521 {
522         struct lod_layout_component *comp = &lo->ldo_comp_entries[comp_idx];
523
524         return comp->llc_ost_indices == NULL;
525 }
526
527 static inline int
528 lod_obj_is_ost_use_cb(const struct lu_env *env, struct lod_object *lo,
529                       int comp_idx, struct lod_obj_stripe_cb_data *data)
530 {
531         struct lod_layout_component *comp = &lo->ldo_comp_entries[comp_idx];
532         int i;
533
534         for (i = 0; i < comp->llc_stripe_count; i++) {
535                 if (comp->llc_ost_indices[i] == data->locd_ost_index) {
536                         data->locd_ost_index = -1;
537                         return -EEXIST;
538                 }
539         }
540
541         return 0;
542 }
543
544 /**
545  * Check is OST used in a composite layout
546  *
547  * \param[in] lo        lod object
548  * \param[in] ost       OST target index to check
549  *
550  * \retval false        not used
551  * \retval true         used
552  */
553 static inline bool lod_comp_is_ost_used(const struct lu_env *env,
554                                        struct lod_object *lo, int ost)
555 {
556         struct lod_obj_stripe_cb_data data = { { 0 } };
557
558         data.locd_ost_index = ost;
559         data.locd_comp_skip_cb = lod_obj_is_ost_use_skip_cb;
560         data.locd_comp_cb = lod_obj_is_ost_use_cb;
561
562         (void)lod_obj_for_each_stripe(env, lo, NULL, &data);
563
564         return data.locd_ost_index == -1;
565 }
566
567 static inline void lod_avoid_update(struct lod_object *lo,
568                                     struct lod_avoid_guide *lag)
569 {
570         if (!lod_is_flr(lo))
571                 return;
572
573         lag->lag_ost_avail--;
574 }
575
576 static inline bool lod_should_avoid_ost(struct lod_object *lo,
577                                         struct lod_avoid_guide *lag,
578                                         __u32 index)
579 {
580         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
581         struct lod_tgt_desc *ost = OST_TGT(lod, index);
582         struct lu_svr_qos *lsq = ost->ltd_qos.ltq_svr;
583         bool used = false;
584         int i;
585
586         if (!test_bit(index, lod->lod_ost_bitmap)) {
587                 QOS_DEBUG("OST%d: been used in conflicting mirror component\n",
588                           index);
589                 return true;
590         }
591
592         /**
593          * we've tried our best, all available OSTs have been used in
594          * overlapped components in the other mirror
595          */
596         if (lag->lag_ost_avail == 0)
597                 return false;
598
599         /* check OSS use */
600         for (i = 0; i < lag->lag_oaa_count; i++) {
601                 if (lag->lag_oss_avoid_array[i] == lsq->lsq_id) {
602                         used = true;
603                         break;
604                 }
605         }
606         /**
607          * if the OSS which OST[index] resides has not been used, we'd like to
608          * use it
609          */
610         if (!used)
611                 return false;
612
613         /* if the OSS has been used, check whether the OST has been used */
614         if (!test_bit(index, lag->lag_ost_avoid_bitmap))
615                 used = false;
616         else
617                 QOS_DEBUG("OST%d: been used in conflicting mirror component\n",
618                           index);
619         return used;
620 }
621
622 static int lod_check_and_reserve_ost(const struct lu_env *env,
623                                      struct lod_object *lo,
624                                      struct lod_layout_component *lod_comp,
625                                      __u32 ost_idx, __u32 speed, __u32 *s_idx,
626                                      struct dt_object **stripe,
627                                      __u32 *ost_indices,
628                                      struct thandle *th,
629                                      bool *overstriped,
630                                      __u64 reserve)
631 {
632         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
633         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
634         struct lu_tgt_desc *ost = OST_TGT(lod, ost_idx);
635         struct dt_object   *o;
636         __u32 stripe_idx = *s_idx;
637         int rc;
638
639         ENTRY;
640
641         rc = lod_statfs_and_check(env, lod, &lod->lod_ost_descs, ost, reserve);
642         if (rc)
643                 RETURN(rc);
644
645         /*
646          * We expect number of precreated objects in f_ffree at
647          * the first iteration, skip OSPs with no objects ready
648          */
649         if (ost->ltd_statfs.os_fprecreated == 0 && speed == 0) {
650                 QOS_DEBUG("#%d: precreation is empty\n", ost_idx);
651                 RETURN(rc);
652         }
653
654         /*
655          * try to use another OSP if this one is degraded
656          */
657         if (ost->ltd_statfs.os_state & OS_STATFS_DEGRADED && speed < 2) {
658                 QOS_DEBUG("#%d: degraded\n", ost_idx);
659                 RETURN(rc);
660         }
661
662         /*
663          * try not allocate on OST which has been used by other
664          * component
665          */
666         if (speed == 0 && lod_comp_is_ost_used(env, lo, ost_idx)) {
667                 QOS_DEBUG("iter %d: OST%d used by other component\n",
668                           speed, ost_idx);
669                 RETURN(rc);
670         }
671
672         /**
673          * try not allocate OSTs used by conflicting component of other mirrors
674          * for the first and second time.
675          */
676         if (speed < 2 && lod_should_avoid_ost(lo, lag, ost_idx)) {
677                 QOS_DEBUG("iter %d: OST%d used by conflicting mirror component\n",
678                           speed, ost_idx);
679                 RETURN(rc);
680         }
681
682         /* do not put >1 objects on a single OST, except for overstriping */
683         if (lod_qos_is_tgt_used(env, ost_idx, stripe_idx)) {
684                 if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
685                         *overstriped = true;
686                 else
687                         RETURN(rc);
688         }
689
690         o = lod_qos_declare_object_on(env, lod, ost_idx, (speed > 1), th);
691         if (IS_ERR(o)) {
692                 CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
693                        ost_idx, (int) PTR_ERR(o));
694                 rc = PTR_ERR(o);
695                 RETURN(rc);
696         }
697
698         /*
699          * We've successfully declared (reserved) an object
700          */
701         lod_avoid_update(lo, lag);
702         lod_qos_tgt_in_use(env, stripe_idx, ost_idx);
703         stripe[stripe_idx] = o;
704         ost_indices[stripe_idx] = ost_idx;
705         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_LOV_CREATE_RACE, 2);
706         stripe_idx++;
707         *s_idx = stripe_idx;
708
709         RETURN(rc);
710 }
711
712 /**
713  * Allocate a striping using round-robin algorithm.
714  *
715  * Allocates a new striping using round-robin algorithm. The function refreshes
716  * all the internal structures (statfs cache, array of available OSTs sorted
717  * with regard to OSS, etc). The number of stripes required is taken from the
718  * object (must be prepared by the caller), but can change if the flag
719  * LOV_USES_DEFAULT_STRIPE is supplied. The caller should ensure nobody else
720  * is trying to create a striping on the object in parallel. All the internal
721  * structures (like pools, etc) are protected and no additional locking is
722  * required. The function succeeds even if a single stripe is allocated. To save
723  * time we give priority to targets which already have objects precreated.
724  * Full OSTs are skipped (see lod_qos_dev_is_full() for the details).
725  *
726  * \param[in] env               execution environment for this thread
727  * \param[in] lo                LOD object
728  * \param[out] stripe           striping created
729  * \param[out] ost_indices      ost indices of striping created
730  * \param[in] flags             allocation flags (0 or LOV_USES_DEFAULT_STRIPE)
731  * \param[in] th                transaction handle
732  * \param[in] comp_idx          index of ldo_comp_entries
733  *
734  * \retval 0            on success
735  * \retval -ENOSPC      if not enough OSTs are found
736  * \retval negative     negated errno for other failures
737  */
738 static int lod_ost_alloc_rr(const struct lu_env *env, struct lod_object *lo,
739                             struct dt_object **stripe, __u32 *ost_indices,
740                             int flags, struct thandle *th, int comp_idx,
741                             __u64 reserve)
742 {
743         struct lod_layout_component *lod_comp;
744         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
745         struct pool_desc  *pool = NULL;
746         struct lu_tgt_pool *osts;
747         struct lu_qos_rr *lqr;
748         unsigned int i, array_idx;
749         __u32 stripe_idx = 0;
750         __u32 stripe_count, stripe_count_min, ost_idx;
751         int rc, speed = 0, ost_connecting = 0;
752         int stripes_per_ost = 1;
753         bool overstriped = false;
754         ENTRY;
755
756         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
757         lod_comp = &lo->ldo_comp_entries[comp_idx];
758         stripe_count = lod_comp->llc_stripe_count;
759         stripe_count_min = min_stripe_count(stripe_count, flags);
760
761         if (lod_comp->llc_pool != NULL)
762                 pool = lod_find_pool(m, lod_comp->llc_pool);
763
764         if (pool != NULL) {
765                 down_read(&pool_tgt_rw_sem(pool));
766                 osts = &(pool->pool_obds);
767                 lqr = &(pool->pool_rr);
768         } else {
769                 osts = &m->lod_ost_descs.ltd_tgt_pool;
770                 lqr = &(m->lod_ost_descs.ltd_qos.lq_rr);
771         }
772
773         rc = lod_qos_calc_rr(m, &m->lod_ost_descs, osts, lqr);
774         if (rc)
775                 GOTO(out, rc);
776
777         rc = lod_qos_tgt_in_use_clear(env, stripe_count);
778         if (rc)
779                 GOTO(out, rc);
780
781         down_read(&m->lod_ost_descs.ltd_qos.lq_rw_sem);
782         spin_lock(&lqr->lqr_alloc);
783         if (--lqr->lqr_start_count <= 0) {
784                 atomic_set(&lqr->lqr_start_idx,
785                             prandom_u32_max(osts->op_count));
786                 lqr->lqr_start_count =
787                         (LOV_CREATE_RESEED_MIN / max(osts->op_count, 1U) +
788                          LOV_CREATE_RESEED_MULT) * max(osts->op_count, 1U);
789         } else if (atomic_read(&lqr->lqr_start_idx) >= osts->op_count) {
790                 /* If we have allocated from all of the tgts, slowly
791                  * precess the next start OST if the tgt/stripe count
792                  * difference isn't already doing this for us.
793                  */
794                 atomic_sub(osts->op_count, &lqr->lqr_start_idx);
795                 if (stripe_count > 1 && (osts->op_count % stripe_count) != 1)
796                         ++lqr->lqr_offset_idx;
797         }
798         spin_unlock(&lqr->lqr_alloc);
799         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
800                 stripes_per_ost =
801                         (lod_comp->llc_stripe_count - 1) / osts->op_count + 1;
802
803 repeat_find:
804         QOS_DEBUG("pool '%s' want %d start_idx %d start_count %d offset %d "
805                   "active %d count %d\n",
806                   lod_comp->llc_pool ? lod_comp->llc_pool : "",
807                   stripe_count, atomic_read(&lqr->lqr_start_idx),
808                   lqr->lqr_start_count, lqr->lqr_offset_idx, osts->op_count,
809                   osts->op_count);
810
811         for (i = 0; i < osts->op_count * stripes_per_ost &&
812                     stripe_idx < stripe_count; i++) {
813                 int idx;
814
815                 idx = atomic_inc_return(&lqr->lqr_start_idx);
816                 array_idx = (idx + lqr->lqr_offset_idx) %
817                                 osts->op_count;
818                 ost_idx = lqr->lqr_pool.op_array[array_idx];
819
820                 QOS_DEBUG("#%d strt %d act %d strp %d ary %d idx %d\n",
821                           i, idx, /* XXX: active*/ 0,
822                           stripe_idx, array_idx, ost_idx);
823
824                 if ((ost_idx == LOV_QOS_EMPTY) ||
825                     !test_bit(ost_idx, m->lod_ost_bitmap))
826                         continue;
827
828                 /* Fail Check before osc_precreate() is called
829                    so we can only 'fail' single OSC. */
830                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
831                         continue;
832
833                 if (OBD_FAIL_PRECHECK(OBD_FAIL_MDS_LOD_CREATE_PAUSE)) {
834                         clear_bit(LQ_SAME_SPACE,
835                                   &m->lod_ost_descs.ltd_qos.lq_flags);
836                         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_LOD_CREATE_PAUSE,
837                                          cfs_fail_val);
838                 }
839                 rc = lod_check_and_reserve_ost(env, lo, lod_comp, ost_idx,
840                                                speed, &stripe_idx, stripe,
841                                                ost_indices, th, &overstriped,
842                                                reserve);
843
844                 if (rc != 0 && OST_TGT(m, ost_idx)->ltd_connecting)
845                         ost_connecting = 1;
846         }
847         if ((speed < 2) && (stripe_idx < stripe_count_min)) {
848                 /* Try again, allowing slower OSCs */
849                 speed++;
850
851                 ost_connecting = 0;
852                 goto repeat_find;
853         }
854         up_read(&m->lod_ost_descs.ltd_qos.lq_rw_sem);
855
856         /* If there are enough OSTs, a component with overstriping requested
857          * will not actually end up overstriped.  The comp should reflect this.
858          */
859         if (!overstriped)
860                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
861
862         if (stripe_idx) {
863                 lod_comp->llc_stripe_count = stripe_idx;
864                 /* at least one stripe is allocated */
865                 rc = 0;
866         } else {
867                 /* nobody provided us with a single object */
868                 if (ost_connecting)
869                         rc = -EINPROGRESS;
870                 else
871                         rc = -ENOSPC;
872         }
873
874 out:
875         if (pool != NULL) {
876                 up_read(&pool_tgt_rw_sem(pool));
877                 /* put back ref got by lod_find_pool() */
878                 lod_pool_putref(pool);
879         }
880
881         RETURN(rc);
882 }
883
884 static int
885 lod_qos_mdt_in_use_init(const struct lu_env *env,
886                         const struct lu_tgt_descs *ltd,
887                         u32 stripe_idx, u32 stripe_count,
888                         const struct lu_tgt_pool *pool,
889                         struct dt_object **stripes)
890 {
891         u32 mdt_idx;
892         struct lu_tgt_desc *mdt;
893         int i, j;
894         int rc;
895
896         rc = lod_qos_tgt_in_use_clear(env, stripe_count);
897         if (rc)
898                 return rc;
899
900         /* if stripe_idx > 1, we are splitting directory, mark existing stripes
901          * in_use. Because for either split or creation, stripe 0 is local,
902          * don't mark it in use.
903          */
904         for (i = 1; i < stripe_idx; i++) {
905                 LASSERT(stripes[i]);
906                 for (j = 0; j < pool->op_count; j++) {
907                         mdt_idx = pool->op_array[j];
908
909                         if (!test_bit(mdt_idx, ltd->ltd_tgt_bitmap))
910                                 continue;
911
912                         mdt = LTD_TGT(ltd, mdt_idx);
913                         if (&mdt->ltd_tgt->dd_lu_dev ==
914                             stripes[i]->do_lu.lo_dev)
915                                 lod_qos_tgt_in_use(env, i, mdt_idx);
916                 }
917         }
918
919         return 0;
920 }
921
922 /**
923  * Allocate a striping using round-robin algorithm.
924  *
925  * Allocates a new striping using round-robin algorithm. The function refreshes
926  * all the internal structures (statfs cache, array of available remote MDTs
927  * sorted with regard to MDS, etc). The number of stripes required is taken from
928  * the object (must be prepared by the caller). The caller should ensure nobody
929  * else is trying to create a striping on the object in parallel. All the
930  * internal structures (like pools, etc) are protected and no additional locking
931  * is required. The function succeeds even if a single stripe is allocated.
932  *
933  * \param[in] env               execution environment for this thread
934  * \param[in] lo                LOD object
935  * \param[out] stripes          striping created
936  *
937  * \retval positive     stripe objects allocated, including the first stripe
938  *                      allocated outside
939  * \retval -ENOSPC      if not enough MDTs are found
940  * \retval negative     negated errno for other failures
941  */
942 int lod_mdt_alloc_rr(const struct lu_env *env, struct lod_object *lo,
943                      struct dt_object **stripes, u32 stripe_idx,
944                      u32 stripe_count)
945 {
946         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
947         struct lu_tgt_descs *ltd = &lod->lod_mdt_descs;
948         struct lu_tgt_pool *pool;
949         struct lu_qos_rr *lqr;
950         struct lu_tgt_desc *mdt;
951         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
952         struct lu_fid fid = { 0 };
953         struct dt_object *dto;
954         unsigned int pool_idx;
955         unsigned int i;
956         u32 saved_idx = stripe_idx;
957         u32 mdt_idx;
958         bool use_degraded = false;
959         int tgt_connecting = 0;
960         int rc;
961
962         ENTRY;
963
964         pool = &ltd->ltd_tgt_pool;
965         lqr = &ltd->ltd_qos.lq_rr;
966         rc = lod_qos_calc_rr(lod, ltd, pool, lqr);
967         if (rc)
968                 RETURN(rc);
969
970         rc = lod_qos_mdt_in_use_init(env, ltd, stripe_idx, stripe_count, pool,
971                                      stripes);
972         if (rc)
973                 RETURN(rc);
974
975         down_read(&ltd->ltd_qos.lq_rw_sem);
976         spin_lock(&lqr->lqr_alloc);
977         if (--lqr->lqr_start_count <= 0) {
978                 atomic_set(&lqr->lqr_start_idx,
979                             prandom_u32_max(pool->op_count));
980                 lqr->lqr_start_count =
981                         (LOV_CREATE_RESEED_MIN / max(pool->op_count, 1U) +
982                          LOV_CREATE_RESEED_MULT) * max(pool->op_count, 1U);
983         } else if (atomic_read(&lqr->lqr_start_idx) >= pool->op_count) {
984                 /* If we have allocated from all of the tgts, slowly
985                  * precess the next start if the tgt/stripe count isn't
986                  * already doing this for us. */
987                 atomic_sub(pool->op_count, &lqr->lqr_start_idx);
988                 if (stripe_count - 1 > 1 &&
989                     (pool->op_count % (stripe_count - 1)) != 1)
990                         ++lqr->lqr_offset_idx;
991         }
992         spin_unlock(&lqr->lqr_alloc);
993
994 repeat_find:
995         QOS_DEBUG("want=%d start_idx=%d start_count=%d offset=%d active=%d count=%d\n",
996                   stripe_count - 1, atomic_read(&lqr->lqr_start_idx),
997                   lqr->lqr_start_count, lqr->lqr_offset_idx, pool->op_count,
998                   pool->op_count);
999
1000         for (i = 0; i < pool->op_count && stripe_idx < stripe_count; i++) {
1001                 int idx;
1002
1003                 idx = atomic_inc_return(&lqr->lqr_start_idx);
1004                 pool_idx = (idx + lqr->lqr_offset_idx) %
1005                             pool->op_count;
1006                 mdt_idx = lqr->lqr_pool.op_array[pool_idx];
1007                 mdt = LTD_TGT(ltd, mdt_idx);
1008
1009                 QOS_DEBUG("#%d strt %d act %d strp %d ary %d idx %d\n",
1010                           i, idx, /* XXX: active*/ 0,
1011                           stripe_idx, pool_idx, mdt_idx);
1012
1013                 if (mdt_idx == LOV_QOS_EMPTY ||
1014                     !test_bit(mdt_idx, ltd->ltd_tgt_bitmap))
1015                         continue;
1016
1017                 /* do not put >1 objects on one MDT */
1018                 if (lod_qos_is_tgt_used(env, mdt_idx, stripe_idx))
1019                         continue;
1020
1021                 rc = lod_is_tgt_usable(ltd, mdt);
1022                 if (rc) {
1023                         if (mdt->ltd_connecting)
1024                                 tgt_connecting = 1;
1025                         continue;
1026                 }
1027
1028                 /* try to use another OSP if this one is degraded */
1029                 if (mdt->ltd_statfs.os_state & OS_STATFS_DEGRADED &&
1030                     !use_degraded) {
1031                         QOS_DEBUG("#%d: degraded\n", mdt_idx);
1032                         continue;
1033                 }
1034
1035                 rc = dt_fid_alloc(env, mdt->ltd_tgt, &fid, NULL, NULL);
1036                 if (rc < 0) {
1037                         QOS_DEBUG("#%d: alloc FID failed: %dl\n", mdt_idx, rc);
1038                         continue;
1039                 }
1040
1041                 dto = dt_locate_at(env, mdt->ltd_tgt, &fid,
1042                                 lo->ldo_obj.do_lu.lo_dev->ld_site->ls_top_dev,
1043                                 &conf);
1044
1045                 if (IS_ERR(dto)) {
1046                         QOS_DEBUG("can't alloc stripe on #%u: %d\n",
1047                                   mdt->ltd_index, (int) PTR_ERR(dto));
1048
1049                         if (mdt->ltd_connecting)
1050                                 tgt_connecting = 1;
1051                         continue;
1052                 }
1053
1054                 lod_qos_tgt_in_use(env, stripe_idx, mdt_idx);
1055                 stripes[stripe_idx++] = dto;
1056         }
1057
1058         if (!use_degraded && stripe_idx < stripe_count) {
1059                 /* Try again, allowing slower MDTs */
1060                 use_degraded = true;
1061
1062                 tgt_connecting = 0;
1063                 goto repeat_find;
1064         }
1065         up_read(&ltd->ltd_qos.lq_rw_sem);
1066
1067         if (stripe_idx > saved_idx)
1068                 /* at least one stripe is allocated */
1069                 RETURN(stripe_idx);
1070
1071         /* nobody provided us with a single object */
1072         if (tgt_connecting)
1073                 RETURN(-EINPROGRESS);
1074
1075         RETURN(-ENOSPC);
1076 }
1077
1078 /**
1079  * Allocate a specific striping layout on a user defined set of OSTs.
1080  *
1081  * Allocates new striping using the OST index range provided by the data from
1082  * the lmm_obejcts contained in the lov_user_md passed to this method. Full
1083  * OSTs are not considered. The exact order of OSTs requested by the user
1084  * is respected as much as possible depending on OST status. The number of
1085  * stripes needed and stripe offset are taken from the object. If that number
1086  * can not be met, then the function returns a failure and then it's the
1087  * caller's responsibility to release the stripes allocated. All the internal
1088  * structures are protected, but no concurrent allocation is allowed on the
1089  * same objects.
1090  *
1091  * \param[in] env               execution environment for this thread
1092  * \param[in] lo                LOD object
1093  * \param[out] stripe           striping created
1094  * \param[out] ost_indices      ost indices of striping created
1095  * \param[in] th                transaction handle
1096  * \param[in] comp_idx          index of ldo_comp_entries
1097  *
1098  * \retval 0            on success
1099  * \retval -ENODEV      OST index does not exist on file system
1100  * \retval -EINVAL      requested OST index is invalid
1101  * \retval negative     negated errno on error
1102  */
1103 static int lod_alloc_ost_list(const struct lu_env *env, struct lod_object *lo,
1104                               struct dt_object **stripe, __u32 *ost_indices,
1105                               struct thandle *th, int comp_idx, __u64 reserve)
1106 {
1107         struct lod_layout_component *lod_comp;
1108         struct lod_device       *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1109         struct dt_object        *o;
1110         unsigned int            array_idx = 0;
1111         int                     stripe_count = 0;
1112         int                     i;
1113         int                     rc = -EINVAL;
1114         ENTRY;
1115
1116         /* for specific OSTs layout */
1117         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1118         lod_comp = &lo->ldo_comp_entries[comp_idx];
1119         LASSERT(lod_comp->llc_ostlist.op_array);
1120         LASSERT(lod_comp->llc_ostlist.op_count);
1121
1122         rc = lod_qos_tgt_in_use_clear(env, lod_comp->llc_stripe_count);
1123         if (rc < 0)
1124                 RETURN(rc);
1125
1126         if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT)
1127                 lod_comp->llc_stripe_offset =
1128                                 lod_comp->llc_ostlist.op_array[0];
1129
1130         for (i = 0; i < lod_comp->llc_stripe_count; i++) {
1131                 if (lod_comp->llc_ostlist.op_array[i] ==
1132                     lod_comp->llc_stripe_offset) {
1133                         array_idx = i;
1134                         break;
1135                 }
1136         }
1137         if (i == lod_comp->llc_stripe_count) {
1138                 CDEBUG(D_OTHER,
1139                        "%s: start index %d not in the specified list of OSTs\n",
1140                        lod2obd(m)->obd_name, lod_comp->llc_stripe_offset);
1141                 RETURN(-EINVAL);
1142         }
1143
1144         for (i = 0; i < lod_comp->llc_stripe_count;
1145              i++, array_idx = (array_idx + 1) % lod_comp->llc_stripe_count) {
1146                 __u32 ost_idx = lod_comp->llc_ostlist.op_array[array_idx];
1147
1148                 if (!test_bit(ost_idx, m->lod_ost_bitmap)) {
1149                         rc = -EINVAL;
1150                         break;
1151                 }
1152
1153                 /* do not put >1 objects on a single OST, except for
1154                  * overstriping
1155                  */
1156                 if (lod_qos_is_tgt_used(env, ost_idx, stripe_count) &&
1157                     !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)) {
1158                         rc = -EINVAL;
1159                         break;
1160                 }
1161
1162                 rc = lod_statfs_and_check(env, m, &m->lod_ost_descs,
1163                                           LTD_TGT(&m->lod_ost_descs, ost_idx),
1164                                           reserve);
1165                 if (rc < 0) /* this OSP doesn't feel well */
1166                         break;
1167
1168                 o = lod_qos_declare_object_on(env, m, ost_idx, true, th);
1169                 if (IS_ERR(o)) {
1170                         rc = PTR_ERR(o);
1171                         CDEBUG(D_OTHER,
1172                                "%s: can't declare new object on #%u: %d\n",
1173                                lod2obd(m)->obd_name, ost_idx, rc);
1174                         break;
1175                 }
1176
1177                 /*
1178                  * We've successfully declared (reserved) an object
1179                  */
1180                 lod_qos_tgt_in_use(env, stripe_count, ost_idx);
1181                 stripe[stripe_count] = o;
1182                 ost_indices[stripe_count] = ost_idx;
1183                 stripe_count++;
1184         }
1185
1186         RETURN(rc);
1187 }
1188
1189 /**
1190  * Allocate a striping on a predefined set of OSTs.
1191  *
1192  * Allocates new layout starting from OST index in lo->ldo_stripe_offset.
1193  * Full OSTs are not considered. The exact order of OSTs is not important and
1194  * varies depending on OST status. The allocation procedure prefers the targets
1195  * with precreated objects ready. The number of stripes needed and stripe
1196  * offset are taken from the object. If that number cannot be met, then the
1197  * function returns an error and then it's the caller's responsibility to
1198  * release the stripes allocated. All the internal structures are protected,
1199  * but no concurrent allocation is allowed on the same objects.
1200  *
1201  * \param[in] env               execution environment for this thread
1202  * \param[in] lo                LOD object
1203  * \param[out] stripe           striping created
1204  * \param[out] ost_indices      ost indices of striping created
1205  * \param[in] flags             not used
1206  * \param[in] th                transaction handle
1207  * \param[in] comp_idx          index of ldo_comp_entries
1208  *
1209  * \retval 0            on success
1210  * \retval -ENOSPC      if no OST objects are available at all
1211  * \retval -EFBIG       if not enough OST objects are found
1212  * \retval -EINVAL      requested offset is invalid
1213  * \retval negative     errno on failure
1214  */
1215 static int lod_ost_alloc_specific(const struct lu_env *env,
1216                                   struct lod_object *lo,
1217                                   struct dt_object **stripe, __u32 *ost_indices,
1218                                   int flags, struct thandle *th, int comp_idx,
1219                                   __u64 reserve)
1220 {
1221         struct lod_layout_component *lod_comp;
1222         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1223         struct dt_object *o;
1224         struct lu_tgt_desc *tgt;
1225         __u32 ost_idx;
1226         unsigned int i, array_idx, ost_count;
1227         int rc, stripe_num = 0;
1228         int speed = 0;
1229         struct pool_desc *pool = NULL;
1230         struct lu_tgt_pool *osts;
1231         int stripes_per_ost = 1;
1232         bool overstriped = false;
1233         ENTRY;
1234
1235         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1236         lod_comp = &lo->ldo_comp_entries[comp_idx];
1237
1238         rc = lod_qos_tgt_in_use_clear(env, lod_comp->llc_stripe_count);
1239         if (rc)
1240                 GOTO(out, rc);
1241
1242         if (lod_comp->llc_pool != NULL)
1243                 pool = lod_find_pool(m, lod_comp->llc_pool);
1244
1245         if (pool != NULL) {
1246                 down_read(&pool_tgt_rw_sem(pool));
1247                 osts = &(pool->pool_obds);
1248         } else {
1249                 osts = &m->lod_ost_descs.ltd_tgt_pool;
1250         }
1251
1252         ost_count = osts->op_count;
1253
1254 repeat_find:
1255         /* search loi_ost_idx in ost array */
1256         array_idx = 0;
1257         for (i = 0; i < ost_count; i++) {
1258                 if (osts->op_array[i] == lod_comp->llc_stripe_offset) {
1259                         array_idx = i;
1260                         break;
1261                 }
1262         }
1263         if (i == ost_count) {
1264                 CERROR("Start index %d not found in pool '%s'\n",
1265                        lod_comp->llc_stripe_offset,
1266                        lod_comp->llc_pool ? lod_comp->llc_pool : "");
1267                 GOTO(out, rc = -EINVAL);
1268         }
1269
1270         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1271                 stripes_per_ost =
1272                         (lod_comp->llc_stripe_count - 1)/ost_count + 1;
1273
1274         /* user specifies bigger stripe count than available ost count */
1275         if (lod_comp->llc_stripe_count > ost_count * stripes_per_ost)
1276                 lod_comp->llc_stripe_count = ost_count * stripes_per_ost;
1277
1278         for (i = 0; i < ost_count * stripes_per_ost;
1279                         i++, array_idx = (array_idx + 1) % ost_count) {
1280                 ost_idx = osts->op_array[array_idx];
1281
1282                 if (!test_bit(ost_idx, m->lod_ost_bitmap))
1283                         continue;
1284
1285                 /* Fail Check before osc_precreate() is called
1286                    so we can only 'fail' single OSC. */
1287                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
1288                         continue;
1289
1290                 /*
1291                  * do not put >1 objects on a single OST, except for
1292                  * overstriping, where it is intended
1293                  */
1294                 if (lod_qos_is_tgt_used(env, ost_idx, stripe_num)) {
1295                         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1296                                 overstriped = true;
1297                         else
1298                                 continue;
1299                 }
1300
1301                 /*
1302                  * try not allocate on the OST used by other component
1303                  */
1304                 if (speed == 0 && i != 0 &&
1305                     lod_comp_is_ost_used(env, lo, ost_idx))
1306                         continue;
1307
1308                 tgt = LTD_TGT(&m->lod_ost_descs, ost_idx);
1309
1310                 /* Drop slow OSCs if we can, but not for requested start idx.
1311                  *
1312                  * This means "if OSC is slow and it is not the requested
1313                  * start OST, then it can be skipped, otherwise skip it only
1314                  * if it is inactive/recovering/out-of-space." */
1315
1316                 rc = lod_statfs_and_check(env, m, &m->lod_ost_descs,
1317                                           tgt, reserve);
1318                 if (rc) {
1319                         /* this OSP doesn't feel well */
1320                         continue;
1321                 }
1322
1323                 /*
1324                  * We expect number of precreated objects at the first
1325                  * iteration.  Skip OSPs with no objects ready.  Don't apply
1326                  * this logic to OST specified with stripe_offset.
1327                  */
1328                 if (i && !tgt->ltd_statfs.os_fprecreated && !speed)
1329                         continue;
1330
1331                 o = lod_qos_declare_object_on(env, m, ost_idx, true, th);
1332                 if (IS_ERR(o)) {
1333                         CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
1334                                ost_idx, (int) PTR_ERR(o));
1335                         continue;
1336                 }
1337
1338                 /*
1339                  * We've successfully declared (reserved) an object
1340                  */
1341                 lod_qos_tgt_in_use(env, stripe_num, ost_idx);
1342                 stripe[stripe_num] = o;
1343                 ost_indices[stripe_num] = ost_idx;
1344                 stripe_num++;
1345
1346                 /* We have enough stripes */
1347                 if (stripe_num == lod_comp->llc_stripe_count)
1348                         GOTO(out, rc = 0);
1349         }
1350         if (speed < 2) {
1351                 /* Try again, allowing slower OSCs */
1352                 speed++;
1353                 goto repeat_find;
1354         }
1355
1356         /* If we were passed specific striping params, then a failure to
1357          * meet those requirements is an error, since we can't reallocate
1358          * that memory (it might be part of a larger array or something).
1359          */
1360         CERROR("can't lstripe objid "DFID": have %d want %u\n",
1361                PFID(lu_object_fid(lod2lu_obj(lo))), stripe_num,
1362                lod_comp->llc_stripe_count);
1363         rc = stripe_num == 0 ? -ENOSPC : -EFBIG;
1364
1365         /* If there are enough OSTs, a component with overstriping requessted
1366          * will not actually end up overstriped.  The comp should reflect this.
1367          */
1368         if (rc == 0 && !overstriped)
1369                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
1370
1371 out:
1372         if (pool != NULL) {
1373                 up_read(&pool_tgt_rw_sem(pool));
1374                 /* put back ref got by lod_find_pool() */
1375                 lod_pool_putref(pool);
1376         }
1377
1378         RETURN(rc);
1379 }
1380
1381 #ifdef HAVE_DOWN_WRITE_KILLABLE
1382 struct semaphore_timer {
1383         struct timer_list timer;
1384         struct task_struct *task;
1385 };
1386
1387 static void process_semaphore_timer(struct timer_list *t)
1388 {
1389         struct semaphore_timer *timeout = cfs_from_timer(timeout, t, timer);
1390
1391         send_sig(SIGKILL, timeout->task, 1);
1392 }
1393 #endif
1394
1395 /**
1396  * Calculate penalties per-ost in a pool
1397  *
1398  * The algorithm is similar to ltd_qos_penalties_calc(), but much simpler,
1399  * just considering the space of each OST in this pool.
1400  *
1401  * \param[in] lod       lod_device
1402  * \param[in] pool      pool_desc
1403  *
1404  * \retval 0            on success
1405  * \retval -EAGAIN      the number of OSTs isn't enough or all tgt spaces are
1406  *                      almost the same
1407  */
1408 static int lod_pool_qos_penalties_calc(struct lod_device *lod,
1409                                        struct pool_desc *pool)
1410 {
1411         struct lu_tgt_descs *ltd = &lod->lod_ost_descs;
1412         struct lu_qos *qos = &ltd->ltd_qos;
1413         struct lov_desc *desc = &ltd->ltd_lov_desc;
1414         struct lu_tgt_pool *osts = &pool->pool_obds;
1415         struct lod_tgt_desc *ost;
1416         __u64 ba_max, ba_min, ba;
1417         __u32 num_active;
1418         int prio_wide;
1419         time64_t now, age;
1420         int i, rc;
1421
1422         ENTRY;
1423
1424         now = ktime_get_real_seconds();
1425
1426         if (pool->pool_same_space && now < pool->pool_same_space_expire)
1427                 GOTO(out, rc = 0);
1428
1429         num_active = osts->op_count - 1;
1430         if (num_active < 1)
1431                 GOTO(out, rc = -EAGAIN);
1432
1433         prio_wide = 256 - qos->lq_prio_free;
1434
1435         ba_min = (__u64)(-1);
1436         ba_max = 0;
1437
1438         /* Calculate penalty per OST */
1439         for (i = 0; i < osts->op_count; i++) {
1440                 if (!test_bit(osts->op_array[i], lod->lod_ost_bitmap))
1441                         continue;
1442
1443                 ost = OST_TGT(lod, osts->op_array[i]);
1444                 if (!ost->ltd_active)
1445                         continue;
1446
1447                 ba = tgt_statfs_bavail(ost) >> 8;
1448                 if (!ba)
1449                         continue;
1450
1451                 ba_min = min(ba, ba_min);
1452                 ba_max = max(ba, ba_max);
1453                 ost->ltd_qos.ltq_svr->lsq_bavail += ba;
1454
1455                 /*
1456                  * per-ost penalty is
1457                  * prio * bavail / (num_tgt - 1) / prio_max / 2
1458                  */
1459                 ost->ltd_qos.ltq_penalty_per_obj = prio_wide * ba >> 9;
1460                 do_div(ost->ltd_qos.ltq_penalty_per_obj, num_active);
1461
1462                 age = (now - ost->ltd_qos.ltq_used) >> 3;
1463                 if (age > 32 * desc->ld_qos_maxage)
1464                         ost->ltd_qos.ltq_penalty = 0;
1465                 else if (age > desc->ld_qos_maxage)
1466                         /* Decay ost penalty. */
1467                         ost->ltd_qos.ltq_penalty >>= age / desc->ld_qos_maxage;
1468         }
1469
1470         /*
1471          * If each ost has almost same free space, do rr allocation for better
1472          * creation performance
1473          */
1474         if ((ba_max * (256 - qos->lq_threshold_rr)) >> 8 < ba_min) {
1475                 pool->pool_same_space = true;
1476                 pool->pool_same_space_expire = now + desc->ld_qos_maxage;
1477         } else {
1478                 pool->pool_same_space = false;
1479         }
1480         rc = 0;
1481
1482 out:
1483         if (!rc && pool->pool_same_space)
1484                 rc = -EAGAIN;
1485
1486         RETURN(rc);
1487 }
1488
1489 /**
1490  * Allocate a striping using an algorithm with weights.
1491  *
1492  * The function allocates OST objects to create a striping. The algorithm
1493  * used is based on weights (currently only using the free space), and it's
1494  * trying to ensure the space is used evenly by OSTs and OSSs. The striping
1495  * configuration (# of stripes, offset, pool) is taken from the object and
1496  * is prepared by the caller.
1497  *
1498  * If LOV_USES_DEFAULT_STRIPE is not passed and prepared configuration can't
1499  * be met due to too few OSTs, then allocation fails. If the flag is passed
1500  * fewer than 3/4 of the requested number of stripes can be allocated, then
1501  * allocation fails.
1502  *
1503  * No concurrent allocation is allowed on the object and this must be ensured
1504  * by the caller. All the internal structures are protected by the function.
1505  *
1506  * The algorithm has two steps: find available OSTs and calculate their
1507  * weights, then select the OSTs with their weights used as the probability.
1508  * An OST with a higher weight is proportionately more likely to be selected
1509  * than one with a lower weight.
1510  *
1511  * \param[in] env               execution environment for this thread
1512  * \param[in] lo                LOD object
1513  * \param[out] stripe           striping created
1514  * \param[out] ost_indices      ost indices of striping created
1515  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
1516  * \param[in] th                transaction handle
1517  * \param[in] comp_idx          index of ldo_comp_entries
1518  *
1519  * \retval 0            on success
1520  * \retval -EAGAIN      not enough OSTs are found for specified stripe count
1521  * \retval -EINVAL      requested OST index is invalid
1522  * \retval negative     errno on failure
1523  */
1524 static int lod_ost_alloc_qos(const struct lu_env *env, struct lod_object *lo,
1525                              struct dt_object **stripe, __u32 *ost_indices,
1526                              int flags, struct thandle *th, int comp_idx,
1527                              __u64 reserve)
1528 {
1529         struct lod_layout_component *lod_comp;
1530         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1531         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
1532         struct lod_tgt_desc *ost;
1533         struct dt_object *o;
1534         __u64 total_weight = 0;
1535         struct pool_desc *pool = NULL;
1536         struct lu_tgt_pool *osts;
1537         unsigned int i;
1538         __u32 nfound, good_osts, stripe_count, stripe_count_min;
1539         bool overstriped = false;
1540         int stripes_per_ost = 1;
1541         bool slow = false;
1542         int rc = 0;
1543         ENTRY;
1544
1545         /* Totally skip qos part when qos_threshold_rr=100% */
1546         if (lod->lod_ost_descs.ltd_qos.lq_threshold_rr == QOS_THRESHOLD_MAX)
1547                 return -EAGAIN;
1548
1549         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1550         lod_comp = &lo->ldo_comp_entries[comp_idx];
1551         stripe_count = lod_comp->llc_stripe_count;
1552         stripe_count_min = min_stripe_count(stripe_count, flags);
1553         if (stripe_count_min < 1)
1554                 RETURN(-EINVAL);
1555
1556         if (lod_comp->llc_pool != NULL)
1557                 pool = lod_find_pool(lod, lod_comp->llc_pool);
1558
1559         if (pool != NULL) {
1560                 down_read(&pool_tgt_rw_sem(pool));
1561                 osts = &(pool->pool_obds);
1562         } else {
1563                 osts = &lod->lod_ost_descs.ltd_tgt_pool;
1564         }
1565
1566         /* Detect -EAGAIN early, before expensive lock is taken. */
1567         if (!ltd_qos_is_usable(&lod->lod_ost_descs))
1568                 GOTO(out_nolock, rc = -EAGAIN);
1569
1570         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1571                 stripes_per_ost =
1572                         (lod_comp->llc_stripe_count - 1)/osts->op_count + 1;
1573
1574 #ifdef HAVE_DOWN_WRITE_KILLABLE
1575         if (!down_write_trylock(&lod->lod_ost_descs.ltd_qos.lq_rw_sem)) {
1576                 struct semaphore_timer timer;
1577
1578                 kernel_sigaction(SIGKILL, SIG_DFL);
1579                 timer.task = current;
1580                 cfs_timer_setup(&timer.timer, process_semaphore_timer, 0, 0);
1581                 mod_timer(&timer.timer, jiffies + cfs_time_seconds(2));
1582                 /* Do actual allocation, use write lock here. */
1583                 rc = down_write_killable(&lod->lod_ost_descs.ltd_qos.lq_rw_sem);
1584
1585                 timer_delete_sync(&timer.timer);
1586                 kernel_sigaction(SIGKILL, SIG_IGN);
1587                 if (rc) {
1588                         flush_signals(current);
1589                         QOS_DEBUG("%s: wakeup semaphore on timeout rc = %d\n",
1590                                   lod2obd(lod)->obd_name, rc);
1591                         GOTO(out_nolock, rc = -EAGAIN);
1592                 }
1593         }
1594 #else
1595         /* Do actual allocation, use write lock here. */
1596         down_write(&lod->lod_ost_descs.ltd_qos.lq_rw_sem);
1597 #endif
1598         /*
1599          * Check again, while we were sleeping on @lq_rw_sem things could
1600          * change.
1601          */
1602         if (!ltd_qos_is_usable(&lod->lod_ost_descs))
1603                 GOTO(out, rc = -EAGAIN);
1604
1605         if (pool != NULL)
1606                 rc = lod_pool_qos_penalties_calc(lod, pool);
1607         else
1608                 rc = ltd_qos_penalties_calc(&lod->lod_ost_descs);
1609         if (rc)
1610                 GOTO(out, rc);
1611
1612         rc = lod_qos_tgt_in_use_clear(env, lod_comp->llc_stripe_count);
1613         if (rc)
1614                 GOTO(out, rc);
1615
1616         good_osts = 0;
1617         /* Find all the OSTs that are valid stripe candidates */
1618         for (i = 0; i < osts->op_count; i++) {
1619                 if (!test_bit(osts->op_array[i], lod->lod_ost_bitmap))
1620                         continue;
1621
1622                 ost = OST_TGT(lod, osts->op_array[i]);
1623                 ost->ltd_qos.ltq_usable = 0;
1624
1625                 rc = lod_statfs_and_check(env, lod, &lod->lod_ost_descs,
1626                                           ost, reserve);
1627                 if (rc) {
1628                         /* this OSP doesn't feel well */
1629                         continue;
1630                 }
1631
1632                 if (ost->ltd_statfs.os_state & OS_STATFS_DEGRADED)
1633                         continue;
1634
1635                 /* Fail Check before osc_precreate() is called
1636                  * so we can only 'fail' single OSC.
1637                  */
1638                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) &&
1639                                    osts->op_array[i] == 0)
1640                         continue;
1641
1642                 ost->ltd_qos.ltq_usable = 1;
1643                 lu_tgt_qos_weight_calc(ost, false);
1644                 total_weight += ost->ltd_qos.ltq_weight;
1645
1646                 good_osts++;
1647         }
1648
1649         QOS_DEBUG("found %d good osts\n", good_osts);
1650
1651         if (good_osts < stripe_count_min)
1652                 GOTO(out, rc = -EAGAIN);
1653
1654         /* If we do not have enough OSTs for the requested stripe count, do not
1655          * put more stripes per OST than requested.
1656          */
1657         if (stripe_count / stripes_per_ost > good_osts)
1658                 stripe_count = good_osts * stripes_per_ost;
1659
1660         /* Find enough OSTs with weighted random allocation. */
1661         nfound = 0;
1662         while (nfound < stripe_count) {
1663                 u64 rand, cur_weight;
1664
1665                 cur_weight = 0;
1666                 rc = -ENOSPC;
1667
1668                 rand = lu_prandom_u64_max(total_weight);
1669
1670                 /* On average, this will hit larger-weighted OSTs more often.
1671                  * 0-weight OSTs will always get used last (only when rand=0)
1672                  */
1673                 for (i = 0; i < osts->op_count; i++) {
1674                         __u32 idx = osts->op_array[i];
1675                         struct lod_tgt_desc *ost;
1676
1677                         if (lod_should_avoid_ost(lo, lag, idx))
1678                                 continue;
1679
1680                         ost = OST_TGT(lod, idx);
1681
1682                         if (!ost->ltd_qos.ltq_usable)
1683                                 continue;
1684
1685                         cur_weight += ost->ltd_qos.ltq_weight;
1686                         QOS_DEBUG("stripe_count=%d nfound=%d cur_weight=%llu "
1687                                   "rand=%llu total_weight=%llu\n",
1688                                   stripe_count, nfound, cur_weight, rand,
1689                                   total_weight);
1690
1691                         if (cur_weight < rand)
1692                                 continue;
1693
1694                         QOS_DEBUG("stripe=%d to idx=%d\n", nfound, idx);
1695                         /*
1696                          * do not put >1 objects on a single OST, except for
1697                          * overstriping
1698                          */
1699                         if ((lod_comp_is_ost_used(env, lo, idx)) &&
1700                             !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING))
1701                                 continue;
1702
1703                         if (lod_qos_is_tgt_used(env, idx, nfound)) {
1704                                 if (lod_comp->llc_pattern &
1705                                     LOV_PATTERN_OVERSTRIPING)
1706                                         overstriped = true;
1707                                 else
1708                                         continue;
1709                         }
1710
1711                         o = lod_qos_declare_object_on(env, lod, idx, slow, th);
1712                         if (IS_ERR(o)) {
1713                                 QOS_DEBUG("can't declare object on #%u: %d\n",
1714                                           idx, (int) PTR_ERR(o));
1715                                 continue;
1716                         }
1717
1718                         lod_avoid_update(lo, lag);
1719                         lod_qos_tgt_in_use(env, nfound, idx);
1720                         stripe[nfound] = o;
1721                         ost_indices[nfound] = idx;
1722                         ltd_qos_update(&lod->lod_ost_descs, ost, &total_weight);
1723                         nfound++;
1724                         rc = 0;
1725                         break;
1726                 }
1727
1728                 if (rc && !slow && nfound < stripe_count) {
1729                         /* couldn't allocate using precreated objects
1730                          * so try to wait for new precreations */
1731                         slow = true;
1732                         rc = 0;
1733                 }
1734
1735                 if (rc) {
1736                         /* no OST found on this iteration, give up */
1737                         break;
1738                 }
1739         }
1740
1741         if (unlikely(nfound != stripe_count)) {
1742                 /*
1743                  * when the decision to use weighted algorithm was made
1744                  * we had enough appropriate OSPs, but this state can
1745                  * change anytime (no space on OST, broken connection, etc)
1746                  * so it's possible OSP won't be able to provide us with
1747                  * an object due to just changed state
1748                  */
1749                 QOS_DEBUG("%s: wanted %d objects, found only %d\n",
1750                           lod2obd(lod)->obd_name, stripe_count, nfound);
1751                 for (i = 0; i < nfound; i++) {
1752                         LASSERT(stripe[i] != NULL);
1753                         dt_object_put(env, stripe[i]);
1754                         stripe[i] = NULL;
1755                 }
1756
1757                 /* makes sense to rebalance next time */
1758                 set_bit(LQ_DIRTY, &lod->lod_ost_descs.ltd_qos.lq_flags);
1759                 clear_bit(LQ_SAME_SPACE, &lod->lod_ost_descs.ltd_qos.lq_flags);
1760                 rc = -EAGAIN;
1761         }
1762
1763         /* If there are enough OSTs, a component with overstriping requessted
1764          * will not actually end up overstriped.  The comp should reflect this.
1765          */
1766         if (rc == 0 && !overstriped)
1767                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
1768
1769 out:
1770         up_write(&lod->lod_ost_descs.ltd_qos.lq_rw_sem);
1771
1772 out_nolock:
1773         if (pool != NULL) {
1774                 up_read(&pool_tgt_rw_sem(pool));
1775                 /* put back ref got by lod_find_pool() */
1776                 lod_pool_putref(pool);
1777         }
1778
1779         RETURN(rc);
1780 }
1781
1782 /**
1783  * Allocate a striping using an algorithm with weights.
1784  *
1785  * The function allocates remote MDT objects to create a striping, the first
1786  * object was already allocated on current MDT to ensure master object and
1787  * the first object are on the same MDT. The algorithm used is based on weights
1788  * (both free space and inodes), and it's trying to ensure the space/inodes are
1789  * used evenly by MDTs and MDSs. The striping configuration (# of stripes,
1790  * offset, pool) is taken from the object and is prepared by the caller.
1791  *
1792  * If prepared configuration can't be met due to too few MDTs, then allocation
1793  * fails.
1794  *
1795  * No concurrent allocation is allowed on the object and this must be ensured
1796  * by the caller. All the internal structures are protected by the function.
1797  *
1798  * The algorithm has two steps: find available MDTs and calculate their
1799  * weights, then select the MDTs with their weights used as the probability.
1800  * An MDT with a higher weight is proportionately more likely to be selected
1801  * than one with a lower weight.
1802  *
1803  * \param[in] env               execution environment for this thread
1804  * \param[in] lo                LOD object
1805  * \param[in] stripe_idx        starting stripe index to allocate, if it's not
1806  *                              0, we are restriping directory
1807  * \param[in] stripe_count      total stripe count
1808  * \param[out] stripes          striping created
1809  *
1810  * \retval positive     stripes allocated, and it should be equal to
1811  *                      lo->ldo_dir_stripe_count
1812  * \retval -EAGAIN      not enough tgts are found for specified stripe count
1813  * \retval -EINVAL      requested MDT index is invalid
1814  * \retval negative     errno on failure
1815  */
1816 int lod_mdt_alloc_qos(const struct lu_env *env, struct lod_object *lo,
1817                       struct dt_object **stripes, u32 stripe_idx,
1818                       u32 stripe_count)
1819 {
1820         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1821         struct lu_tgt_descs *ltd = &lod->lod_mdt_descs;
1822         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
1823         struct lu_fid fid = { 0 };
1824         const struct lu_tgt_pool *pool;
1825         struct lu_tgt_desc *mdt;
1826         struct dt_object *dto;
1827         u64 total_weight = 0;
1828         u32 saved_idx = stripe_idx;
1829         u32 mdt_idx;
1830         unsigned int good_mdts;
1831         unsigned int i;
1832         int rc = 0;
1833
1834         ENTRY;
1835
1836         /* Totally skip qos part when qos_threshold_rr=100% */
1837         if (ltd->ltd_qos.lq_threshold_rr == QOS_THRESHOLD_MAX)
1838                 return -EAGAIN;
1839
1840         LASSERT(stripe_idx <= stripe_count);
1841         if (stripe_idx == stripe_count)
1842                 RETURN(stripe_count);
1843
1844         /* use MDT pool in @ltd, once MDT pool is supported in the future, it
1845          * can be passed in as argument like OST object allocation.
1846          */
1847         pool = &ltd->ltd_tgt_pool;
1848
1849         /* Detect -EAGAIN early, before expensive lock is taken. */
1850         if (!ltd_qos_is_usable(ltd))
1851                 RETURN(-EAGAIN);
1852
1853         rc = lod_qos_mdt_in_use_init(env, ltd, stripe_idx, stripe_count, pool,
1854                                      stripes);
1855         if (rc)
1856                 RETURN(rc);
1857
1858         /* Do actual allocation, use write lock here. */
1859         down_write(&ltd->ltd_qos.lq_rw_sem);
1860
1861         /*
1862          * Check again, while we were sleeping on @lq_rw_sem things could
1863          * change.
1864          */
1865         if (!ltd_qos_is_usable(ltd))
1866                 GOTO(unlock, rc = -EAGAIN);
1867
1868         rc = ltd_qos_penalties_calc(ltd);
1869         if (rc)
1870                 GOTO(unlock, rc);
1871
1872         good_mdts = 0;
1873         /* Find all the MDTs that are valid stripe candidates */
1874         for (i = 0; i < pool->op_count; i++) {
1875                 if (!test_bit(pool->op_array[i], ltd->ltd_tgt_bitmap))
1876                         continue;
1877
1878                 mdt = LTD_TGT(ltd, pool->op_array[i]);
1879                 mdt->ltd_qos.ltq_usable = 0;
1880
1881                 rc = lod_is_tgt_usable(ltd, mdt);
1882                 if (rc)
1883                         continue;
1884
1885                 if (mdt->ltd_statfs.os_state & OS_STATFS_DEGRADED)
1886                         continue;
1887
1888                 mdt->ltd_qos.ltq_usable = 1;
1889                 lu_tgt_qos_weight_calc(mdt, true);
1890                 total_weight += mdt->ltd_qos.ltq_weight;
1891
1892                 good_mdts++;
1893         }
1894
1895         QOS_DEBUG("found %d good MDTs\n", good_mdts);
1896
1897         if (good_mdts < stripe_count - stripe_idx)
1898                 GOTO(unlock, rc = -EAGAIN);
1899
1900         /* Find enough MDTs with weighted random allocation. */
1901         while (stripe_idx < stripe_count) {
1902                 u64 rand, cur_weight;
1903
1904                 cur_weight = 0;
1905                 rc = -ENOSPC;
1906
1907                 rand = lu_prandom_u64_max(total_weight);
1908
1909                 /* On average, this will hit larger-weighted MDTs more often.
1910                  * 0-weight MDT will always get used last (only when rand=0) */
1911                 for (i = 0; i < pool->op_count; i++) {
1912                         int rc2;
1913
1914                         mdt_idx = pool->op_array[i];
1915                         mdt = LTD_TGT(ltd, mdt_idx);
1916
1917                         if (!mdt->ltd_qos.ltq_usable)
1918                                 continue;
1919
1920                         cur_weight += mdt->ltd_qos.ltq_weight;
1921
1922                         QOS_DEBUG("stripe_count=%d stripe_index=%d cur_weight=%llu rand=%llu total_weight=%llu\n",
1923                                   stripe_count, stripe_idx, cur_weight, rand,
1924                                   total_weight);
1925
1926                         if (cur_weight < rand)
1927                                 continue;
1928
1929                         QOS_DEBUG("stripe=%d to idx=%d\n",
1930                                   stripe_idx, mdt_idx);
1931
1932                         if (lod_qos_is_tgt_used(env, mdt_idx, stripe_idx))
1933                                 continue;
1934
1935                         rc2 = dt_fid_alloc(env, mdt->ltd_tgt, &fid, NULL, NULL);
1936                         if (rc2 < 0) {
1937                                 QOS_DEBUG("can't alloc FID on #%u: %d\n",
1938                                           mdt_idx, rc2);
1939                                 continue;
1940                         }
1941
1942                         conf.loc_flags = LOC_F_NEW;
1943                         dto = dt_locate_at(env, mdt->ltd_tgt, &fid,
1944                                 lo->ldo_obj.do_lu.lo_dev->ld_site->ls_top_dev,
1945                                 &conf);
1946                         if (IS_ERR(dto)) {
1947                                 QOS_DEBUG("can't alloc stripe on #%u: %d\n",
1948                                           mdt_idx, (int) PTR_ERR(dto));
1949                                 continue;
1950                         }
1951
1952                         lod_qos_tgt_in_use(env, stripe_idx, mdt_idx);
1953                         stripes[stripe_idx] = dto;
1954                         ltd_qos_update(ltd, mdt, &total_weight);
1955                         stripe_idx++;
1956                         rc = 0;
1957                         break;
1958                 }
1959
1960                 /* no MDT found on this iteration, give up */
1961                 if (rc)
1962                         break;
1963         }
1964
1965         if (unlikely(stripe_idx != stripe_count)) {
1966                 /*
1967                  * when the decision to use weighted algorithm was made
1968                  * we had enough appropriate OSPs, but this state can
1969                  * change anytime (no space on MDT, broken connection, etc)
1970                  * so it's possible OSP won't be able to provide us with
1971                  * an object due to just changed state
1972                  */
1973                 QOS_DEBUG("%s: wanted %d objects, found only %d\n",
1974                           lod2obd(lod)->obd_name, stripe_count, stripe_idx);
1975                 for (i = saved_idx; i < stripe_idx; i++) {
1976                         LASSERT(stripes[i] != NULL);
1977                         dt_object_put(env, stripes[i]);
1978                         stripes[i] = NULL;
1979                 }
1980
1981                 /* makes sense to rebalance next time */
1982                 set_bit(LQ_DIRTY, &ltd->ltd_qos.lq_flags);
1983                 clear_bit(LQ_SAME_SPACE, &ltd->ltd_qos.lq_flags);
1984
1985                 rc = -EAGAIN;
1986         } else {
1987                 rc = stripe_idx;
1988         }
1989
1990 unlock:
1991         up_write(&ltd->ltd_qos.lq_rw_sem);
1992
1993         RETURN(rc);
1994 }
1995
1996 /**
1997  * Check stripe count the caller can use.
1998  *
1999  * For new layouts (no initialized components), check the total size of the
2000  * layout against the maximum EA size from the backing file system.  This
2001  * stops us from creating a layout which will be too large once initialized.
2002  *
2003  * For existing layouts (with initialized components):
2004  * Find the maximal possible stripe count not greater than \a stripe_count.
2005  * If the provided stripe count is 0, then the filesystem's default is used.
2006  *
2007  * \param[in] lod       LOD device
2008  * \param[in] lo        The lod_object
2009  * \param[in] comp_idx  The component id, which the amount of stripes is
2010                         calculated for
2011  * \param[in] stripe_count      count the caller would like to use
2012  *
2013  * \retval              the maximum usable stripe count
2014  */
2015 __u16 lod_get_stripe_count(struct lod_device *lod, struct lod_object *lo,
2016                            int comp_idx, __u16 stripe_count, bool overstriping)
2017 {
2018         __u32 max_stripes = LOV_MAX_STRIPE_COUNT_OLD;
2019         /* max stripe count is based on OSD ea size */
2020         unsigned int easize = lod->lod_osd_max_easize;
2021         int i;
2022         ENTRY;
2023
2024         if (stripe_count == (__u16)(-1) && lod->lod_max_stripecount)
2025                 stripe_count = lod->lod_max_stripecount;
2026         if (!stripe_count)
2027                 stripe_count =
2028                         lod->lod_ost_descs.ltd_lov_desc.ld_default_stripe_count;
2029         if (!stripe_count)
2030                 stripe_count = 1;
2031         /* Overstriping allows more stripes than targets */
2032         if (stripe_count >
2033                 lod->lod_ost_descs.ltd_lov_desc.ld_active_tgt_count &&
2034             !overstriping)
2035                 stripe_count =
2036                         lod->lod_ost_descs.ltd_lov_desc.ld_active_tgt_count;
2037
2038         if (lo->ldo_is_composite) {
2039                 struct lod_layout_component *lod_comp;
2040                 unsigned int header_sz = sizeof(struct lov_comp_md_v1);
2041                 unsigned int init_comp_sz = 0;
2042                 unsigned int total_comp_sz = 0;
2043                 unsigned int comp_sz;
2044
2045                 header_sz += sizeof(struct lov_comp_md_entry_v1) *
2046                                 lo->ldo_comp_cnt;
2047
2048                 for (i = 0; i < lo->ldo_comp_cnt; i++) {
2049                         unsigned int stripes;
2050
2051                         if (i == comp_idx)
2052                                 continue;
2053
2054                         lod_comp = &lo->ldo_comp_entries[i];
2055                         /* Extension comp is never inited - 0 stripes on disk */
2056                         stripes = lod_comp->llc_flags & LCME_FL_EXTENSION ? 0 :
2057                                 lod_comp->llc_stripe_count;
2058
2059                         comp_sz = lov_mds_md_size(stripes, LOV_MAGIC_V3);
2060                         total_comp_sz += comp_sz;
2061                         if (lod_comp->llc_flags & LCME_FL_INIT)
2062                                 init_comp_sz += comp_sz;
2063                 }
2064
2065                 if (init_comp_sz > 0)
2066                         total_comp_sz = init_comp_sz;
2067
2068                 header_sz += total_comp_sz;
2069
2070                 if (easize > header_sz)
2071                         easize -= header_sz;
2072                 else
2073                         easize = 0;
2074         }
2075
2076         max_stripes = lov_mds_md_max_stripe_count(easize, LOV_MAGIC_V3);
2077         max_stripes = (max_stripes == 0) ? 0 : max_stripes - 1;
2078
2079         stripe_count = min_t(__u16, stripe_count, max_stripes);
2080         RETURN(stripe_count);
2081 }
2082
2083 /**
2084  * Create in-core respresentation for a fully-defined striping
2085  *
2086  * When the caller passes a fully-defined striping (i.e. everything including
2087  * OST object FIDs are defined), then we still need to instantiate LU-cache
2088  * with the objects representing the stripes defined. This function completes
2089  * that task.
2090  *
2091  * \param[in] env       execution environment for this thread
2092  * \param[in] mo        LOD object
2093  * \param[in] buf       buffer containing the striping
2094  *
2095  * \retval 0            on success
2096  * \retval negative     negated errno on error
2097  */
2098 int lod_use_defined_striping(const struct lu_env *env,
2099                              struct lod_object *mo,
2100                              const struct lu_buf *buf)
2101 {
2102         struct lod_layout_component *lod_comp;
2103         struct lov_mds_md_v1   *v1 = buf->lb_buf;
2104         struct lov_mds_md_v3   *v3 = buf->lb_buf;
2105         struct lov_comp_md_v1  *comp_v1 = NULL;
2106         struct lov_ost_data_v1 *objs;
2107         __u32   magic;
2108         __u16   comp_cnt;
2109         __u16   mirror_cnt;
2110         int     rc = 0, i;
2111         ENTRY;
2112
2113         mutex_lock(&mo->ldo_layout_mutex);
2114         lod_striping_free_nolock(env, mo);
2115
2116         magic = le32_to_cpu(v1->lmm_magic) & ~LOV_MAGIC_DEFINED;
2117
2118         if (magic != LOV_MAGIC_V1 && magic != LOV_MAGIC_V3 &&
2119             magic != LOV_MAGIC_COMP_V1 && magic != LOV_MAGIC_FOREIGN)
2120                 GOTO(unlock, rc = -EINVAL);
2121
2122         if (magic == LOV_MAGIC_COMP_V1) {
2123                 comp_v1 = buf->lb_buf;
2124                 comp_cnt = le16_to_cpu(comp_v1->lcm_entry_count);
2125                 if (comp_cnt == 0)
2126                         GOTO(unlock, rc = -EINVAL);
2127                 mirror_cnt = le16_to_cpu(comp_v1->lcm_mirror_count) + 1;
2128                 mo->ldo_flr_state = le16_to_cpu(comp_v1->lcm_flags) &
2129                                         LCM_FL_FLR_MASK;
2130                 mo->ldo_is_composite = 1;
2131         } else if (magic == LOV_MAGIC_FOREIGN) {
2132                 struct lov_foreign_md *foreign;
2133                 size_t length;
2134
2135                 if (buf->lb_len < offsetof(typeof(*foreign), lfm_value)) {
2136                         CDEBUG(D_LAYOUT,
2137                                "buf len %zu < min lov_foreign_md size (%zu)\n",
2138                                buf->lb_len,
2139                                offsetof(typeof(*foreign), lfm_value));
2140                         GOTO(out, rc = -EINVAL);
2141                 }
2142                 foreign = (struct lov_foreign_md *)buf->lb_buf;
2143                 length = foreign_size_le(foreign);
2144                 if (buf->lb_len < length) {
2145                         CDEBUG(D_LAYOUT,
2146                                "buf len %zu < this lov_foreign_md size (%zu)\n",
2147                                buf->lb_len, length);
2148                         GOTO(out, rc = -EINVAL);
2149                 }
2150
2151                 /* just cache foreign LOV EA raw */
2152                 rc = lod_alloc_foreign_lov(mo, length);
2153                 if (rc)
2154                         GOTO(out, rc);
2155                 memcpy(mo->ldo_foreign_lov, buf->lb_buf, length);
2156                 GOTO(out, rc);
2157         } else {
2158                 mo->ldo_is_composite = 0;
2159                 comp_cnt = 1;
2160                 mirror_cnt = 0;
2161         }
2162         mo->ldo_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
2163
2164         rc = lod_alloc_comp_entries(mo, mirror_cnt, comp_cnt);
2165         if (rc)
2166                 GOTO(unlock, rc);
2167
2168         for (i = 0; i < comp_cnt; i++) {
2169                 struct lu_extent *ext;
2170                 char    *pool_name;
2171                 __u32   offs;
2172
2173                 lod_comp = &mo->ldo_comp_entries[i];
2174
2175                 if (mo->ldo_is_composite) {
2176                         offs = le32_to_cpu(comp_v1->lcm_entries[i].lcme_offset);
2177                         v1 = (struct lov_mds_md_v1 *)((char *)comp_v1 + offs);
2178                         v3 = (struct lov_mds_md_v3 *)v1;
2179                         magic = le32_to_cpu(v1->lmm_magic);
2180
2181                         ext = &comp_v1->lcm_entries[i].lcme_extent;
2182                         lod_comp->llc_extent.e_start =
2183                                 le64_to_cpu(ext->e_start);
2184                         lod_comp->llc_extent.e_end = le64_to_cpu(ext->e_end);
2185                         lod_comp->llc_flags =
2186                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_flags);
2187                         if (lod_comp->llc_flags & LCME_FL_NOSYNC)
2188                                 lod_comp->llc_timestamp = le64_to_cpu(
2189                                         comp_v1->lcm_entries[i].lcme_timestamp);
2190                         lod_comp->llc_id =
2191                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_id);
2192                         if (lod_comp->llc_id == LCME_ID_INVAL)
2193                                 GOTO(out, rc = -EINVAL);
2194                 }
2195
2196                 pool_name = NULL;
2197                 if (magic == LOV_MAGIC_V1) {
2198                         objs = &v1->lmm_objects[0];
2199                 } else if (magic == LOV_MAGIC_V3) {
2200                         objs = &v3->lmm_objects[0];
2201                         if (v3->lmm_pool_name[0] != '\0')
2202                                 pool_name = v3->lmm_pool_name;
2203                 } else {
2204                         CDEBUG(D_LAYOUT, "Invalid magic %x\n", magic);
2205                         GOTO(out, rc = -EINVAL);
2206                 }
2207
2208                 lod_comp->llc_pattern = le32_to_cpu(v1->lmm_pattern);
2209                 lod_comp->llc_stripe_size = le32_to_cpu(v1->lmm_stripe_size);
2210                 lod_comp->llc_stripe_count = le16_to_cpu(v1->lmm_stripe_count);
2211                 lod_comp->llc_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
2212                 /**
2213                  * The stripe_offset of an uninit-ed component is stored in
2214                  * the lmm_layout_gen
2215                  */
2216                 if (mo->ldo_is_composite && !lod_comp_inited(lod_comp))
2217                         lod_comp->llc_stripe_offset = lod_comp->llc_layout_gen;
2218                 lod_obj_set_pool(mo, i, pool_name);
2219
2220                 if ((!mo->ldo_is_composite || lod_comp_inited(lod_comp)) &&
2221                     !(lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED) &&
2222                     !(lod_comp->llc_pattern & LOV_PATTERN_MDT)) {
2223                         rc = lod_initialize_objects(env, mo, objs, i);
2224                         if (rc)
2225                                 GOTO(out, rc);
2226                 }
2227         }
2228
2229         rc = lod_fill_mirrors(mo);
2230         GOTO(out, rc);
2231 out:
2232         if (rc)
2233                 lod_striping_free_nolock(env, mo);
2234 unlock:
2235         mutex_unlock(&mo->ldo_layout_mutex);
2236
2237         RETURN(rc);
2238 }
2239
2240 static void lod_qos_set_pool(struct lod_object *lo, int pos, char *pool_name,
2241                              struct lov_user_md_v1 *v1)
2242 {
2243         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2244         struct lod_layout_component *lod_comp;
2245         struct pool_desc *pool = NULL;
2246         int j, rc = 0;
2247
2248         /* In the function below, .hs_keycmp resolves to
2249          * pool_hashkey_keycmp() */
2250         /* coverity[overrun-buffer-val] */
2251         if (pool_name)
2252                 pool = lod_find_pool(d, pool_name);
2253
2254         if (pool) {
2255                 lod_comp = &lo->ldo_comp_entries[pos];
2256                 if (lod_comp->llc_stripe_offset != LOV_OFFSET_DEFAULT) {
2257                         if (v1->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
2258                                 struct lov_user_md_v3 *v3;
2259
2260                                 v3 = (struct lov_user_md_v3 *)v1;
2261                                 for (j = 0; j < v3->lmm_stripe_count; j++) {
2262                                         __u32 num;
2263
2264                                         num = lod_comp->llc_ostlist.op_array[j];
2265                                         rc = lod_check_index_in_pool(num, pool);
2266                                         if (rc)
2267                                                 break;
2268                                 }
2269                         } else {
2270                                 rc = lod_check_index_in_pool(
2271                                         lod_comp->llc_stripe_offset, pool);
2272                         }
2273                         if (rc < 0) {
2274                                 CDEBUG(D_LAYOUT, "%s: index %u is not in the "
2275                                        "pool %s, dropping the pool\n",
2276                                        lod2obd(d)->obd_name,
2277                                        lod_comp->llc_stripe_offset,
2278                                        pool_name);
2279                                 pool_name = NULL;
2280                         }
2281                 }
2282
2283                 if (lod_comp->llc_stripe_count > pool_tgt_count(pool) &&
2284                     !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING))
2285                         lod_comp->llc_stripe_count = pool_tgt_count(pool);
2286
2287                 lod_pool_putref(pool);
2288         }
2289
2290         lod_obj_set_pool(lo, pos, pool_name);
2291 }
2292
2293 /**
2294  * Parse suggested striping configuration.
2295  *
2296  * The caller gets a suggested striping configuration from a number of sources
2297  * including per-directory default and applications. Then it needs to verify
2298  * the suggested striping is valid, apply missing bits and store the resulting
2299  * configuration in the object to be used by the allocator later. Must not be
2300  * called concurrently against the same object. It's OK to provide a
2301  * fully-defined striping.
2302  *
2303  * \param[in] env       execution environment for this thread
2304  * \param[in] lo        LOD object
2305  * \param[in] buf       buffer containing the striping
2306  *
2307  * \retval 0            on success
2308  * \retval negative     negated errno on error
2309  */
2310 int lod_qos_parse_config(const struct lu_env *env, struct lod_object *lo,
2311                          const struct lu_buf *buf)
2312 {
2313         struct lod_layout_component *lod_comp;
2314         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2315         struct lov_desc *desc = &d->lod_ost_descs.ltd_lov_desc;
2316         struct lov_user_md_v1 *v1 = NULL;
2317         struct lov_user_md_v3 *v3 = NULL;
2318         struct lov_comp_md_v1 *comp_v1 = NULL;
2319         struct lov_foreign_md *lfm = NULL;
2320         char def_pool[LOV_MAXPOOLNAME + 1];
2321         __u32 magic;
2322         __u16 comp_cnt;
2323         __u16 mirror_cnt;
2324         int i, rc;
2325         ENTRY;
2326
2327         if (buf == NULL || buf->lb_buf == NULL || buf->lb_len == 0)
2328                 RETURN(0);
2329
2330         memset(def_pool, 0, sizeof(def_pool));
2331         if (lo->ldo_comp_entries != NULL)
2332                 lod_layout_get_pool(lo->ldo_comp_entries, lo->ldo_comp_cnt,
2333                                     def_pool, sizeof(def_pool));
2334
2335         /* free default striping info */
2336         if (lo->ldo_is_foreign)
2337                 lod_free_foreign_lov(lo);
2338         else
2339                 lod_free_comp_entries(lo);
2340
2341         rc = lod_verify_striping(env, d, lo, buf, false);
2342         if (rc)
2343                 RETURN(-EINVAL);
2344
2345         v3 = buf->lb_buf;
2346         v1 = buf->lb_buf;
2347         comp_v1 = buf->lb_buf;
2348         /* {lmm,lfm}_magic position/length work for all LOV formats */
2349         magic = v1->lmm_magic;
2350
2351         if (unlikely(le32_to_cpu(magic) & LOV_MAGIC_DEFINED)) {
2352                 /* try to use as fully defined striping */
2353                 rc = lod_use_defined_striping(env, lo, buf);
2354                 RETURN(rc);
2355         }
2356
2357         switch (magic) {
2358         case __swab32(LOV_USER_MAGIC_V1):
2359                 lustre_swab_lov_user_md_v1(v1);
2360                 magic = v1->lmm_magic;
2361                 fallthrough;
2362         case LOV_USER_MAGIC_V1:
2363                 break;
2364         case __swab32(LOV_USER_MAGIC_V3):
2365                 lustre_swab_lov_user_md_v3(v3);
2366                 magic = v3->lmm_magic;
2367                 fallthrough;
2368         case LOV_USER_MAGIC_V3:
2369                 break;
2370         case __swab32(LOV_USER_MAGIC_SPECIFIC):
2371                 lustre_swab_lov_user_md_v3(v3);
2372                 lustre_swab_lov_user_md_objects(v3->lmm_objects,
2373                                                 v3->lmm_stripe_count);
2374                 magic = v3->lmm_magic;
2375                 fallthrough;
2376         case LOV_USER_MAGIC_SPECIFIC:
2377                 break;
2378         case __swab32(LOV_USER_MAGIC_COMP_V1):
2379                 lustre_swab_lov_comp_md_v1(comp_v1);
2380                 magic = comp_v1->lcm_magic;
2381                 /* fall trhough */
2382         case LOV_USER_MAGIC_COMP_V1:
2383                 break;
2384         case __swab32(LOV_USER_MAGIC_FOREIGN):
2385                 lfm = buf->lb_buf;
2386                 __swab32s(&lfm->lfm_magic);
2387                 __swab32s(&lfm->lfm_length);
2388                 __swab32s(&lfm->lfm_type);
2389                 __swab32s(&lfm->lfm_flags);
2390                 magic = lfm->lfm_magic;
2391                 fallthrough;
2392         case LOV_USER_MAGIC_FOREIGN:
2393                 if (!lfm)
2394                         lfm = buf->lb_buf;
2395                 rc = lod_alloc_foreign_lov(lo, foreign_size(lfm));
2396                 if (rc)
2397                         RETURN(rc);
2398                 memcpy(lo->ldo_foreign_lov, buf->lb_buf, foreign_size(lfm));
2399                 RETURN(0);
2400         default:
2401                 CERROR("%s: unrecognized magic %X\n",
2402                        lod2obd(d)->obd_name, magic);
2403                 RETURN(-EINVAL);
2404         }
2405
2406         lustre_print_user_md(D_OTHER, v1, "parse config");
2407
2408         if (magic == LOV_USER_MAGIC_COMP_V1) {
2409                 comp_cnt = comp_v1->lcm_entry_count;
2410                 if (comp_cnt == 0)
2411                         RETURN(-EINVAL);
2412                 mirror_cnt =  comp_v1->lcm_mirror_count + 1;
2413                 if (mirror_cnt > 1)
2414                         lo->ldo_flr_state = LCM_FL_RDONLY;
2415                 lo->ldo_is_composite = 1;
2416         } else {
2417                 comp_cnt = 1;
2418                 mirror_cnt = 0;
2419                 lo->ldo_is_composite = 0;
2420         }
2421
2422         rc = lod_alloc_comp_entries(lo, mirror_cnt, comp_cnt);
2423         if (rc)
2424                 RETURN(rc);
2425
2426         LASSERT(lo->ldo_comp_entries);
2427
2428         for (i = 0; i < comp_cnt; i++) {
2429                 struct lu_extent        *ext;
2430                 char    *pool_name;
2431
2432                 lod_comp = &lo->ldo_comp_entries[i];
2433
2434                 if (lo->ldo_is_composite) {
2435                         v1 = (struct lov_user_md *)((char *)comp_v1 +
2436                                         comp_v1->lcm_entries[i].lcme_offset);
2437                         ext = &comp_v1->lcm_entries[i].lcme_extent;
2438                         lod_comp->llc_extent = *ext;
2439                         lod_comp->llc_flags =
2440                                 comp_v1->lcm_entries[i].lcme_flags &
2441                                         LCME_CL_COMP_FLAGS;
2442                 }
2443
2444                 pool_name = NULL;
2445                 if (def_pool[0] != '\0')
2446                         pool_name = def_pool;
2447
2448                 if (v1->lmm_magic == LOV_USER_MAGIC_V3 ||
2449                     v1->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
2450                         v3 = (struct lov_user_md_v3 *)v1;
2451
2452                         if (lov_pool_is_ignored(v3->lmm_pool_name))
2453                                 pool_name = NULL;
2454                         else if (v3->lmm_pool_name[0] != '\0' &&
2455                                  !lov_pool_is_inherited(v3->lmm_pool_name))
2456                                 pool_name = v3->lmm_pool_name;
2457
2458                         if (v3->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
2459                                 rc = lod_comp_copy_ost_lists(lod_comp, v3);
2460                                 if (rc)
2461                                         GOTO(free_comp, rc);
2462                         }
2463                 }
2464
2465                 if (v1->lmm_pattern == 0)
2466                         v1->lmm_pattern = LOV_PATTERN_RAID0;
2467                 if (lov_pattern(v1->lmm_pattern) != LOV_PATTERN_RAID0 &&
2468                     lov_pattern(v1->lmm_pattern) != LOV_PATTERN_MDT &&
2469                     lov_pattern(v1->lmm_pattern) !=
2470                         (LOV_PATTERN_RAID0 | LOV_PATTERN_OVERSTRIPING)) {
2471                         CDEBUG(D_LAYOUT, "%s: invalid pattern: %x\n",
2472                                lod2obd(d)->obd_name, v1->lmm_pattern);
2473                         GOTO(free_comp, rc = -EINVAL);
2474                 }
2475
2476                 lod_comp->llc_pattern = v1->lmm_pattern;
2477                 lod_comp->llc_stripe_size = v1->lmm_stripe_size;
2478                 lod_adjust_stripe_size(lod_comp, desc->ld_default_stripe_size);
2479
2480                 lod_comp->llc_stripe_count = desc->ld_default_stripe_count;
2481                 if (v1->lmm_stripe_count ||
2482                     lov_pattern(v1->lmm_pattern) == LOV_PATTERN_MDT)
2483                         lod_comp->llc_stripe_count = v1->lmm_stripe_count;
2484
2485                 if (lov_pattern(lod_comp->llc_pattern) == LOV_PATTERN_MDT &&
2486                     lod_comp->llc_stripe_count != 0) {
2487                         CDEBUG(D_LAYOUT, "%s: invalid stripe count: %u\n",
2488                                lod2obd(d)->obd_name,
2489                                lod_comp->llc_stripe_count);
2490                         GOTO(free_comp, rc = -EINVAL);
2491                 }
2492
2493                 lod_comp->llc_stripe_offset = v1->lmm_stripe_offset;
2494                 lod_qos_set_pool(lo, i, pool_name, v1);
2495         }
2496
2497         RETURN(0);
2498
2499 free_comp:
2500         lod_free_comp_entries(lo);
2501         RETURN(rc);
2502 }
2503
2504 /**
2505  * prepare enough OST avoidance bitmap space
2506  */
2507 int lod_prepare_avoidance(const struct lu_env *env, struct lod_object *lo)
2508 {
2509         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
2510         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
2511         unsigned long *bitmap = NULL;
2512         __u32 *new_oss = NULL;
2513
2514         lag->lag_ost_avail = lod->lod_ost_count;
2515
2516         /* reset OSS avoid guide array */
2517         lag->lag_oaa_count = 0;
2518         if (lag->lag_oss_avoid_array &&
2519             lag->lag_oaa_size < lod->lod_ost_count) {
2520                 OBD_FREE_PTR_ARRAY(lag->lag_oss_avoid_array, lag->lag_oaa_size);
2521                 lag->lag_oss_avoid_array = NULL;
2522                 lag->lag_oaa_size = 0;
2523         }
2524
2525         /* init OST avoid guide bitmap */
2526         if (lag->lag_ost_avoid_bitmap) {
2527                 if (lod->lod_ost_count <= lag->lag_ost_avoid_size) {
2528                         bitmap_zero(lag->lag_ost_avoid_bitmap,
2529                                     lag->lag_ost_avoid_size);
2530                 } else {
2531                         bitmap_free(lag->lag_ost_avoid_bitmap);
2532                         lag->lag_ost_avoid_bitmap = NULL;
2533                 }
2534         }
2535
2536         if (!lag->lag_ost_avoid_bitmap) {
2537                 bitmap = bitmap_zalloc(lod->lod_ost_count, GFP_KERNEL);
2538                 if (!bitmap)
2539                         return -ENOMEM;
2540         }
2541
2542         if (!lag->lag_oss_avoid_array) {
2543                 /**
2544                  * usually there are multiple OSTs in one OSS, but we don't
2545                  * know the exact OSS number, so we choose a safe option,
2546                  * using OST count to allocate the array to store the OSS
2547                  * id.
2548                  */
2549                 OBD_ALLOC_PTR_ARRAY(new_oss, lod->lod_ost_count);
2550                 if (!new_oss) {
2551                         bitmap_free(bitmap);
2552                         return -ENOMEM;
2553                 }
2554         }
2555
2556         if (new_oss) {
2557                 lag->lag_oss_avoid_array = new_oss;
2558                 lag->lag_oaa_size = lod->lod_ost_count;
2559         }
2560         if (bitmap) {
2561                 lag->lag_ost_avoid_bitmap = bitmap;
2562                 lag->lag_ost_avoid_size = lod->lod_ost_count;
2563         }
2564
2565         return 0;
2566 }
2567
2568 /**
2569  * Collect information of used OSTs and OSSs in the overlapped components
2570  * of other mirrors
2571  */
2572 void lod_collect_avoidance(struct lod_object *lo, struct lod_avoid_guide *lag,
2573                            int comp_idx)
2574 {
2575         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
2576         struct lod_layout_component *lod_comp = &lo->ldo_comp_entries[comp_idx];
2577         unsigned long *bitmap = lag->lag_ost_avoid_bitmap;
2578         int i, j;
2579
2580         /* iterate components */
2581         for (i = 0; i < lo->ldo_comp_cnt; i++) {
2582                 struct lod_layout_component *comp;
2583
2584                 /**
2585                  * skip mirror containing component[comp_idx], we only
2586                  * collect OSTs info of conflicting component in other mirrors,
2587                  * so that during read, if OSTs of a mirror's component are
2588                  * not available, we still have other mirror with different
2589                  * OSTs to read the data.
2590                  */
2591                 comp = &lo->ldo_comp_entries[i];
2592                 if (comp->llc_id != LCME_ID_INVAL &&
2593                     mirror_id_of(comp->llc_id) ==
2594                                                 mirror_id_of(lod_comp->llc_id))
2595                         continue;
2596
2597                 /**
2598                  * skip non-overlapped or un-instantiated components,
2599                  * NOTE: don't use lod_comp_inited(comp) to judge
2600                  * whether @comp has been inited, since during
2601                  * declare phase, comp->llc_stripe has been allocated
2602                  * while it's init flag not been set until the exec
2603                  * phase.
2604                  */
2605                 if (!lu_extent_is_overlapped(&comp->llc_extent,
2606                                              &lod_comp->llc_extent) ||
2607                     !comp->llc_stripe)
2608                         continue;
2609
2610                 /**
2611                  * collect used OSTs index and OSS info from a
2612                  * component
2613                  */
2614                 for (j = 0; j < comp->llc_stripe_count; j++) {
2615                         struct lod_tgt_desc *ost;
2616                         struct lu_svr_qos *lsq;
2617                         int k;
2618
2619                         ost = OST_TGT(lod, comp->llc_ost_indices[j]);
2620                         lsq = ost->ltd_qos.ltq_svr;
2621
2622                         if (test_bit(ost->ltd_index, bitmap))
2623                                 continue;
2624
2625                         QOS_DEBUG("OST%d used in conflicting mirror "
2626                                   "component\n", ost->ltd_index);
2627                         set_bit(ost->ltd_index, bitmap);
2628                         lag->lag_ost_avail--;
2629
2630                         for (k = 0; k < lag->lag_oaa_count; k++) {
2631                                 if (lag->lag_oss_avoid_array[k] ==
2632                                     lsq->lsq_id)
2633                                         break;
2634                         }
2635                         if (k == lag->lag_oaa_count) {
2636                                 lag->lag_oss_avoid_array[k] =
2637                                                         lsq->lsq_id;
2638                                 lag->lag_oaa_count++;
2639                         }
2640                 }
2641         }
2642 }
2643
2644 /**
2645  * Create a striping for an obejct.
2646  *
2647  * The function creates a new striping for the object. The function tries QoS
2648  * algorithm first unless free space is distributed evenly among OSTs, but
2649  * by default RR algorithm is preferred due to internal concurrency (QoS is
2650  * serialized). The caller must ensure no concurrent calls to the function
2651  * are made against the same object.
2652  *
2653  * \param[in] env       execution environment for this thread
2654  * \param[in] lo        LOD object
2655  * \param[in] attr      attributes OST objects will be declared with
2656  * \param[in] th        transaction handle
2657  * \param[in] comp_idx  index of ldo_comp_entries
2658  *
2659  * \retval 0            on success
2660  * \retval negative     negated errno on error
2661  */
2662 int lod_qos_prep_create(const struct lu_env *env, struct lod_object *lo,
2663                         struct lu_attr *attr, struct thandle *th,
2664                         int comp_idx, __u64 reserve)
2665 {
2666         struct lod_layout_component *lod_comp;
2667         struct lod_device      *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2668         int                     stripe_len;
2669         int                     flag = LOV_USES_ASSIGNED_STRIPE;
2670         int                     i, rc = 0;
2671         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
2672         struct dt_object **stripe = NULL;
2673         __u32 *ost_indices = NULL;
2674         ENTRY;
2675
2676         LASSERT(lo);
2677         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
2678         lod_comp = &lo->ldo_comp_entries[comp_idx];
2679         LASSERT(!(lod_comp->llc_flags & LCME_FL_EXTENSION));
2680
2681         /* A released component is being created */
2682         if (lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED)
2683                 RETURN(0);
2684
2685         /* A Data-on-MDT component is being created */
2686         if (lov_pattern(lod_comp->llc_pattern) == LOV_PATTERN_MDT)
2687                 RETURN(0);
2688
2689         if (lod_comp->llc_pool)
2690                 lod_check_and_spill_pool(env, d, &lod_comp->llc_pool);
2691
2692         if (likely(lod_comp->llc_stripe == NULL)) {
2693                 /*
2694                  * no striping has been created so far
2695                  */
2696                 LASSERT(lod_comp->llc_stripe_count);
2697                 /*
2698                  * statfs and check OST targets now, since ld_active_tgt_count
2699                  * could be changed if some OSTs are [de]activated manually.
2700                  */
2701                 lod_qos_statfs_update(env, d, &d->lod_ost_descs);
2702                 stripe_len = lod_get_stripe_count(d, lo, comp_idx,
2703                                                   lod_comp->llc_stripe_count,
2704                                                   lod_comp->llc_pattern &
2705                                                   LOV_PATTERN_OVERSTRIPING);
2706
2707                 if (stripe_len == 0)
2708                         GOTO(out, rc = -ERANGE);
2709                 lod_comp->llc_stripe_count = stripe_len;
2710                 OBD_ALLOC_PTR_ARRAY(stripe, stripe_len);
2711                 if (stripe == NULL)
2712                         GOTO(out, rc = -ENOMEM);
2713                 OBD_ALLOC_PTR_ARRAY(ost_indices, stripe_len);
2714                 if (!ost_indices)
2715                         GOTO(out, rc = -ENOMEM);
2716
2717 repeat:
2718                 lod_getref(&d->lod_ost_descs);
2719                 /* XXX: support for non-0 files w/o objects */
2720                 CDEBUG(D_OTHER, "tgt_count %d stripe_count %d\n",
2721                        d->lod_ost_count, stripe_len);
2722
2723                 if (lod_comp->llc_ostlist.op_array &&
2724                     lod_comp->llc_ostlist.op_count) {
2725                         rc = lod_alloc_ost_list(env, lo, stripe, ost_indices,
2726                                                 th, comp_idx, reserve);
2727                 } else if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT) {
2728                         /**
2729                          * collect OSTs and OSSs used in other mirrors whose
2730                          * components cross the ldo_comp_entries[comp_idx]
2731                          */
2732                         rc = lod_prepare_avoidance(env, lo);
2733                         if (rc)
2734                                 GOTO(put_ldts, rc);
2735
2736                         QOS_DEBUG("collecting conflict osts for comp[%d]\n",
2737                                   comp_idx);
2738                         lod_collect_avoidance(lo, lag, comp_idx);
2739
2740                         rc = lod_ost_alloc_qos(env, lo, stripe, ost_indices,
2741                                                flag, th, comp_idx, reserve);
2742                         if (rc == -EAGAIN)
2743                                 rc = lod_ost_alloc_rr(env, lo, stripe,
2744                                                       ost_indices, flag, th,
2745                                                       comp_idx, reserve);
2746                 } else {
2747                         rc = lod_ost_alloc_specific(env, lo, stripe,
2748                                                     ost_indices, flag, th,
2749                                                     comp_idx, reserve);
2750                 }
2751 put_ldts:
2752                 lod_putref(d, &d->lod_ost_descs);
2753                 if (rc < 0) {
2754                         for (i = 0; i < stripe_len; i++)
2755                                 if (stripe[i] != NULL)
2756                                         dt_object_put(env, stripe[i]);
2757
2758                         /* In case there is no space on any OST, let's ignore
2759                          * the @reserve space to avoid an error at the init
2760                          * time, probably the actual IO will be less than the
2761                          * given @reserve space (aka extension_size). */
2762                         if (reserve) {
2763                                 reserve = 0;
2764                                 goto repeat;
2765                         }
2766                         lod_comp->llc_stripe_count = 0;
2767                 } else {
2768                         lod_comp->llc_layout_gen = 0;
2769                         lod_comp->llc_stripe = stripe;
2770                         lod_comp->llc_ost_indices = ost_indices;
2771                         lod_comp->llc_stripes_allocated = stripe_len;
2772                 }
2773         } else {
2774                 /*
2775                  * lod_qos_parse_config() found supplied buf as a predefined
2776                  * striping (not a hint), so it allocated all the object
2777                  * now we need to create them
2778                  */
2779                 for (i = 0; i < lod_comp->llc_stripe_count; i++) {
2780                         struct dt_object  *o;
2781
2782                         o = lod_comp->llc_stripe[i];
2783                         LASSERT(o);
2784
2785                         rc = lod_sub_declare_create(env, o, attr, NULL,
2786                                                     NULL, th);
2787                         if (rc < 0) {
2788                                 CERROR("can't declare create: %d\n", rc);
2789                                 break;
2790                         }
2791                 }
2792                 /**
2793                  * Clear LCME_FL_INIT for the component so that
2794                  * lod_striping_create() can create the striping objects
2795                  * in replay.
2796                  */
2797                 lod_comp_unset_init(lod_comp);
2798         }
2799
2800 out:
2801         if (rc < 0) {
2802                 if (stripe)
2803                         OBD_FREE_PTR_ARRAY(stripe, stripe_len);
2804                 if (ost_indices)
2805                         OBD_FREE_PTR_ARRAY(ost_indices, stripe_len);
2806         }
2807         RETURN(rc);
2808 }
2809
2810 int lod_prepare_create(const struct lu_env *env, struct lod_object *lo,
2811                        struct lu_attr *attr, const struct lu_buf *buf,
2812                        struct thandle *th)
2813
2814 {
2815         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2816         uint64_t size = 0;
2817         int i;
2818         int rc;
2819         ENTRY;
2820
2821         LASSERT(lo);
2822
2823         /* no OST available */
2824         /* XXX: should we be waiting a bit to prevent failures during
2825          * cluster initialization? */
2826         if (!d->lod_ost_count)
2827                 RETURN(-EIO);
2828
2829         /*
2830          * by this time, the object's ldo_stripe_count and ldo_stripe_size
2831          * contain default value for striping: taken from the parent
2832          * or from filesystem defaults
2833          *
2834          * in case the caller is passing lovea with new striping config,
2835          * we may need to parse lovea and apply new configuration
2836          */
2837         rc = lod_qos_parse_config(env, lo, buf);
2838         if (rc)
2839                 RETURN(rc);
2840
2841         if (attr->la_valid & LA_SIZE)
2842                 size = attr->la_size;
2843
2844         /**
2845          * prepare OST object creation for the component covering file's
2846          * size, the 1st component (including plain layout file) is always
2847          * instantiated.
2848          */
2849         for (i = 0; i < lo->ldo_comp_cnt; i++) {
2850                 struct lod_layout_component *lod_comp;
2851                 struct lu_extent *extent;
2852
2853                 lod_comp = &lo->ldo_comp_entries[i];
2854                 extent = &lod_comp->llc_extent;
2855                 QOS_DEBUG("comp[%d] %lld "DEXT"\n", i, size, PEXT(extent));
2856                 if (!lo->ldo_is_composite || size >= extent->e_start) {
2857                         rc = lod_qos_prep_create(env, lo, attr, th, i, 0);
2858                         if (rc)
2859                                 break;
2860                 }
2861         }
2862
2863         RETURN(rc);
2864 }