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