Whamcloud - gitweb
LU-15393 lod: skip qos for qos_threshold_rr=100
[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                 rc = lod_check_and_reserve_ost(env, lo, lod_comp, ost_idx,
834                                                speed, &stripe_idx, stripe,
835                                                ost_indices, th, &overstriped,
836                                                reserve);
837
838                 if (rc != 0 && OST_TGT(m, ost_idx)->ltd_connecting)
839                         ost_connecting = 1;
840         }
841         if ((speed < 2) && (stripe_idx < stripe_count_min)) {
842                 /* Try again, allowing slower OSCs */
843                 speed++;
844
845                 ost_connecting = 0;
846                 goto repeat_find;
847         }
848         up_read(&m->lod_ost_descs.ltd_qos.lq_rw_sem);
849
850         /* If there are enough OSTs, a component with overstriping requested
851          * will not actually end up overstriped.  The comp should reflect this.
852          */
853         if (!overstriped)
854                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
855
856         if (stripe_idx) {
857                 lod_comp->llc_stripe_count = stripe_idx;
858                 /* at least one stripe is allocated */
859                 rc = 0;
860         } else {
861                 /* nobody provided us with a single object */
862                 if (ost_connecting)
863                         rc = -EINPROGRESS;
864                 else
865                         rc = -ENOSPC;
866         }
867
868 out:
869         if (pool != NULL) {
870                 up_read(&pool_tgt_rw_sem(pool));
871                 /* put back ref got by lod_find_pool() */
872                 lod_pool_putref(pool);
873         }
874
875         RETURN(rc);
876 }
877
878 static int
879 lod_qos_mdt_in_use_init(const struct lu_env *env,
880                         const struct lu_tgt_descs *ltd,
881                         u32 stripe_idx, u32 stripe_count,
882                         const struct lu_tgt_pool *pool,
883                         struct dt_object **stripes)
884 {
885         u32 mdt_idx;
886         struct lu_tgt_desc *mdt;
887         int i, j;
888         int rc;
889
890         rc = lod_qos_tgt_in_use_clear(env, stripe_count);
891         if (rc)
892                 return rc;
893
894         /* if stripe_idx > 1, we are splitting directory, mark existing stripes
895          * in_use. Because for either split or creation, stripe 0 is local,
896          * don't mark it in use.
897          */
898         for (i = 1; i < stripe_idx; i++) {
899                 LASSERT(stripes[i]);
900                 for (j = 0; j < pool->op_count; j++) {
901                         mdt_idx = pool->op_array[j];
902
903                         if (!test_bit(mdt_idx, ltd->ltd_tgt_bitmap))
904                                 continue;
905
906                         mdt = LTD_TGT(ltd, mdt_idx);
907                         if (&mdt->ltd_tgt->dd_lu_dev ==
908                             stripes[i]->do_lu.lo_dev)
909                                 lod_qos_tgt_in_use(env, i, mdt_idx);
910                 }
911         }
912
913         return 0;
914 }
915
916 /**
917  * Allocate a striping using round-robin algorithm.
918  *
919  * Allocates a new striping using round-robin algorithm. The function refreshes
920  * all the internal structures (statfs cache, array of available remote MDTs
921  * sorted with regard to MDS, etc). The number of stripes required is taken from
922  * the object (must be prepared by the caller). The caller should ensure nobody
923  * else is trying to create a striping on the object in parallel. All the
924  * internal structures (like pools, etc) are protected and no additional locking
925  * is required. The function succeeds even if a single stripe is allocated.
926  *
927  * \param[in] env               execution environment for this thread
928  * \param[in] lo                LOD object
929  * \param[out] stripes          striping created
930  *
931  * \retval positive     stripe objects allocated, including the first stripe
932  *                      allocated outside
933  * \retval -ENOSPC      if not enough MDTs are found
934  * \retval negative     negated errno for other failures
935  */
936 int lod_mdt_alloc_rr(const struct lu_env *env, struct lod_object *lo,
937                      struct dt_object **stripes, u32 stripe_idx,
938                      u32 stripe_count)
939 {
940         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
941         struct lu_tgt_descs *ltd = &lod->lod_mdt_descs;
942         struct lu_tgt_pool *pool;
943         struct lu_qos_rr *lqr;
944         struct lu_tgt_desc *mdt;
945         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
946         struct lu_fid fid = { 0 };
947         struct dt_object *dto;
948         unsigned int pool_idx;
949         unsigned int i;
950         u32 saved_idx = stripe_idx;
951         u32 mdt_idx;
952         bool use_degraded = false;
953         int tgt_connecting = 0;
954         int rc;
955
956         ENTRY;
957
958         pool = &ltd->ltd_tgt_pool;
959         lqr = &ltd->ltd_qos.lq_rr;
960         rc = lod_qos_calc_rr(lod, ltd, pool, lqr);
961         if (rc)
962                 RETURN(rc);
963
964         rc = lod_qos_mdt_in_use_init(env, ltd, stripe_idx, stripe_count, pool,
965                                      stripes);
966         if (rc)
967                 RETURN(rc);
968
969         down_read(&ltd->ltd_qos.lq_rw_sem);
970         spin_lock(&lqr->lqr_alloc);
971         if (--lqr->lqr_start_count <= 0) {
972                 atomic_set(&lqr->lqr_start_idx,
973                             prandom_u32_max(pool->op_count));
974                 lqr->lqr_start_count =
975                         (LOV_CREATE_RESEED_MIN / max(pool->op_count, 1U) +
976                          LOV_CREATE_RESEED_MULT) * max(pool->op_count, 1U);
977         } else if (atomic_read(&lqr->lqr_start_idx) >= pool->op_count) {
978                 /* If we have allocated from all of the tgts, slowly
979                  * precess the next start if the tgt/stripe count isn't
980                  * already doing this for us. */
981                 atomic_sub(pool->op_count, &lqr->lqr_start_idx);
982                 if (stripe_count - 1 > 1 &&
983                     (pool->op_count % (stripe_count - 1)) != 1)
984                         ++lqr->lqr_offset_idx;
985         }
986         spin_unlock(&lqr->lqr_alloc);
987
988 repeat_find:
989         QOS_DEBUG("want=%d start_idx=%d start_count=%d offset=%d active=%d count=%d\n",
990                   stripe_count - 1, atomic_read(&lqr->lqr_start_idx),
991                   lqr->lqr_start_count, lqr->lqr_offset_idx, pool->op_count,
992                   pool->op_count);
993
994         for (i = 0; i < pool->op_count && stripe_idx < stripe_count; i++) {
995                 int idx;
996
997                 idx = atomic_inc_return(&lqr->lqr_start_idx);
998                 pool_idx = (idx + lqr->lqr_offset_idx) %
999                             pool->op_count;
1000                 mdt_idx = lqr->lqr_pool.op_array[pool_idx];
1001                 mdt = LTD_TGT(ltd, mdt_idx);
1002
1003                 QOS_DEBUG("#%d strt %d act %d strp %d ary %d idx %d\n",
1004                           i, idx, /* XXX: active*/ 0,
1005                           stripe_idx, pool_idx, mdt_idx);
1006
1007                 if (mdt_idx == LOV_QOS_EMPTY ||
1008                     !test_bit(mdt_idx, ltd->ltd_tgt_bitmap))
1009                         continue;
1010
1011                 /* do not put >1 objects on one MDT */
1012                 if (lod_qos_is_tgt_used(env, mdt_idx, stripe_idx))
1013                         continue;
1014
1015                 rc = lod_is_tgt_usable(ltd, mdt);
1016                 if (rc) {
1017                         if (mdt->ltd_connecting)
1018                                 tgt_connecting = 1;
1019                         continue;
1020                 }
1021
1022                 /* try to use another OSP if this one is degraded */
1023                 if (mdt->ltd_statfs.os_state & OS_STATFS_DEGRADED &&
1024                     !use_degraded) {
1025                         QOS_DEBUG("#%d: degraded\n", mdt_idx);
1026                         continue;
1027                 }
1028
1029                 rc = dt_fid_alloc(env, mdt->ltd_tgt, &fid, NULL, NULL);
1030                 if (rc < 0) {
1031                         QOS_DEBUG("#%d: alloc FID failed: %dl\n", mdt_idx, rc);
1032                         continue;
1033                 }
1034
1035                 dto = dt_locate_at(env, mdt->ltd_tgt, &fid,
1036                                 lo->ldo_obj.do_lu.lo_dev->ld_site->ls_top_dev,
1037                                 &conf);
1038
1039                 if (IS_ERR(dto)) {
1040                         QOS_DEBUG("can't alloc stripe on #%u: %d\n",
1041                                   mdt->ltd_index, (int) PTR_ERR(dto));
1042
1043                         if (mdt->ltd_connecting)
1044                                 tgt_connecting = 1;
1045                         continue;
1046                 }
1047
1048                 lod_qos_tgt_in_use(env, stripe_idx, mdt_idx);
1049                 stripes[stripe_idx++] = dto;
1050         }
1051
1052         if (!use_degraded && stripe_idx < stripe_count) {
1053                 /* Try again, allowing slower MDTs */
1054                 use_degraded = true;
1055
1056                 tgt_connecting = 0;
1057                 goto repeat_find;
1058         }
1059         up_read(&ltd->ltd_qos.lq_rw_sem);
1060
1061         if (stripe_idx > saved_idx)
1062                 /* at least one stripe is allocated */
1063                 RETURN(stripe_idx);
1064
1065         /* nobody provided us with a single object */
1066         if (tgt_connecting)
1067                 RETURN(-EINPROGRESS);
1068
1069         RETURN(-ENOSPC);
1070 }
1071
1072 /**
1073  * Allocate a specific striping layout on a user defined set of OSTs.
1074  *
1075  * Allocates new striping using the OST index range provided by the data from
1076  * the lmm_obejcts contained in the lov_user_md passed to this method. Full
1077  * OSTs are not considered. The exact order of OSTs requested by the user
1078  * is respected as much as possible depending on OST status. The number of
1079  * stripes needed and stripe offset are taken from the object. If that number
1080  * can not be met, then the function returns a failure and then it's the
1081  * caller's responsibility to release the stripes allocated. All the internal
1082  * structures are protected, but no concurrent allocation is allowed on the
1083  * same objects.
1084  *
1085  * \param[in] env               execution environment for this thread
1086  * \param[in] lo                LOD object
1087  * \param[out] stripe           striping created
1088  * \param[out] ost_indices      ost indices of striping created
1089  * \param[in] th                transaction handle
1090  * \param[in] comp_idx          index of ldo_comp_entries
1091  *
1092  * \retval 0            on success
1093  * \retval -ENODEV      OST index does not exist on file system
1094  * \retval -EINVAL      requested OST index is invalid
1095  * \retval negative     negated errno on error
1096  */
1097 static int lod_alloc_ost_list(const struct lu_env *env, struct lod_object *lo,
1098                               struct dt_object **stripe, __u32 *ost_indices,
1099                               struct thandle *th, int comp_idx, __u64 reserve)
1100 {
1101         struct lod_layout_component *lod_comp;
1102         struct lod_device       *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1103         struct dt_object        *o;
1104         unsigned int            array_idx = 0;
1105         int                     stripe_count = 0;
1106         int                     i;
1107         int                     rc = -EINVAL;
1108         ENTRY;
1109
1110         /* for specific OSTs layout */
1111         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1112         lod_comp = &lo->ldo_comp_entries[comp_idx];
1113         LASSERT(lod_comp->llc_ostlist.op_array);
1114         LASSERT(lod_comp->llc_ostlist.op_count);
1115
1116         rc = lod_qos_tgt_in_use_clear(env, lod_comp->llc_stripe_count);
1117         if (rc < 0)
1118                 RETURN(rc);
1119
1120         if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT)
1121                 lod_comp->llc_stripe_offset =
1122                                 lod_comp->llc_ostlist.op_array[0];
1123
1124         for (i = 0; i < lod_comp->llc_stripe_count; i++) {
1125                 if (lod_comp->llc_ostlist.op_array[i] ==
1126                     lod_comp->llc_stripe_offset) {
1127                         array_idx = i;
1128                         break;
1129                 }
1130         }
1131         if (i == lod_comp->llc_stripe_count) {
1132                 CDEBUG(D_OTHER,
1133                        "%s: start index %d not in the specified list of OSTs\n",
1134                        lod2obd(m)->obd_name, lod_comp->llc_stripe_offset);
1135                 RETURN(-EINVAL);
1136         }
1137
1138         for (i = 0; i < lod_comp->llc_stripe_count;
1139              i++, array_idx = (array_idx + 1) % lod_comp->llc_stripe_count) {
1140                 __u32 ost_idx = lod_comp->llc_ostlist.op_array[array_idx];
1141
1142                 if (!test_bit(ost_idx, m->lod_ost_bitmap)) {
1143                         rc = -ENODEV;
1144                         break;
1145                 }
1146
1147                 /* do not put >1 objects on a single OST, except for
1148                  * overstriping
1149                  */
1150                 if (lod_qos_is_tgt_used(env, ost_idx, stripe_count) &&
1151                     !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)) {
1152                         rc = -EINVAL;
1153                         break;
1154                 }
1155
1156                 rc = lod_statfs_and_check(env, m, &m->lod_ost_descs,
1157                                           LTD_TGT(&m->lod_ost_descs, ost_idx),
1158                                           reserve);
1159                 if (rc < 0) /* this OSP doesn't feel well */
1160                         break;
1161
1162                 o = lod_qos_declare_object_on(env, m, ost_idx, true, th);
1163                 if (IS_ERR(o)) {
1164                         rc = PTR_ERR(o);
1165                         CDEBUG(D_OTHER,
1166                                "%s: can't declare new object on #%u: %d\n",
1167                                lod2obd(m)->obd_name, ost_idx, rc);
1168                         break;
1169                 }
1170
1171                 /*
1172                  * We've successfully declared (reserved) an object
1173                  */
1174                 lod_qos_tgt_in_use(env, stripe_count, ost_idx);
1175                 stripe[stripe_count] = o;
1176                 ost_indices[stripe_count] = ost_idx;
1177                 stripe_count++;
1178         }
1179
1180         RETURN(rc);
1181 }
1182
1183 /**
1184  * Allocate a striping on a predefined set of OSTs.
1185  *
1186  * Allocates new layout starting from OST index in lo->ldo_stripe_offset.
1187  * Full OSTs are not considered. The exact order of OSTs is not important and
1188  * varies depending on OST status. The allocation procedure prefers the targets
1189  * with precreated objects ready. The number of stripes needed and stripe
1190  * offset are taken from the object. If that number cannot be met, then the
1191  * function returns an error and then it's the caller's responsibility to
1192  * release the stripes allocated. All the internal structures are protected,
1193  * but no concurrent allocation is allowed on the same objects.
1194  *
1195  * \param[in] env               execution environment for this thread
1196  * \param[in] lo                LOD object
1197  * \param[out] stripe           striping created
1198  * \param[out] ost_indices      ost indices of striping created
1199  * \param[in] flags             not used
1200  * \param[in] th                transaction handle
1201  * \param[in] comp_idx          index of ldo_comp_entries
1202  *
1203  * \retval 0            on success
1204  * \retval -ENOSPC      if no OST objects are available at all
1205  * \retval -EFBIG       if not enough OST objects are found
1206  * \retval -EINVAL      requested offset is invalid
1207  * \retval negative     errno on failure
1208  */
1209 static int lod_ost_alloc_specific(const struct lu_env *env,
1210                                   struct lod_object *lo,
1211                                   struct dt_object **stripe, __u32 *ost_indices,
1212                                   int flags, struct thandle *th, int comp_idx,
1213                                   __u64 reserve)
1214 {
1215         struct lod_layout_component *lod_comp;
1216         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1217         struct dt_object *o;
1218         struct lu_tgt_desc *tgt;
1219         __u32 ost_idx;
1220         unsigned int i, array_idx, ost_count;
1221         int rc, stripe_num = 0;
1222         int speed = 0;
1223         struct pool_desc *pool = NULL;
1224         struct lu_tgt_pool *osts;
1225         int stripes_per_ost = 1;
1226         bool overstriped = false;
1227         ENTRY;
1228
1229         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1230         lod_comp = &lo->ldo_comp_entries[comp_idx];
1231
1232         rc = lod_qos_tgt_in_use_clear(env, lod_comp->llc_stripe_count);
1233         if (rc)
1234                 GOTO(out, rc);
1235
1236         if (lod_comp->llc_pool != NULL)
1237                 pool = lod_find_pool(m, lod_comp->llc_pool);
1238
1239         if (pool != NULL) {
1240                 down_read(&pool_tgt_rw_sem(pool));
1241                 osts = &(pool->pool_obds);
1242         } else {
1243                 osts = &m->lod_ost_descs.ltd_tgt_pool;
1244         }
1245
1246         ost_count = osts->op_count;
1247
1248 repeat_find:
1249         /* search loi_ost_idx in ost array */
1250         array_idx = 0;
1251         for (i = 0; i < ost_count; i++) {
1252                 if (osts->op_array[i] == lod_comp->llc_stripe_offset) {
1253                         array_idx = i;
1254                         break;
1255                 }
1256         }
1257         if (i == ost_count) {
1258                 CERROR("Start index %d not found in pool '%s'\n",
1259                        lod_comp->llc_stripe_offset,
1260                        lod_comp->llc_pool ? lod_comp->llc_pool : "");
1261                 GOTO(out, rc = -EINVAL);
1262         }
1263
1264         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1265                 stripes_per_ost =
1266                         (lod_comp->llc_stripe_count - 1)/ost_count + 1;
1267
1268         /* user specifies bigger stripe count than available ost count */
1269         if (lod_comp->llc_stripe_count > ost_count * stripes_per_ost)
1270                 lod_comp->llc_stripe_count = ost_count * stripes_per_ost;
1271
1272         for (i = 0; i < ost_count * stripes_per_ost;
1273                         i++, array_idx = (array_idx + 1) % ost_count) {
1274                 ost_idx = osts->op_array[array_idx];
1275
1276                 if (!test_bit(ost_idx, m->lod_ost_bitmap))
1277                         continue;
1278
1279                 /* Fail Check before osc_precreate() is called
1280                    so we can only 'fail' single OSC. */
1281                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
1282                         continue;
1283
1284                 /*
1285                  * do not put >1 objects on a single OST, except for
1286                  * overstriping, where it is intended
1287                  */
1288                 if (lod_qos_is_tgt_used(env, ost_idx, stripe_num)) {
1289                         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1290                                 overstriped = true;
1291                         else
1292                                 continue;
1293                 }
1294
1295                 /*
1296                  * try not allocate on the OST used by other component
1297                  */
1298                 if (speed == 0 && i != 0 &&
1299                     lod_comp_is_ost_used(env, lo, ost_idx))
1300                         continue;
1301
1302                 tgt = LTD_TGT(&m->lod_ost_descs, ost_idx);
1303
1304                 /* Drop slow OSCs if we can, but not for requested start idx.
1305                  *
1306                  * This means "if OSC is slow and it is not the requested
1307                  * start OST, then it can be skipped, otherwise skip it only
1308                  * if it is inactive/recovering/out-of-space." */
1309
1310                 rc = lod_statfs_and_check(env, m, &m->lod_ost_descs,
1311                                           tgt, reserve);
1312                 if (rc) {
1313                         /* this OSP doesn't feel well */
1314                         continue;
1315                 }
1316
1317                 /*
1318                  * We expect number of precreated objects at the first
1319                  * iteration.  Skip OSPs with no objects ready.  Don't apply
1320                  * this logic to OST specified with stripe_offset.
1321                  */
1322                 if (i && !tgt->ltd_statfs.os_fprecreated && !speed)
1323                         continue;
1324
1325                 o = lod_qos_declare_object_on(env, m, ost_idx, true, th);
1326                 if (IS_ERR(o)) {
1327                         CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
1328                                ost_idx, (int) PTR_ERR(o));
1329                         continue;
1330                 }
1331
1332                 /*
1333                  * We've successfully declared (reserved) an object
1334                  */
1335                 lod_qos_tgt_in_use(env, stripe_num, ost_idx);
1336                 stripe[stripe_num] = o;
1337                 ost_indices[stripe_num] = ost_idx;
1338                 stripe_num++;
1339
1340                 /* We have enough stripes */
1341                 if (stripe_num == lod_comp->llc_stripe_count)
1342                         GOTO(out, rc = 0);
1343         }
1344         if (speed < 2) {
1345                 /* Try again, allowing slower OSCs */
1346                 speed++;
1347                 goto repeat_find;
1348         }
1349
1350         /* If we were passed specific striping params, then a failure to
1351          * meet those requirements is an error, since we can't reallocate
1352          * that memory (it might be part of a larger array or something).
1353          */
1354         CERROR("can't lstripe objid "DFID": have %d want %u\n",
1355                PFID(lu_object_fid(lod2lu_obj(lo))), stripe_num,
1356                lod_comp->llc_stripe_count);
1357         rc = stripe_num == 0 ? -ENOSPC : -EFBIG;
1358
1359         /* If there are enough OSTs, a component with overstriping requessted
1360          * will not actually end up overstriped.  The comp should reflect this.
1361          */
1362         if (rc == 0 && !overstriped)
1363                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
1364
1365 out:
1366         if (pool != NULL) {
1367                 up_read(&pool_tgt_rw_sem(pool));
1368                 /* put back ref got by lod_find_pool() */
1369                 lod_pool_putref(pool);
1370         }
1371
1372         RETURN(rc);
1373 }
1374
1375 #ifdef HAVE_DOWN_WRITE_KILLABLE
1376 struct semaphore_timer {
1377         struct timer_list timer;
1378         struct task_struct *task;
1379 };
1380
1381 static void process_semaphore_timer(struct timer_list *t)
1382 {
1383         struct semaphore_timer *timeout = cfs_from_timer(timeout, t, timer);
1384
1385         send_sig(SIGKILL, timeout->task, 1);
1386 }
1387 #endif
1388
1389 /**
1390  * Calculate penalties per-ost in a pool
1391  *
1392  * The algorithm is similar to ltd_qos_penalties_calc(), but much simpler,
1393  * just considering the space of each OST in this pool.
1394  *
1395  * \param[in] lod       lod_device
1396  * \param[in] pool      pool_desc
1397  *
1398  * \retval 0            on success
1399  * \retval -EAGAIN      the number of OSTs isn't enough or all tgt spaces are
1400  *                      almost the same
1401  */
1402 static int lod_pool_qos_penalties_calc(struct lod_device *lod,
1403                                        struct pool_desc *pool)
1404 {
1405         struct lu_tgt_descs *ltd = &lod->lod_ost_descs;
1406         struct lu_qos *qos = &ltd->ltd_qos;
1407         struct lov_desc *desc = &ltd->ltd_lov_desc;
1408         struct lu_tgt_pool *osts = &pool->pool_obds;
1409         struct lod_tgt_desc *ost;
1410         __u64 ba_max, ba_min, ba;
1411         __u32 num_active;
1412         int prio_wide;
1413         time64_t now, age;
1414         int i, rc;
1415
1416         ENTRY;
1417
1418         now = ktime_get_real_seconds();
1419
1420         if (pool->pool_same_space && now < pool->pool_same_space_expire)
1421                 GOTO(out, rc = 0);
1422
1423         num_active = osts->op_count - 1;
1424         if (num_active < 1)
1425                 GOTO(out, rc = -EAGAIN);
1426
1427         prio_wide = 256 - qos->lq_prio_free;
1428
1429         ba_min = (__u64)(-1);
1430         ba_max = 0;
1431
1432         /* Calculate penalty per OST */
1433         for (i = 0; i < osts->op_count; i++) {
1434                 if (!test_bit(osts->op_array[i], lod->lod_ost_bitmap))
1435                         continue;
1436
1437                 ost = OST_TGT(lod, osts->op_array[i]);
1438                 if (!ost->ltd_active)
1439                         continue;
1440
1441                 ba = ost->ltd_statfs.os_bavail * ost->ltd_statfs.os_bsize;
1442                 ba >>= 8;
1443                 if (!ba)
1444                         continue;
1445
1446                 ba_min = min(ba, ba_min);
1447                 ba_max = max(ba, ba_max);
1448                 ost->ltd_qos.ltq_svr->lsq_bavail += ba;
1449
1450                 /*
1451                  * per-ost penalty is
1452                  * prio * bavail * iavail / (num_tgt - 1) / 2
1453                  */
1454                 ost->ltd_qos.ltq_penalty_per_obj = prio_wide * ba >> 8;
1455                 do_div(ost->ltd_qos.ltq_penalty_per_obj, num_active);
1456
1457                 age = (now - ost->ltd_qos.ltq_used) >> 3;
1458                 if (age > 32 * desc->ld_qos_maxage)
1459                         ost->ltd_qos.ltq_penalty = 0;
1460                 else if (age > desc->ld_qos_maxage)
1461                         /* Decay ost penalty. */
1462                         ost->ltd_qos.ltq_penalty >>= age / desc->ld_qos_maxage;
1463         }
1464
1465         /*
1466          * If each ost has almost same free space, do rr allocation for better
1467          * creation performance
1468          */
1469         if ((ba_max * (256 - qos->lq_threshold_rr)) >> 8 < ba_min) {
1470                 pool->pool_same_space = true;
1471                 pool->pool_same_space_expire = now + desc->ld_qos_maxage;
1472         } else {
1473                 pool->pool_same_space = false;
1474         }
1475         rc = 0;
1476
1477 out:
1478         if (!rc && pool->pool_same_space)
1479                 rc = -EAGAIN;
1480
1481         RETURN(rc);
1482 }
1483
1484 /**
1485  * Allocate a striping using an algorithm with weights.
1486  *
1487  * The function allocates OST objects to create a striping. The algorithm
1488  * used is based on weights (currently only using the free space), and it's
1489  * trying to ensure the space is used evenly by OSTs and OSSs. The striping
1490  * configuration (# of stripes, offset, pool) is taken from the object and
1491  * is prepared by the caller.
1492  *
1493  * If LOV_USES_DEFAULT_STRIPE is not passed and prepared configuration can't
1494  * be met due to too few OSTs, then allocation fails. If the flag is passed
1495  * fewer than 3/4 of the requested number of stripes can be allocated, then
1496  * allocation fails.
1497  *
1498  * No concurrent allocation is allowed on the object and this must be ensured
1499  * by the caller. All the internal structures are protected by the function.
1500  *
1501  * The algorithm has two steps: find available OSTs and calculate their
1502  * weights, then select the OSTs with their weights used as the probability.
1503  * An OST with a higher weight is proportionately more likely to be selected
1504  * than one with a lower weight.
1505  *
1506  * \param[in] env               execution environment for this thread
1507  * \param[in] lo                LOD object
1508  * \param[out] stripe           striping created
1509  * \param[out] ost_indices      ost indices of striping created
1510  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
1511  * \param[in] th                transaction handle
1512  * \param[in] comp_idx          index of ldo_comp_entries
1513  *
1514  * \retval 0            on success
1515  * \retval -EAGAIN      not enough OSTs are found for specified stripe count
1516  * \retval -EINVAL      requested OST index is invalid
1517  * \retval negative     errno on failure
1518  */
1519 static int lod_ost_alloc_qos(const struct lu_env *env, struct lod_object *lo,
1520                              struct dt_object **stripe, __u32 *ost_indices,
1521                              int flags, struct thandle *th, int comp_idx,
1522                              __u64 reserve)
1523 {
1524         struct lod_layout_component *lod_comp;
1525         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1526         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
1527         struct lod_tgt_desc *ost;
1528         struct dt_object *o;
1529         __u64 total_weight = 0;
1530         struct pool_desc *pool = NULL;
1531         struct lu_tgt_pool *osts;
1532         unsigned int i;
1533         __u32 nfound, good_osts, stripe_count, stripe_count_min;
1534         bool overstriped = false;
1535         int stripes_per_ost = 1;
1536         bool slow = false;
1537         int rc = 0;
1538         ENTRY;
1539
1540         /* Totally skip qos part when qos_threshold_rr=100% */
1541         if (lod->lod_ost_descs.ltd_qos.lq_threshold_rr == QOS_THRESHOLD_MAX)
1542                 return -EAGAIN;
1543
1544         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1545         lod_comp = &lo->ldo_comp_entries[comp_idx];
1546         stripe_count = lod_comp->llc_stripe_count;
1547         stripe_count_min = min_stripe_count(stripe_count, flags);
1548         if (stripe_count_min < 1)
1549                 RETURN(-EINVAL);
1550
1551         if (lod_comp->llc_pool != NULL)
1552                 pool = lod_find_pool(lod, lod_comp->llc_pool);
1553
1554         if (pool != NULL) {
1555                 down_read(&pool_tgt_rw_sem(pool));
1556                 osts = &(pool->pool_obds);
1557         } else {
1558                 osts = &lod->lod_ost_descs.ltd_tgt_pool;
1559         }
1560
1561         /* Detect -EAGAIN early, before expensive lock is taken. */
1562         if (!ltd_qos_is_usable(&lod->lod_ost_descs))
1563                 GOTO(out_nolock, rc = -EAGAIN);
1564
1565         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1566                 stripes_per_ost =
1567                         (lod_comp->llc_stripe_count - 1)/osts->op_count + 1;
1568
1569 #ifdef HAVE_DOWN_WRITE_KILLABLE
1570         if (!down_write_trylock(&lod->lod_ost_descs.ltd_qos.lq_rw_sem)) {
1571                 struct semaphore_timer timer;
1572
1573                 kernel_sigaction(SIGKILL, SIG_DFL);
1574                 timer.task = current;
1575                 cfs_timer_setup(&timer.timer, process_semaphore_timer, 0, 0);
1576                 mod_timer(&timer.timer, jiffies + cfs_time_seconds(2));
1577                 /* Do actual allocation, use write lock here. */
1578                 rc = down_write_killable(&lod->lod_ost_descs.ltd_qos.lq_rw_sem);
1579
1580                 del_singleshot_timer_sync(&timer.timer);
1581                 kernel_sigaction(SIGKILL, SIG_IGN);
1582                 if (rc) {
1583                         flush_signals(current);
1584                         QOS_DEBUG("%s: wakeup semaphore on timeout rc = %d\n",
1585                                   lod2obd(lod)->obd_name, rc);
1586                         GOTO(out_nolock, rc = -EAGAIN);
1587                 }
1588         }
1589 #else
1590         /* Do actual allocation, use write lock here. */
1591         down_write(&lod->lod_ost_descs.ltd_qos.lq_rw_sem);
1592 #endif
1593         /*
1594          * Check again, while we were sleeping on @lq_rw_sem things could
1595          * change.
1596          */
1597         if (!ltd_qos_is_usable(&lod->lod_ost_descs))
1598                 GOTO(out, rc = -EAGAIN);
1599
1600         if (pool != NULL)
1601                 rc = lod_pool_qos_penalties_calc(lod, pool);
1602         else
1603                 rc = ltd_qos_penalties_calc(&lod->lod_ost_descs);
1604         if (rc)
1605                 GOTO(out, rc);
1606
1607         rc = lod_qos_tgt_in_use_clear(env, lod_comp->llc_stripe_count);
1608         if (rc)
1609                 GOTO(out, rc);
1610
1611         good_osts = 0;
1612         /* Find all the OSTs that are valid stripe candidates */
1613         for (i = 0; i < osts->op_count; i++) {
1614                 if (!test_bit(osts->op_array[i], lod->lod_ost_bitmap))
1615                         continue;
1616
1617                 ost = OST_TGT(lod, osts->op_array[i]);
1618                 ost->ltd_qos.ltq_usable = 0;
1619
1620                 rc = lod_statfs_and_check(env, lod, &lod->lod_ost_descs,
1621                                           ost, reserve);
1622                 if (rc) {
1623                         /* this OSP doesn't feel well */
1624                         continue;
1625                 }
1626
1627                 if (ost->ltd_statfs.os_state & OS_STATFS_DEGRADED)
1628                         continue;
1629
1630                 /* Fail Check before osc_precreate() is called
1631                  * so we can only 'fail' single OSC.
1632                  */
1633                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) &&
1634                                    osts->op_array[i] == 0)
1635                         continue;
1636
1637                 ost->ltd_qos.ltq_usable = 1;
1638                 lu_tgt_qos_weight_calc(ost);
1639                 total_weight += ost->ltd_qos.ltq_weight;
1640
1641                 good_osts++;
1642         }
1643
1644         QOS_DEBUG("found %d good osts\n", good_osts);
1645
1646         if (good_osts < stripe_count_min)
1647                 GOTO(out, rc = -EAGAIN);
1648
1649         /* If we do not have enough OSTs for the requested stripe count, do not
1650          * put more stripes per OST than requested.
1651          */
1652         if (stripe_count / stripes_per_ost > good_osts)
1653                 stripe_count = good_osts * stripes_per_ost;
1654
1655         /* Find enough OSTs with weighted random allocation. */
1656         nfound = 0;
1657         while (nfound < stripe_count) {
1658                 u64 rand, cur_weight;
1659
1660                 cur_weight = 0;
1661                 rc = -ENOSPC;
1662
1663                 rand = lu_prandom_u64_max(total_weight);
1664
1665                 /* On average, this will hit larger-weighted OSTs more often.
1666                  * 0-weight OSTs will always get used last (only when rand=0)
1667                  */
1668                 for (i = 0; i < osts->op_count; i++) {
1669                         __u32 idx = osts->op_array[i];
1670                         struct lod_tgt_desc *ost;
1671
1672                         if (lod_should_avoid_ost(lo, lag, idx))
1673                                 continue;
1674
1675                         ost = OST_TGT(lod, idx);
1676
1677                         if (!ost->ltd_qos.ltq_usable)
1678                                 continue;
1679
1680                         cur_weight += ost->ltd_qos.ltq_weight;
1681                         QOS_DEBUG("stripe_count=%d nfound=%d cur_weight=%llu "
1682                                   "rand=%llu total_weight=%llu\n",
1683                                   stripe_count, nfound, cur_weight, rand,
1684                                   total_weight);
1685
1686                         if (cur_weight < rand)
1687                                 continue;
1688
1689                         QOS_DEBUG("stripe=%d to idx=%d\n", nfound, idx);
1690                         /*
1691                          * do not put >1 objects on a single OST, except for
1692                          * overstriping
1693                          */
1694                         if ((lod_comp_is_ost_used(env, lo, idx)) &&
1695                             !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING))
1696                                 continue;
1697
1698                         if (lod_qos_is_tgt_used(env, idx, nfound)) {
1699                                 if (lod_comp->llc_pattern &
1700                                     LOV_PATTERN_OVERSTRIPING)
1701                                         overstriped = true;
1702                                 else
1703                                         continue;
1704                         }
1705
1706                         o = lod_qos_declare_object_on(env, lod, idx, slow, th);
1707                         if (IS_ERR(o)) {
1708                                 QOS_DEBUG("can't declare object on #%u: %d\n",
1709                                           idx, (int) PTR_ERR(o));
1710                                 continue;
1711                         }
1712
1713                         lod_avoid_update(lo, lag);
1714                         lod_qos_tgt_in_use(env, nfound, idx);
1715                         stripe[nfound] = o;
1716                         ost_indices[nfound] = idx;
1717                         ltd_qos_update(&lod->lod_ost_descs, ost, &total_weight);
1718                         nfound++;
1719                         rc = 0;
1720                         break;
1721                 }
1722
1723                 if (rc && !slow && nfound < stripe_count) {
1724                         /* couldn't allocate using precreated objects
1725                          * so try to wait for new precreations */
1726                         slow = true;
1727                         rc = 0;
1728                 }
1729
1730                 if (rc) {
1731                         /* no OST found on this iteration, give up */
1732                         break;
1733                 }
1734         }
1735
1736         if (unlikely(nfound != stripe_count)) {
1737                 /*
1738                  * when the decision to use weighted algorithm was made
1739                  * we had enough appropriate OSPs, but this state can
1740                  * change anytime (no space on OST, broken connection, etc)
1741                  * so it's possible OSP won't be able to provide us with
1742                  * an object due to just changed state
1743                  */
1744                 QOS_DEBUG("%s: wanted %d objects, found only %d\n",
1745                           lod2obd(lod)->obd_name, stripe_count, nfound);
1746                 for (i = 0; i < nfound; i++) {
1747                         LASSERT(stripe[i] != NULL);
1748                         dt_object_put(env, stripe[i]);
1749                         stripe[i] = NULL;
1750                 }
1751
1752                 /* makes sense to rebalance next time */
1753                 set_bit(LQ_DIRTY, &lod->lod_ost_descs.ltd_qos.lq_flags);
1754                 clear_bit(LQ_SAME_SPACE, &lod->lod_ost_descs.ltd_qos.lq_flags);
1755                 rc = -EAGAIN;
1756         }
1757
1758         /* If there are enough OSTs, a component with overstriping requessted
1759          * will not actually end up overstriped.  The comp should reflect this.
1760          */
1761         if (rc == 0 && !overstriped)
1762                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
1763
1764 out:
1765         up_write(&lod->lod_ost_descs.ltd_qos.lq_rw_sem);
1766
1767 out_nolock:
1768         if (pool != NULL) {
1769                 up_read(&pool_tgt_rw_sem(pool));
1770                 /* put back ref got by lod_find_pool() */
1771                 lod_pool_putref(pool);
1772         }
1773
1774         RETURN(rc);
1775 }
1776
1777 /**
1778  * Allocate a striping using an algorithm with weights.
1779  *
1780  * The function allocates remote MDT objects to create a striping, the first
1781  * object was already allocated on current MDT to ensure master object and
1782  * the first object are on the same MDT. The algorithm used is based on weights
1783  * (both free space and inodes), and it's trying to ensure the space/inodes are
1784  * used evenly by MDTs and MDSs. The striping configuration (# of stripes,
1785  * offset, pool) is taken from the object and is prepared by the caller.
1786  *
1787  * If prepared configuration can't be met due to too few MDTs, then allocation
1788  * fails.
1789  *
1790  * No concurrent allocation is allowed on the object and this must be ensured
1791  * by the caller. All the internal structures are protected by the function.
1792  *
1793  * The algorithm has two steps: find available MDTs and calculate their
1794  * weights, then select the MDTs with their weights used as the probability.
1795  * An MDT with a higher weight is proportionately more likely to be selected
1796  * than one with a lower weight.
1797  *
1798  * \param[in] env               execution environment for this thread
1799  * \param[in] lo                LOD object
1800  * \param[in] stripe_idx        starting stripe index to allocate, if it's not
1801  *                              0, we are restriping directory
1802  * \param[in] stripe_count      total stripe count
1803  * \param[out] stripes          striping created
1804  *
1805  * \retval positive     stripes allocated, and it should be equal to
1806  *                      lo->ldo_dir_stripe_count
1807  * \retval -EAGAIN      not enough tgts are found for specified stripe count
1808  * \retval -EINVAL      requested MDT index is invalid
1809  * \retval negative     errno on failure
1810  */
1811 int lod_mdt_alloc_qos(const struct lu_env *env, struct lod_object *lo,
1812                       struct dt_object **stripes, u32 stripe_idx,
1813                       u32 stripe_count)
1814 {
1815         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1816         struct lu_tgt_descs *ltd = &lod->lod_mdt_descs;
1817         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
1818         struct lu_fid fid = { 0 };
1819         const struct lu_tgt_pool *pool;
1820         struct lu_tgt_desc *mdt;
1821         struct dt_object *dto;
1822         u64 total_weight = 0;
1823         u32 saved_idx = stripe_idx;
1824         u32 mdt_idx;
1825         unsigned int good_mdts;
1826         unsigned int i;
1827         int rc = 0;
1828
1829         ENTRY;
1830
1831         /* Totally skip qos part when qos_threshold_rr=100% */
1832         if (ltd->ltd_qos.lq_threshold_rr == QOS_THRESHOLD_MAX)
1833                 return -EAGAIN;
1834
1835         LASSERT(stripe_idx <= stripe_count);
1836         if (stripe_idx == stripe_count)
1837                 RETURN(stripe_count);
1838
1839         /* use MDT pool in @ltd, once MDT pool is supported in the future, it
1840          * can be passed in as argument like OST object allocation.
1841          */
1842         pool = &ltd->ltd_tgt_pool;
1843
1844         /* Detect -EAGAIN early, before expensive lock is taken. */
1845         if (!ltd_qos_is_usable(ltd))
1846                 RETURN(-EAGAIN);
1847
1848         rc = lod_qos_mdt_in_use_init(env, ltd, stripe_idx, stripe_count, pool,
1849                                      stripes);
1850         if (rc)
1851                 RETURN(rc);
1852
1853         /* Do actual allocation, use write lock here. */
1854         down_write(&ltd->ltd_qos.lq_rw_sem);
1855
1856         /*
1857          * Check again, while we were sleeping on @lq_rw_sem things could
1858          * change.
1859          */
1860         if (!ltd_qos_is_usable(ltd))
1861                 GOTO(unlock, rc = -EAGAIN);
1862
1863         rc = ltd_qos_penalties_calc(ltd);
1864         if (rc)
1865                 GOTO(unlock, rc);
1866
1867         good_mdts = 0;
1868         /* Find all the MDTs that are valid stripe candidates */
1869         for (i = 0; i < pool->op_count; i++) {
1870                 if (!test_bit(pool->op_array[i], ltd->ltd_tgt_bitmap))
1871                         continue;
1872
1873                 mdt = LTD_TGT(ltd, pool->op_array[i]);
1874                 mdt->ltd_qos.ltq_usable = 0;
1875
1876                 rc = lod_is_tgt_usable(ltd, mdt);
1877                 if (rc)
1878                         continue;
1879
1880                 if (mdt->ltd_statfs.os_state & OS_STATFS_DEGRADED)
1881                         continue;
1882
1883                 mdt->ltd_qos.ltq_usable = 1;
1884                 lu_tgt_qos_weight_calc(mdt);
1885                 total_weight += mdt->ltd_qos.ltq_weight;
1886
1887                 good_mdts++;
1888         }
1889
1890         QOS_DEBUG("found %d good MDTs\n", good_mdts);
1891
1892         if (good_mdts < stripe_count - stripe_idx)
1893                 GOTO(unlock, rc = -EAGAIN);
1894
1895         /* Find enough MDTs with weighted random allocation. */
1896         while (stripe_idx < stripe_count) {
1897                 u64 rand, cur_weight;
1898
1899                 cur_weight = 0;
1900                 rc = -ENOSPC;
1901
1902                 rand = lu_prandom_u64_max(total_weight);
1903
1904                 /* On average, this will hit larger-weighted MDTs more often.
1905                  * 0-weight MDT will always get used last (only when rand=0) */
1906                 for (i = 0; i < pool->op_count; i++) {
1907                         int rc2;
1908
1909                         mdt_idx = pool->op_array[i];
1910                         mdt = LTD_TGT(ltd, mdt_idx);
1911
1912                         if (!mdt->ltd_qos.ltq_usable)
1913                                 continue;
1914
1915                         cur_weight += mdt->ltd_qos.ltq_weight;
1916
1917                         QOS_DEBUG("stripe_count=%d stripe_index=%d cur_weight=%llu rand=%llu total_weight=%llu\n",
1918                                   stripe_count, stripe_idx, cur_weight, rand,
1919                                   total_weight);
1920
1921                         if (cur_weight < rand)
1922                                 continue;
1923
1924                         QOS_DEBUG("stripe=%d to idx=%d\n",
1925                                   stripe_idx, mdt_idx);
1926
1927                         if (lod_qos_is_tgt_used(env, mdt_idx, stripe_idx))
1928                                 continue;
1929
1930                         rc2 = dt_fid_alloc(env, mdt->ltd_tgt, &fid, NULL, NULL);
1931                         if (rc2 < 0) {
1932                                 QOS_DEBUG("can't alloc FID on #%u: %d\n",
1933                                           mdt_idx, rc2);
1934                                 continue;
1935                         }
1936
1937                         conf.loc_flags = LOC_F_NEW;
1938                         dto = dt_locate_at(env, mdt->ltd_tgt, &fid,
1939                                 lo->ldo_obj.do_lu.lo_dev->ld_site->ls_top_dev,
1940                                 &conf);
1941                         if (IS_ERR(dto)) {
1942                                 QOS_DEBUG("can't alloc stripe on #%u: %d\n",
1943                                           mdt_idx, (int) PTR_ERR(dto));
1944                                 continue;
1945                         }
1946
1947                         lod_qos_tgt_in_use(env, stripe_idx, mdt_idx);
1948                         stripes[stripe_idx] = dto;
1949                         ltd_qos_update(ltd, mdt, &total_weight);
1950                         stripe_idx++;
1951                         rc = 0;
1952                         break;
1953                 }
1954
1955                 /* no MDT found on this iteration, give up */
1956                 if (rc)
1957                         break;
1958         }
1959
1960         if (unlikely(stripe_idx != stripe_count)) {
1961                 /*
1962                  * when the decision to use weighted algorithm was made
1963                  * we had enough appropriate OSPs, but this state can
1964                  * change anytime (no space on MDT, broken connection, etc)
1965                  * so it's possible OSP won't be able to provide us with
1966                  * an object due to just changed state
1967                  */
1968                 QOS_DEBUG("%s: wanted %d objects, found only %d\n",
1969                           lod2obd(lod)->obd_name, stripe_count, stripe_idx);
1970                 for (i = saved_idx; i < stripe_idx; i++) {
1971                         LASSERT(stripes[i] != NULL);
1972                         dt_object_put(env, stripes[i]);
1973                         stripes[i] = NULL;
1974                 }
1975
1976                 /* makes sense to rebalance next time */
1977                 set_bit(LQ_DIRTY, &ltd->ltd_qos.lq_flags);
1978                 clear_bit(LQ_SAME_SPACE, &ltd->ltd_qos.lq_flags);
1979
1980                 rc = -EAGAIN;
1981         } else {
1982                 rc = stripe_idx;
1983         }
1984
1985 unlock:
1986         up_write(&ltd->ltd_qos.lq_rw_sem);
1987
1988         RETURN(rc);
1989 }
1990
1991 /**
1992  * Check stripe count the caller can use.
1993  *
1994  * For new layouts (no initialized components), check the total size of the
1995  * layout against the maximum EA size from the backing file system.  This
1996  * stops us from creating a layout which will be too large once initialized.
1997  *
1998  * For existing layouts (with initialized components):
1999  * Find the maximal possible stripe count not greater than \a stripe_count.
2000  * If the provided stripe count is 0, then the filesystem's default is used.
2001  *
2002  * \param[in] lod       LOD device
2003  * \param[in] lo        The lod_object
2004  * \param[in] comp_idx  The component id, which the amount of stripes is
2005                         calculated for
2006  * \param[in] stripe_count      count the caller would like to use
2007  *
2008  * \retval              the maximum usable stripe count
2009  */
2010 __u16 lod_get_stripe_count(struct lod_device *lod, struct lod_object *lo,
2011                            int comp_idx, __u16 stripe_count, bool overstriping)
2012 {
2013         __u32 max_stripes = LOV_MAX_STRIPE_COUNT_OLD;
2014         /* max stripe count is based on OSD ea size */
2015         unsigned int easize = lod->lod_osd_max_easize;
2016         int i;
2017         ENTRY;
2018
2019         if (stripe_count == (__u16)(-1) && lod->lod_max_stripecount)
2020                 stripe_count = lod->lod_max_stripecount;
2021         if (!stripe_count)
2022                 stripe_count =
2023                         lod->lod_ost_descs.ltd_lov_desc.ld_default_stripe_count;
2024         if (!stripe_count)
2025                 stripe_count = 1;
2026         /* Overstriping allows more stripes than targets */
2027         if (stripe_count >
2028                 lod->lod_ost_descs.ltd_lov_desc.ld_active_tgt_count &&
2029             !overstriping)
2030                 stripe_count =
2031                         lod->lod_ost_descs.ltd_lov_desc.ld_active_tgt_count;
2032
2033         if (lo->ldo_is_composite) {
2034                 struct lod_layout_component *lod_comp;
2035                 unsigned int header_sz = sizeof(struct lov_comp_md_v1);
2036                 unsigned int init_comp_sz = 0;
2037                 unsigned int total_comp_sz = 0;
2038                 unsigned int comp_sz;
2039
2040                 header_sz += sizeof(struct lov_comp_md_entry_v1) *
2041                                 lo->ldo_comp_cnt;
2042
2043                 for (i = 0; i < lo->ldo_comp_cnt; i++) {
2044                         unsigned int stripes;
2045
2046                         if (i == comp_idx)
2047                                 continue;
2048
2049                         lod_comp = &lo->ldo_comp_entries[i];
2050                         /* Extension comp is never inited - 0 stripes on disk */
2051                         stripes = lod_comp->llc_flags & LCME_FL_EXTENSION ? 0 :
2052                                 lod_comp->llc_stripe_count;
2053
2054                         comp_sz = lov_mds_md_size(stripes, LOV_MAGIC_V3);
2055                         total_comp_sz += comp_sz;
2056                         if (lod_comp->llc_flags & LCME_FL_INIT)
2057                                 init_comp_sz += comp_sz;
2058                 }
2059
2060                 if (init_comp_sz > 0)
2061                         total_comp_sz = init_comp_sz;
2062
2063                 header_sz += total_comp_sz;
2064
2065                 if (easize > header_sz)
2066                         easize -= header_sz;
2067                 else
2068                         easize = 0;
2069         }
2070
2071         max_stripes = lov_mds_md_max_stripe_count(easize, LOV_MAGIC_V3);
2072         max_stripes = (max_stripes == 0) ? 0 : max_stripes - 1;
2073
2074         stripe_count = min_t(__u16, stripe_count, max_stripes);
2075         RETURN(stripe_count);
2076 }
2077
2078 /**
2079  * Create in-core respresentation for a fully-defined striping
2080  *
2081  * When the caller passes a fully-defined striping (i.e. everything including
2082  * OST object FIDs are defined), then we still need to instantiate LU-cache
2083  * with the objects representing the stripes defined. This function completes
2084  * that task.
2085  *
2086  * \param[in] env       execution environment for this thread
2087  * \param[in] mo        LOD object
2088  * \param[in] buf       buffer containing the striping
2089  *
2090  * \retval 0            on success
2091  * \retval negative     negated errno on error
2092  */
2093 int lod_use_defined_striping(const struct lu_env *env,
2094                              struct lod_object *mo,
2095                              const struct lu_buf *buf)
2096 {
2097         struct lod_layout_component *lod_comp;
2098         struct lov_mds_md_v1   *v1 = buf->lb_buf;
2099         struct lov_mds_md_v3   *v3 = buf->lb_buf;
2100         struct lov_comp_md_v1  *comp_v1 = NULL;
2101         struct lov_ost_data_v1 *objs;
2102         __u32   magic;
2103         __u16   comp_cnt;
2104         __u16   mirror_cnt;
2105         int     rc = 0, i;
2106         ENTRY;
2107
2108         mutex_lock(&mo->ldo_layout_mutex);
2109         lod_striping_free_nolock(env, mo);
2110
2111         magic = le32_to_cpu(v1->lmm_magic) & ~LOV_MAGIC_DEFINED;
2112
2113         if (magic != LOV_MAGIC_V1 && magic != LOV_MAGIC_V3 &&
2114             magic != LOV_MAGIC_COMP_V1 && magic != LOV_MAGIC_FOREIGN)
2115                 GOTO(unlock, rc = -EINVAL);
2116
2117         if (magic == LOV_MAGIC_COMP_V1) {
2118                 comp_v1 = buf->lb_buf;
2119                 comp_cnt = le16_to_cpu(comp_v1->lcm_entry_count);
2120                 if (comp_cnt == 0)
2121                         GOTO(unlock, rc = -EINVAL);
2122                 mirror_cnt = le16_to_cpu(comp_v1->lcm_mirror_count) + 1;
2123                 mo->ldo_flr_state = le16_to_cpu(comp_v1->lcm_flags) &
2124                                         LCM_FL_FLR_MASK;
2125                 mo->ldo_is_composite = 1;
2126         } else if (magic == LOV_MAGIC_FOREIGN) {
2127                 struct lov_foreign_md *foreign;
2128                 size_t length;
2129
2130                 if (buf->lb_len < offsetof(typeof(*foreign), lfm_value)) {
2131                         CDEBUG(D_LAYOUT,
2132                                "buf len %zu < min lov_foreign_md size (%zu)\n",
2133                                buf->lb_len,
2134                                offsetof(typeof(*foreign), lfm_value));
2135                         GOTO(out, rc = -EINVAL);
2136                 }
2137                 foreign = (struct lov_foreign_md *)buf->lb_buf;
2138                 length = foreign_size_le(foreign);
2139                 if (buf->lb_len < length) {
2140                         CDEBUG(D_LAYOUT,
2141                                "buf len %zu < this lov_foreign_md size (%zu)\n",
2142                                buf->lb_len, length);
2143                         GOTO(out, rc = -EINVAL);
2144                 }
2145
2146                 /* just cache foreign LOV EA raw */
2147                 rc = lod_alloc_foreign_lov(mo, length);
2148                 if (rc)
2149                         GOTO(out, rc);
2150                 memcpy(mo->ldo_foreign_lov, buf->lb_buf, length);
2151                 GOTO(out, rc);
2152         } else {
2153                 mo->ldo_is_composite = 0;
2154                 comp_cnt = 1;
2155                 mirror_cnt = 0;
2156         }
2157         mo->ldo_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
2158
2159         rc = lod_alloc_comp_entries(mo, mirror_cnt, comp_cnt);
2160         if (rc)
2161                 GOTO(unlock, rc);
2162
2163         for (i = 0; i < comp_cnt; i++) {
2164                 struct lu_extent *ext;
2165                 char    *pool_name;
2166                 __u32   offs;
2167
2168                 lod_comp = &mo->ldo_comp_entries[i];
2169
2170                 if (mo->ldo_is_composite) {
2171                         offs = le32_to_cpu(comp_v1->lcm_entries[i].lcme_offset);
2172                         v1 = (struct lov_mds_md_v1 *)((char *)comp_v1 + offs);
2173                         v3 = (struct lov_mds_md_v3 *)v1;
2174                         magic = le32_to_cpu(v1->lmm_magic);
2175
2176                         ext = &comp_v1->lcm_entries[i].lcme_extent;
2177                         lod_comp->llc_extent.e_start =
2178                                 le64_to_cpu(ext->e_start);
2179                         lod_comp->llc_extent.e_end = le64_to_cpu(ext->e_end);
2180                         lod_comp->llc_flags =
2181                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_flags);
2182                         if (lod_comp->llc_flags & LCME_FL_NOSYNC)
2183                                 lod_comp->llc_timestamp = le64_to_cpu(
2184                                         comp_v1->lcm_entries[i].lcme_timestamp);
2185                         lod_comp->llc_id =
2186                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_id);
2187                         if (lod_comp->llc_id == LCME_ID_INVAL)
2188                                 GOTO(out, rc = -EINVAL);
2189                 }
2190
2191                 pool_name = NULL;
2192                 if (magic == LOV_MAGIC_V1) {
2193                         objs = &v1->lmm_objects[0];
2194                 } else if (magic == LOV_MAGIC_V3) {
2195                         objs = &v3->lmm_objects[0];
2196                         if (v3->lmm_pool_name[0] != '\0')
2197                                 pool_name = v3->lmm_pool_name;
2198                 } else {
2199                         CDEBUG(D_LAYOUT, "Invalid magic %x\n", magic);
2200                         GOTO(out, rc = -EINVAL);
2201                 }
2202
2203                 lod_comp->llc_pattern = le32_to_cpu(v1->lmm_pattern);
2204                 lod_comp->llc_stripe_size = le32_to_cpu(v1->lmm_stripe_size);
2205                 lod_comp->llc_stripe_count = le16_to_cpu(v1->lmm_stripe_count);
2206                 lod_comp->llc_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
2207                 /**
2208                  * The stripe_offset of an uninit-ed component is stored in
2209                  * the lmm_layout_gen
2210                  */
2211                 if (mo->ldo_is_composite && !lod_comp_inited(lod_comp))
2212                         lod_comp->llc_stripe_offset = lod_comp->llc_layout_gen;
2213                 lod_obj_set_pool(mo, i, pool_name);
2214
2215                 if ((!mo->ldo_is_composite || lod_comp_inited(lod_comp)) &&
2216                     !(lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED) &&
2217                     !(lod_comp->llc_pattern & LOV_PATTERN_MDT)) {
2218                         rc = lod_initialize_objects(env, mo, objs, i);
2219                         if (rc)
2220                                 GOTO(out, rc);
2221                 }
2222         }
2223
2224         rc = lod_fill_mirrors(mo);
2225         GOTO(out, rc);
2226 out:
2227         if (rc)
2228                 lod_striping_free_nolock(env, mo);
2229 unlock:
2230         mutex_unlock(&mo->ldo_layout_mutex);
2231
2232         RETURN(rc);
2233 }
2234
2235 static void lod_qos_set_pool(struct lod_object *lo, int pos, char *pool_name,
2236                              struct lov_user_md_v1 *v1)
2237 {
2238         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2239         struct lod_layout_component *lod_comp;
2240         struct pool_desc *pool = NULL;
2241         int j, rc = 0;
2242
2243         /* In the function below, .hs_keycmp resolves to
2244          * pool_hashkey_keycmp() */
2245         /* coverity[overrun-buffer-val] */
2246         if (pool_name)
2247                 pool = lod_find_pool(d, pool_name);
2248
2249         if (pool) {
2250                 lod_comp = &lo->ldo_comp_entries[pos];
2251                 if (lod_comp->llc_stripe_offset != LOV_OFFSET_DEFAULT) {
2252                         if (v1->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
2253                                 struct lov_user_md_v3 *v3;
2254
2255                                 v3 = (struct lov_user_md_v3 *)v1;
2256                                 for (j = 0; j < v3->lmm_stripe_count; j++) {
2257                                         __u32 num;
2258
2259                                         num = lod_comp->llc_ostlist.op_array[j];
2260                                         rc = lod_check_index_in_pool(num, pool);
2261                                         if (rc)
2262                                                 break;
2263                                 }
2264                         } else {
2265                                 rc = lod_check_index_in_pool(
2266                                         lod_comp->llc_stripe_offset, pool);
2267                         }
2268                         if (rc < 0) {
2269                                 CDEBUG(D_LAYOUT, "%s: index %u is not in the "
2270                                        "pool %s, dropping the pool\n",
2271                                        lod2obd(d)->obd_name,
2272                                        lod_comp->llc_stripe_offset,
2273                                        pool_name);
2274                                 pool_name = NULL;
2275                         }
2276                 }
2277
2278                 if (lod_comp->llc_stripe_count > pool_tgt_count(pool) &&
2279                     !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING))
2280                         lod_comp->llc_stripe_count = pool_tgt_count(pool);
2281
2282                 lod_pool_putref(pool);
2283         }
2284
2285         lod_obj_set_pool(lo, pos, pool_name);
2286 }
2287
2288 /**
2289  * Parse suggested striping configuration.
2290  *
2291  * The caller gets a suggested striping configuration from a number of sources
2292  * including per-directory default and applications. Then it needs to verify
2293  * the suggested striping is valid, apply missing bits and store the resulting
2294  * configuration in the object to be used by the allocator later. Must not be
2295  * called concurrently against the same object. It's OK to provide a
2296  * fully-defined striping.
2297  *
2298  * \param[in] env       execution environment for this thread
2299  * \param[in] lo        LOD object
2300  * \param[in] buf       buffer containing the striping
2301  *
2302  * \retval 0            on success
2303  * \retval negative     negated errno on error
2304  */
2305 int lod_qos_parse_config(const struct lu_env *env, struct lod_object *lo,
2306                          const struct lu_buf *buf)
2307 {
2308         struct lod_layout_component *lod_comp;
2309         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2310         struct lov_desc *desc = &d->lod_ost_descs.ltd_lov_desc;
2311         struct lov_user_md_v1 *v1 = NULL;
2312         struct lov_user_md_v3 *v3 = NULL;
2313         struct lov_comp_md_v1 *comp_v1 = NULL;
2314         struct lov_foreign_md *lfm = NULL;
2315         char def_pool[LOV_MAXPOOLNAME + 1];
2316         __u32 magic;
2317         __u16 comp_cnt;
2318         __u16 mirror_cnt;
2319         int i, rc;
2320         ENTRY;
2321
2322         if (buf == NULL || buf->lb_buf == NULL || buf->lb_len == 0)
2323                 RETURN(0);
2324
2325         memset(def_pool, 0, sizeof(def_pool));
2326         if (lo->ldo_comp_entries != NULL)
2327                 lod_layout_get_pool(lo->ldo_comp_entries, lo->ldo_comp_cnt,
2328                                     def_pool, sizeof(def_pool));
2329
2330         /* free default striping info */
2331         if (lo->ldo_is_foreign)
2332                 lod_free_foreign_lov(lo);
2333         else
2334                 lod_free_comp_entries(lo);
2335
2336         rc = lod_verify_striping(env, d, lo, buf, false);
2337         if (rc)
2338                 RETURN(-EINVAL);
2339
2340         v3 = buf->lb_buf;
2341         v1 = buf->lb_buf;
2342         comp_v1 = buf->lb_buf;
2343         /* {lmm,lfm}_magic position/length work for all LOV formats */
2344         magic = v1->lmm_magic;
2345
2346         if (unlikely(le32_to_cpu(magic) & LOV_MAGIC_DEFINED)) {
2347                 /* try to use as fully defined striping */
2348                 rc = lod_use_defined_striping(env, lo, buf);
2349                 RETURN(rc);
2350         }
2351
2352         switch (magic) {
2353         case __swab32(LOV_USER_MAGIC_V1):
2354                 lustre_swab_lov_user_md_v1(v1);
2355                 magic = v1->lmm_magic;
2356                 fallthrough;
2357         case LOV_USER_MAGIC_V1:
2358                 break;
2359         case __swab32(LOV_USER_MAGIC_V3):
2360                 lustre_swab_lov_user_md_v3(v3);
2361                 magic = v3->lmm_magic;
2362                 fallthrough;
2363         case LOV_USER_MAGIC_V3:
2364                 break;
2365         case __swab32(LOV_USER_MAGIC_SPECIFIC):
2366                 lustre_swab_lov_user_md_v3(v3);
2367                 lustre_swab_lov_user_md_objects(v3->lmm_objects,
2368                                                 v3->lmm_stripe_count);
2369                 magic = v3->lmm_magic;
2370                 fallthrough;
2371         case LOV_USER_MAGIC_SPECIFIC:
2372                 break;
2373         case __swab32(LOV_USER_MAGIC_COMP_V1):
2374                 lustre_swab_lov_comp_md_v1(comp_v1);
2375                 magic = comp_v1->lcm_magic;
2376                 /* fall trhough */
2377         case LOV_USER_MAGIC_COMP_V1:
2378                 break;
2379         case __swab32(LOV_USER_MAGIC_FOREIGN):
2380                 lfm = buf->lb_buf;
2381                 __swab32s(&lfm->lfm_magic);
2382                 __swab32s(&lfm->lfm_length);
2383                 __swab32s(&lfm->lfm_type);
2384                 __swab32s(&lfm->lfm_flags);
2385                 magic = lfm->lfm_magic;
2386                 fallthrough;
2387         case LOV_USER_MAGIC_FOREIGN:
2388                 if (!lfm)
2389                         lfm = buf->lb_buf;
2390                 rc = lod_alloc_foreign_lov(lo, foreign_size(lfm));
2391                 if (rc)
2392                         RETURN(rc);
2393                 memcpy(lo->ldo_foreign_lov, buf->lb_buf, foreign_size(lfm));
2394                 RETURN(0);
2395         default:
2396                 CERROR("%s: unrecognized magic %X\n",
2397                        lod2obd(d)->obd_name, magic);
2398                 RETURN(-EINVAL);
2399         }
2400
2401         lustre_print_user_md(D_OTHER, v1, "parse config");
2402
2403         if (magic == LOV_USER_MAGIC_COMP_V1) {
2404                 comp_cnt = comp_v1->lcm_entry_count;
2405                 if (comp_cnt == 0)
2406                         RETURN(-EINVAL);
2407                 mirror_cnt =  comp_v1->lcm_mirror_count + 1;
2408                 if (mirror_cnt > 1)
2409                         lo->ldo_flr_state = LCM_FL_RDONLY;
2410                 lo->ldo_is_composite = 1;
2411         } else {
2412                 comp_cnt = 1;
2413                 mirror_cnt = 0;
2414                 lo->ldo_is_composite = 0;
2415         }
2416
2417         rc = lod_alloc_comp_entries(lo, mirror_cnt, comp_cnt);
2418         if (rc)
2419                 RETURN(rc);
2420
2421         LASSERT(lo->ldo_comp_entries);
2422
2423         for (i = 0; i < comp_cnt; i++) {
2424                 struct lu_extent        *ext;
2425                 char    *pool_name;
2426
2427                 lod_comp = &lo->ldo_comp_entries[i];
2428
2429                 if (lo->ldo_is_composite) {
2430                         v1 = (struct lov_user_md *)((char *)comp_v1 +
2431                                         comp_v1->lcm_entries[i].lcme_offset);
2432                         ext = &comp_v1->lcm_entries[i].lcme_extent;
2433                         lod_comp->llc_extent = *ext;
2434                         lod_comp->llc_flags =
2435                                 comp_v1->lcm_entries[i].lcme_flags &
2436                                         LCME_CL_COMP_FLAGS;
2437                 }
2438
2439                 pool_name = NULL;
2440                 if (def_pool[0] != '\0')
2441                         pool_name = def_pool;
2442
2443                 if (v1->lmm_magic == LOV_USER_MAGIC_V3 ||
2444                     v1->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
2445                         v3 = (struct lov_user_md_v3 *)v1;
2446
2447                         if (v3->lmm_pool_name[0] != '\0')
2448                                 pool_name = v3->lmm_pool_name;
2449
2450                         if (v3->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
2451                                 rc = lod_comp_copy_ost_lists(lod_comp, v3);
2452                                 if (rc)
2453                                         GOTO(free_comp, rc);
2454                         }
2455                 }
2456
2457                 if (v1->lmm_pattern == 0)
2458                         v1->lmm_pattern = LOV_PATTERN_RAID0;
2459                 if (lov_pattern(v1->lmm_pattern) != LOV_PATTERN_RAID0 &&
2460                     lov_pattern(v1->lmm_pattern) != LOV_PATTERN_MDT &&
2461                     lov_pattern(v1->lmm_pattern) !=
2462                         (LOV_PATTERN_RAID0 | LOV_PATTERN_OVERSTRIPING)) {
2463                         CDEBUG(D_LAYOUT, "%s: invalid pattern: %x\n",
2464                                lod2obd(d)->obd_name, v1->lmm_pattern);
2465                         GOTO(free_comp, rc = -EINVAL);
2466                 }
2467
2468                 lod_comp->llc_pattern = v1->lmm_pattern;
2469                 lod_comp->llc_stripe_size = v1->lmm_stripe_size;
2470                 lod_adjust_stripe_size(lod_comp, desc->ld_default_stripe_size);
2471
2472                 lod_comp->llc_stripe_count = desc->ld_default_stripe_count;
2473                 if (v1->lmm_stripe_count ||
2474                     lov_pattern(v1->lmm_pattern) == LOV_PATTERN_MDT)
2475                         lod_comp->llc_stripe_count = v1->lmm_stripe_count;
2476
2477                 if (lov_pattern(lod_comp->llc_pattern) == LOV_PATTERN_MDT &&
2478                     lod_comp->llc_stripe_count != 0) {
2479                         CDEBUG(D_LAYOUT, "%s: invalid stripe count: %u\n",
2480                                lod2obd(d)->obd_name,
2481                                lod_comp->llc_stripe_count);
2482                         GOTO(free_comp, rc = -EINVAL);
2483                 }
2484
2485                 lod_comp->llc_stripe_offset = v1->lmm_stripe_offset;
2486                 lod_qos_set_pool(lo, i, pool_name, v1);
2487         }
2488
2489         RETURN(0);
2490
2491 free_comp:
2492         lod_free_comp_entries(lo);
2493         RETURN(rc);
2494 }
2495
2496 /**
2497  * prepare enough OST avoidance bitmap space
2498  */
2499 int lod_prepare_avoidance(const struct lu_env *env, struct lod_object *lo)
2500 {
2501         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
2502         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
2503         unsigned long *bitmap = NULL;
2504         __u32 *new_oss = NULL;
2505
2506         lag->lag_ost_avail = lod->lod_ost_count;
2507
2508         /* reset OSS avoid guide array */
2509         lag->lag_oaa_count = 0;
2510         if (lag->lag_oss_avoid_array &&
2511             lag->lag_oaa_size < lod->lod_ost_count) {
2512                 OBD_FREE_PTR_ARRAY(lag->lag_oss_avoid_array, lag->lag_oaa_size);
2513                 lag->lag_oss_avoid_array = NULL;
2514                 lag->lag_oaa_size = 0;
2515         }
2516
2517         /* init OST avoid guide bitmap */
2518         if (lag->lag_ost_avoid_bitmap) {
2519                 if (lod->lod_ost_count <= lag->lag_ost_avoid_size) {
2520                         bitmap_zero(lag->lag_ost_avoid_bitmap,
2521                                     lag->lag_ost_avoid_size);
2522                 } else {
2523                         bitmap_free(lag->lag_ost_avoid_bitmap);
2524                         lag->lag_ost_avoid_bitmap = NULL;
2525                 }
2526         }
2527
2528         if (!lag->lag_ost_avoid_bitmap) {
2529                 bitmap = bitmap_zalloc(lod->lod_ost_count, GFP_KERNEL);
2530                 if (!bitmap)
2531                         return -ENOMEM;
2532         }
2533
2534         if (!lag->lag_oss_avoid_array) {
2535                 /**
2536                  * usually there are multiple OSTs in one OSS, but we don't
2537                  * know the exact OSS number, so we choose a safe option,
2538                  * using OST count to allocate the array to store the OSS
2539                  * id.
2540                  */
2541                 OBD_ALLOC_PTR_ARRAY(new_oss, lod->lod_ost_count);
2542                 if (!new_oss) {
2543                         bitmap_free(bitmap);
2544                         return -ENOMEM;
2545                 }
2546         }
2547
2548         if (new_oss) {
2549                 lag->lag_oss_avoid_array = new_oss;
2550                 lag->lag_oaa_size = lod->lod_ost_count;
2551         }
2552         if (bitmap) {
2553                 lag->lag_ost_avoid_bitmap = bitmap;
2554                 lag->lag_ost_avoid_size = lod->lod_ost_count;
2555         }
2556
2557         return 0;
2558 }
2559
2560 /**
2561  * Collect information of used OSTs and OSSs in the overlapped components
2562  * of other mirrors
2563  */
2564 void lod_collect_avoidance(struct lod_object *lo, struct lod_avoid_guide *lag,
2565                            int comp_idx)
2566 {
2567         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
2568         struct lod_layout_component *lod_comp = &lo->ldo_comp_entries[comp_idx];
2569         unsigned long *bitmap = lag->lag_ost_avoid_bitmap;
2570         int i, j;
2571
2572         /* iterate components */
2573         for (i = 0; i < lo->ldo_comp_cnt; i++) {
2574                 struct lod_layout_component *comp;
2575
2576                 /**
2577                  * skip mirror containing component[comp_idx], we only
2578                  * collect OSTs info of conflicting component in other mirrors,
2579                  * so that during read, if OSTs of a mirror's component are
2580                  * not available, we still have other mirror with different
2581                  * OSTs to read the data.
2582                  */
2583                 comp = &lo->ldo_comp_entries[i];
2584                 if (comp->llc_id != LCME_ID_INVAL &&
2585                     mirror_id_of(comp->llc_id) ==
2586                                                 mirror_id_of(lod_comp->llc_id))
2587                         continue;
2588
2589                 /**
2590                  * skip non-overlapped or un-instantiated components,
2591                  * NOTE: don't use lod_comp_inited(comp) to judge
2592                  * whether @comp has been inited, since during
2593                  * declare phase, comp->llc_stripe has been allocated
2594                  * while it's init flag not been set until the exec
2595                  * phase.
2596                  */
2597                 if (!lu_extent_is_overlapped(&comp->llc_extent,
2598                                              &lod_comp->llc_extent) ||
2599                     !comp->llc_stripe)
2600                         continue;
2601
2602                 /**
2603                  * collect used OSTs index and OSS info from a
2604                  * component
2605                  */
2606                 for (j = 0; j < comp->llc_stripe_count; j++) {
2607                         struct lod_tgt_desc *ost;
2608                         struct lu_svr_qos *lsq;
2609                         int k;
2610
2611                         ost = OST_TGT(lod, comp->llc_ost_indices[j]);
2612                         lsq = ost->ltd_qos.ltq_svr;
2613
2614                         if (test_bit(ost->ltd_index, bitmap))
2615                                 continue;
2616
2617                         QOS_DEBUG("OST%d used in conflicting mirror "
2618                                   "component\n", ost->ltd_index);
2619                         set_bit(ost->ltd_index, bitmap);
2620                         lag->lag_ost_avail--;
2621
2622                         for (k = 0; k < lag->lag_oaa_count; k++) {
2623                                 if (lag->lag_oss_avoid_array[k] ==
2624                                     lsq->lsq_id)
2625                                         break;
2626                         }
2627                         if (k == lag->lag_oaa_count) {
2628                                 lag->lag_oss_avoid_array[k] =
2629                                                         lsq->lsq_id;
2630                                 lag->lag_oaa_count++;
2631                         }
2632                 }
2633         }
2634 }
2635
2636 /**
2637  * Create a striping for an obejct.
2638  *
2639  * The function creates a new striping for the object. The function tries QoS
2640  * algorithm first unless free space is distributed evenly among OSTs, but
2641  * by default RR algorithm is preferred due to internal concurrency (QoS is
2642  * serialized). The caller must ensure no concurrent calls to the function
2643  * are made against the same object.
2644  *
2645  * \param[in] env       execution environment for this thread
2646  * \param[in] lo        LOD object
2647  * \param[in] attr      attributes OST objects will be declared with
2648  * \param[in] th        transaction handle
2649  * \param[in] comp_idx  index of ldo_comp_entries
2650  *
2651  * \retval 0            on success
2652  * \retval negative     negated errno on error
2653  */
2654 int lod_qos_prep_create(const struct lu_env *env, struct lod_object *lo,
2655                         struct lu_attr *attr, struct thandle *th,
2656                         int comp_idx, __u64 reserve)
2657 {
2658         struct lod_layout_component *lod_comp;
2659         struct lod_device      *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2660         int                     stripe_len;
2661         int                     flag = LOV_USES_ASSIGNED_STRIPE;
2662         int                     i, rc = 0;
2663         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
2664         struct dt_object **stripe = NULL;
2665         __u32 *ost_indices = NULL;
2666         ENTRY;
2667
2668         LASSERT(lo);
2669         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
2670         lod_comp = &lo->ldo_comp_entries[comp_idx];
2671         LASSERT(!(lod_comp->llc_flags & LCME_FL_EXTENSION));
2672
2673         /* A released component is being created */
2674         if (lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED)
2675                 RETURN(0);
2676
2677         /* A Data-on-MDT component is being created */
2678         if (lov_pattern(lod_comp->llc_pattern) == LOV_PATTERN_MDT)
2679                 RETURN(0);
2680
2681         if (lod_comp->llc_pool)
2682                 lod_check_and_spill_pool(env, d, &lod_comp->llc_pool);
2683
2684         if (likely(lod_comp->llc_stripe == NULL)) {
2685                 /*
2686                  * no striping has been created so far
2687                  */
2688                 LASSERT(lod_comp->llc_stripe_count);
2689                 /*
2690                  * statfs and check OST targets now, since ld_active_tgt_count
2691                  * could be changed if some OSTs are [de]activated manually.
2692                  */
2693                 lod_qos_statfs_update(env, d, &d->lod_ost_descs);
2694                 stripe_len = lod_get_stripe_count(d, lo, comp_idx,
2695                                                   lod_comp->llc_stripe_count,
2696                                                   lod_comp->llc_pattern &
2697                                                   LOV_PATTERN_OVERSTRIPING);
2698
2699                 if (stripe_len == 0)
2700                         GOTO(out, rc = -ERANGE);
2701                 lod_comp->llc_stripe_count = stripe_len;
2702                 OBD_ALLOC_PTR_ARRAY(stripe, stripe_len);
2703                 if (stripe == NULL)
2704                         GOTO(out, rc = -ENOMEM);
2705                 OBD_ALLOC_PTR_ARRAY(ost_indices, stripe_len);
2706                 if (!ost_indices)
2707                         GOTO(out, rc = -ENOMEM);
2708
2709 repeat:
2710                 lod_getref(&d->lod_ost_descs);
2711                 /* XXX: support for non-0 files w/o objects */
2712                 CDEBUG(D_OTHER, "tgt_count %d stripe_count %d\n",
2713                        d->lod_ost_count, stripe_len);
2714
2715                 if (lod_comp->llc_ostlist.op_array &&
2716                     lod_comp->llc_ostlist.op_count) {
2717                         rc = lod_alloc_ost_list(env, lo, stripe, ost_indices,
2718                                                 th, comp_idx, reserve);
2719                 } else if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT) {
2720                         /**
2721                          * collect OSTs and OSSs used in other mirrors whose
2722                          * components cross the ldo_comp_entries[comp_idx]
2723                          */
2724                         rc = lod_prepare_avoidance(env, lo);
2725                         if (rc)
2726                                 GOTO(put_ldts, rc);
2727
2728                         QOS_DEBUG("collecting conflict osts for comp[%d]\n",
2729                                   comp_idx);
2730                         lod_collect_avoidance(lo, lag, comp_idx);
2731
2732                         rc = lod_ost_alloc_qos(env, lo, stripe, ost_indices,
2733                                                flag, th, comp_idx, reserve);
2734                         if (rc == -EAGAIN)
2735                                 rc = lod_ost_alloc_rr(env, lo, stripe,
2736                                                       ost_indices, flag, th,
2737                                                       comp_idx, reserve);
2738                 } else {
2739                         rc = lod_ost_alloc_specific(env, lo, stripe,
2740                                                     ost_indices, flag, th,
2741                                                     comp_idx, reserve);
2742                 }
2743 put_ldts:
2744                 lod_putref(d, &d->lod_ost_descs);
2745                 if (rc < 0) {
2746                         for (i = 0; i < stripe_len; i++)
2747                                 if (stripe[i] != NULL)
2748                                         dt_object_put(env, stripe[i]);
2749
2750                         /* In case there is no space on any OST, let's ignore
2751                          * the @reserve space to avoid an error at the init
2752                          * time, probably the actual IO will be less than the
2753                          * given @reserve space (aka extension_size). */
2754                         if (reserve) {
2755                                 reserve = 0;
2756                                 goto repeat;
2757                         }
2758                         lod_comp->llc_stripe_count = 0;
2759                 } else {
2760                         lod_comp->llc_stripe = stripe;
2761                         lod_comp->llc_ost_indices = ost_indices;
2762                         lod_comp->llc_stripes_allocated = stripe_len;
2763                 }
2764         } else {
2765                 /*
2766                  * lod_qos_parse_config() found supplied buf as a predefined
2767                  * striping (not a hint), so it allocated all the object
2768                  * now we need to create them
2769                  */
2770                 for (i = 0; i < lod_comp->llc_stripe_count; i++) {
2771                         struct dt_object  *o;
2772
2773                         o = lod_comp->llc_stripe[i];
2774                         LASSERT(o);
2775
2776                         rc = lod_sub_declare_create(env, o, attr, NULL,
2777                                                     NULL, th);
2778                         if (rc < 0) {
2779                                 CERROR("can't declare create: %d\n", rc);
2780                                 break;
2781                         }
2782                 }
2783                 /**
2784                  * Clear LCME_FL_INIT for the component so that
2785                  * lod_striping_create() can create the striping objects
2786                  * in replay.
2787                  */
2788                 lod_comp_unset_init(lod_comp);
2789         }
2790
2791 out:
2792         if (rc < 0) {
2793                 if (stripe)
2794                         OBD_FREE_PTR_ARRAY(stripe, stripe_len);
2795                 if (ost_indices)
2796                         OBD_FREE_PTR_ARRAY(ost_indices, stripe_len);
2797         }
2798         RETURN(rc);
2799 }
2800
2801 int lod_prepare_create(const struct lu_env *env, struct lod_object *lo,
2802                        struct lu_attr *attr, const struct lu_buf *buf,
2803                        struct thandle *th)
2804
2805 {
2806         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2807         uint64_t size = 0;
2808         int i;
2809         int rc;
2810         ENTRY;
2811
2812         LASSERT(lo);
2813
2814         /* no OST available */
2815         /* XXX: should we be waiting a bit to prevent failures during
2816          * cluster initialization? */
2817         if (!d->lod_ost_count)
2818                 RETURN(-EIO);
2819
2820         /*
2821          * by this time, the object's ldo_stripe_count and ldo_stripe_size
2822          * contain default value for striping: taken from the parent
2823          * or from filesystem defaults
2824          *
2825          * in case the caller is passing lovea with new striping config,
2826          * we may need to parse lovea and apply new configuration
2827          */
2828         rc = lod_qos_parse_config(env, lo, buf);
2829         if (rc)
2830                 RETURN(rc);
2831
2832         if (attr->la_valid & LA_SIZE)
2833                 size = attr->la_size;
2834
2835         /**
2836          * prepare OST object creation for the component covering file's
2837          * size, the 1st component (including plain layout file) is always
2838          * instantiated.
2839          */
2840         for (i = 0; i < lo->ldo_comp_cnt; i++) {
2841                 struct lod_layout_component *lod_comp;
2842                 struct lu_extent *extent;
2843
2844                 lod_comp = &lo->ldo_comp_entries[i];
2845                 extent = &lod_comp->llc_extent;
2846                 QOS_DEBUG("comp[%d] %lld "DEXT"\n", i, size, PEXT(extent));
2847                 if (!lo->ldo_is_composite || size >= extent->e_start) {
2848                         rc = lod_qos_prep_create(env, lo, attr, th, i, 0);
2849                         if (rc)
2850                                 break;
2851                 }
2852         }
2853
2854         RETURN(rc);
2855 }