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