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