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