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