Whamcloud - gitweb
LU-9019 libcfs: remove cfs_time_XXX_64 wrappers
[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 <libcfs/libcfs.h>
42 #include <uapi/linux/lustre/lustre_idl.h>
43 #include <lustre_swab.h>
44 #include <obd_class.h>
45
46 #include "lod_internal.h"
47
48 /*
49  * force QoS policy (not RR) to be used for testing purposes
50  */
51 #define FORCE_QOS_
52
53 #define D_QOS   D_OTHER
54
55 #define QOS_DEBUG(fmt, ...)     CDEBUG(D_QOS, fmt, ## __VA_ARGS__)
56 #define QOS_CONSOLE(fmt, ...)   LCONSOLE(D_QOS, fmt, ## __VA_ARGS__)
57
58 #define TGT_BAVAIL(i) (OST_TGT(lod,i)->ltd_statfs.os_bavail * \
59                        OST_TGT(lod,i)->ltd_statfs.os_bsize)
60
61 /**
62  * Add a new target to Quality of Service (QoS) target table.
63  *
64  * Add a new OST target to the structure representing an OSS. Resort the list
65  * of known OSSs by the number of OSTs attached to each OSS. The OSS list is
66  * protected internally and no external locking is required.
67  *
68  * \param[in] lod               LOD device
69  * \param[in] ost_desc          OST description
70  *
71  * \retval 0                    on success
72  * \retval -ENOMEM              on error
73  */
74 int qos_add_tgt(struct lod_device *lod, struct lod_tgt_desc *ost_desc)
75 {
76         struct lod_qos_oss *oss = NULL, *temposs;
77         struct obd_export  *exp = ost_desc->ltd_exp;
78         int                 rc = 0, found = 0;
79         struct list_head   *list;
80         ENTRY;
81
82         down_write(&lod->lod_qos.lq_rw_sem);
83         /*
84          * a bit hacky approach to learn NID of corresponding connection
85          * but there is no official API to access information like this
86          * with OSD API.
87          */
88         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
89                 if (obd_uuid_equals(&oss->lqo_uuid,
90                                     &exp->exp_connection->c_remote_uuid)) {
91                         found++;
92                         break;
93                 }
94         }
95
96         if (!found) {
97                 OBD_ALLOC_PTR(oss);
98                 if (!oss)
99                         GOTO(out, rc = -ENOMEM);
100                 memcpy(&oss->lqo_uuid, &exp->exp_connection->c_remote_uuid,
101                        sizeof(oss->lqo_uuid));
102         } else {
103                 /* Assume we have to move this one */
104                 list_del(&oss->lqo_oss_list);
105         }
106
107         oss->lqo_ost_count++;
108         ost_desc->ltd_qos.ltq_oss = oss;
109
110         CDEBUG(D_QOS, "add tgt %s to OSS %s (%d OSTs)\n",
111                obd_uuid2str(&ost_desc->ltd_uuid), obd_uuid2str(&oss->lqo_uuid),
112                oss->lqo_ost_count);
113
114         /* Add sorted by # of OSTs.  Find the first entry that we're
115            bigger than... */
116         list = &lod->lod_qos.lq_oss_list;
117         list_for_each_entry(temposs, list, lqo_oss_list) {
118                 if (oss->lqo_ost_count > temposs->lqo_ost_count)
119                         break;
120         }
121         /* ...and add before it.  If we're the first or smallest, temposs
122            points to the list head, and we add to the end. */
123         list_add_tail(&oss->lqo_oss_list, &temposs->lqo_oss_list);
124
125         lod->lod_qos.lq_dirty = 1;
126         lod->lod_qos.lq_rr.lqr_dirty = 1;
127
128 out:
129         up_write(&lod->lod_qos.lq_rw_sem);
130         RETURN(rc);
131 }
132
133 /**
134  * Remove OST target from QoS table.
135  *
136  * Removes given OST target from QoS table and releases related OSS structure
137  * if no OSTs remain on the OSS.
138  *
139  * \param[in] lod               LOD device
140  * \param[in] ost_desc          OST description
141  *
142  * \retval 0                    on success
143  * \retval -ENOENT              if no OSS was found
144  */
145 int qos_del_tgt(struct lod_device *lod, struct lod_tgt_desc *ost_desc)
146 {
147         struct lod_qos_oss *oss;
148         int                 rc = 0;
149         ENTRY;
150
151         down_write(&lod->lod_qos.lq_rw_sem);
152         oss = ost_desc->ltd_qos.ltq_oss;
153         if (!oss)
154                 GOTO(out, rc = -ENOENT);
155
156         oss->lqo_ost_count--;
157         if (oss->lqo_ost_count == 0) {
158                 CDEBUG(D_QOS, "removing OSS %s\n",
159                        obd_uuid2str(&oss->lqo_uuid));
160                 list_del(&oss->lqo_oss_list);
161                 ost_desc->ltd_qos.ltq_oss = NULL;
162                 OBD_FREE_PTR(oss);
163         }
164
165         lod->lod_qos.lq_dirty = 1;
166         lod->lod_qos.lq_rr.lqr_dirty = 1;
167 out:
168         up_write(&lod->lod_qos.lq_rw_sem);
169         RETURN(rc);
170 }
171
172 /**
173  * Check whether the target is available for new OST objects.
174  *
175  * Request statfs data from the given target and verify it's active and not
176  * read-only. If so, then it can be used to place new OST objects. This
177  * function also maintains the number of active/inactive targets and sets
178  * dirty flags if those numbers change so others can run re-balance procedures.
179  * No external locking is required.
180  *
181  * \param[in] env       execution environment for this thread
182  * \param[in] d         LOD device
183  * \param[in] index     index of OST target to check
184  * \param[out] sfs      buffer for statfs data
185  *
186  * \retval 0            if the target is good
187  * \retval negative     negated errno on error
188
189  */
190 static int lod_statfs_and_check(const struct lu_env *env, struct lod_device *d,
191                                 int index, struct obd_statfs *sfs)
192 {
193         struct lod_tgt_desc *ost;
194         int                  rc;
195         ENTRY;
196
197         LASSERT(d);
198         ost = OST_TGT(d,index);
199         LASSERT(ost);
200
201         rc = dt_statfs(env, ost->ltd_ost, sfs);
202
203         if (rc == 0 && ((sfs->os_state & OS_STATE_ENOSPC) ||
204             (sfs->os_state & OS_STATE_ENOINO && sfs->os_fprecreated == 0)))
205                 RETURN(-ENOSPC);
206
207         if (rc && rc != -ENOTCONN)
208                 CERROR("%s: statfs: rc = %d\n", lod2obd(d)->obd_name, rc);
209
210         /* If the OST is readonly then we can't allocate objects there */
211         if (sfs->os_state & OS_STATE_READONLY)
212                 rc = -EROFS;
213
214         /* check whether device has changed state (active, inactive) */
215         if (rc != 0 && ost->ltd_active) {
216                 /* turned inactive? */
217                 spin_lock(&d->lod_lock);
218                 if (ost->ltd_active) {
219                         ost->ltd_active = 0;
220                         if (rc == -ENOTCONN)
221                                 ost->ltd_connecting = 1;
222
223                         LASSERT(d->lod_desc.ld_active_tgt_count > 0);
224                         d->lod_desc.ld_active_tgt_count--;
225                         d->lod_qos.lq_dirty = 1;
226                         d->lod_qos.lq_rr.lqr_dirty = 1;
227                         CDEBUG(D_CONFIG, "%s: turns inactive\n",
228                                ost->ltd_exp->exp_obd->obd_name);
229                 }
230                 spin_unlock(&d->lod_lock);
231         } else if (rc == 0 && ost->ltd_active == 0) {
232                 /* turned active? */
233                 LASSERTF(d->lod_desc.ld_active_tgt_count < d->lod_ostnr,
234                          "active tgt count %d, ost nr %d\n",
235                          d->lod_desc.ld_active_tgt_count, d->lod_ostnr);
236                 spin_lock(&d->lod_lock);
237                 if (ost->ltd_active == 0) {
238                         ost->ltd_active = 1;
239                         ost->ltd_connecting = 0;
240                         d->lod_desc.ld_active_tgt_count++;
241                         d->lod_qos.lq_dirty = 1;
242                         d->lod_qos.lq_rr.lqr_dirty = 1;
243                         CDEBUG(D_CONFIG, "%s: turns active\n",
244                                ost->ltd_exp->exp_obd->obd_name);
245                 }
246                 spin_unlock(&d->lod_lock);
247         }
248
249         RETURN(rc);
250 }
251
252 /**
253  * Maintain per-target statfs data.
254  *
255  * The function refreshes statfs data for all the targets every N seconds.
256  * The actual N is controlled via procfs and set to LOV_DESC_QOS_MAXAGE_DEFAULT
257  * initially.
258  *
259  * \param[in] env       execution environment for this thread
260  * \param[in] lod       LOD device
261  */
262 static void lod_qos_statfs_update(const struct lu_env *env,
263                                   struct lod_device *lod)
264 {
265         struct obd_device *obd = lod2obd(lod);
266         struct ost_pool *osts = &(lod->lod_pool_info);
267         time64_t max_age;
268         unsigned int i;
269         u64 avail;
270         int idx;
271         ENTRY;
272
273         max_age = ktime_get_seconds() - 2 * lod->lod_desc.ld_qos_maxage;
274
275         if (obd->obd_osfs_age > max_age)
276                 /* statfs data are quite recent, don't need to refresh it */
277                 RETURN_EXIT;
278
279         down_write(&lod->lod_qos.lq_rw_sem);
280         if (max_age <= obd->obd_osfs_age)
281                 goto out;
282
283         for (i = 0; i < osts->op_count; i++) {
284                 idx = osts->op_array[i];
285                 avail = OST_TGT(lod,idx)->ltd_statfs.os_bavail;
286                 if (lod_statfs_and_check(env, lod, idx,
287                                          &OST_TGT(lod, idx)->ltd_statfs))
288                         continue;
289                 if (OST_TGT(lod,idx)->ltd_statfs.os_bavail != avail)
290                         /* recalculate weigths */
291                         lod->lod_qos.lq_dirty = 1;
292         }
293         obd->obd_osfs_age = ktime_get_seconds();
294
295 out:
296         up_write(&lod->lod_qos.lq_rw_sem);
297         EXIT;
298 }
299
300 /**
301  * Calculate per-OST and per-OSS penalties
302  *
303  * Re-calculate penalties when the configuration changes, active targets
304  * change and after statfs refresh (all these are reflected by lq_dirty flag).
305  * On every OST and OSS: decay the penalty by half for every 8x the update
306  * interval that the device has been idle. That gives lots of time for the
307  * statfs information to be updated (which the penalty is only a proxy for),
308  * and avoids penalizing OSS/OSTs under light load.
309  * See lod_qos_calc_weight() for how penalties are factored into the weight.
310  *
311  * \param[in] lod       LOD device
312  *
313  * \retval 0            on success
314  * \retval -EAGAIN      the number of OSTs isn't enough
315  */
316 static int lod_qos_calc_ppo(struct lod_device *lod)
317 {
318         struct lod_qos_oss *oss;
319         __u64               ba_max, ba_min, temp;
320         __u32               num_active;
321         unsigned int        i;
322         int                 rc, prio_wide;
323         time_t              now, age;
324         ENTRY;
325
326         if (!lod->lod_qos.lq_dirty)
327                 GOTO(out, rc = 0);
328
329         num_active = lod->lod_desc.ld_active_tgt_count - 1;
330         if (num_active < 1)
331                 GOTO(out, rc = -EAGAIN);
332
333         /* find bavail on each OSS */
334         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list)
335                             oss->lqo_bavail = 0;
336         lod->lod_qos.lq_active_oss_count = 0;
337
338         /*
339          * How badly user wants to select OSTs "widely" (not recently chosen
340          * and not on recent OSS's).  As opposed to "freely" (free space
341          * avail.) 0-256
342          */
343         prio_wide = 256 - lod->lod_qos.lq_prio_free;
344
345         ba_min = (__u64)(-1);
346         ba_max = 0;
347         now = cfs_time_current_sec();
348         /* Calculate OST penalty per object
349          * (lod ref taken in lod_qos_prep_create()) */
350         cfs_foreach_bit(lod->lod_ost_bitmap, i) {
351                 LASSERT(OST_TGT(lod,i));
352                 temp = TGT_BAVAIL(i);
353                 if (!temp)
354                         continue;
355                 ba_min = min(temp, ba_min);
356                 ba_max = max(temp, ba_max);
357
358                 /* Count the number of usable OSS's */
359                 if (OST_TGT(lod,i)->ltd_qos.ltq_oss->lqo_bavail == 0)
360                         lod->lod_qos.lq_active_oss_count++;
361                 OST_TGT(lod,i)->ltd_qos.ltq_oss->lqo_bavail += temp;
362
363                 /* per-OST penalty is prio * TGT_bavail / (num_ost - 1) / 2 */
364                 temp >>= 1;
365                 do_div(temp, num_active);
366                 OST_TGT(lod,i)->ltd_qos.ltq_penalty_per_obj =
367                         (temp * prio_wide) >> 8;
368
369                 age = (now - OST_TGT(lod,i)->ltd_qos.ltq_used) >> 3;
370                 if (lod->lod_qos.lq_reset ||
371                     age > 32 * lod->lod_desc.ld_qos_maxage)
372                         OST_TGT(lod,i)->ltd_qos.ltq_penalty = 0;
373                 else if (age > lod->lod_desc.ld_qos_maxage)
374                         /* Decay OST penalty. */
375                         OST_TGT(lod,i)->ltd_qos.ltq_penalty >>=
376                                 (age / lod->lod_desc.ld_qos_maxage);
377         }
378
379         num_active = lod->lod_qos.lq_active_oss_count - 1;
380         if (num_active < 1) {
381                 /* If there's only 1 OSS, we can't penalize it, so instead
382                    we have to double the OST penalty */
383                 num_active = 1;
384                 cfs_foreach_bit(lod->lod_ost_bitmap, i)
385                         OST_TGT(lod,i)->ltd_qos.ltq_penalty_per_obj <<= 1;
386         }
387
388         /* Per-OSS penalty is prio * oss_avail / oss_osts / (num_oss - 1) / 2 */
389         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
390                 temp = oss->lqo_bavail >> 1;
391                 do_div(temp, oss->lqo_ost_count * num_active);
392                 oss->lqo_penalty_per_obj = (temp * prio_wide) >> 8;
393
394                 age = (now - oss->lqo_used) >> 3;
395                 if (lod->lod_qos.lq_reset ||
396                     age > 32 * lod->lod_desc.ld_qos_maxage)
397                         oss->lqo_penalty = 0;
398                 else if (age > lod->lod_desc.ld_qos_maxage)
399                         /* Decay OSS penalty. */
400                         oss->lqo_penalty >>= age / lod->lod_desc.ld_qos_maxage;
401         }
402
403         lod->lod_qos.lq_dirty = 0;
404         lod->lod_qos.lq_reset = 0;
405
406         /* If each ost has almost same free space,
407          * do rr allocation for better creation performance */
408         lod->lod_qos.lq_same_space = 0;
409         if ((ba_max * (256 - lod->lod_qos.lq_threshold_rr)) >> 8 < ba_min) {
410                 lod->lod_qos.lq_same_space = 1;
411                 /* Reset weights for the next time we enter qos mode */
412                 lod->lod_qos.lq_reset = 1;
413         }
414         rc = 0;
415
416 out:
417 #ifndef FORCE_QOS
418         if (!rc && lod->lod_qos.lq_same_space)
419                 RETURN(-EAGAIN);
420 #endif
421         RETURN(rc);
422 }
423
424 /**
425  * Calculate weight for a given OST target.
426  *
427  * The final OST weight is the number of bytes available minus the OST and
428  * OSS penalties.  See lod_qos_calc_ppo() for how penalties are calculated.
429  *
430  * \param[in] lod       LOD device, where OST targets are listed
431  * \param[in] i         OST target index
432  *
433  * \retval              0
434  */
435 static int lod_qos_calc_weight(struct lod_device *lod, int i)
436 {
437         __u64 temp, temp2;
438
439         temp = TGT_BAVAIL(i);
440         temp2 = OST_TGT(lod,i)->ltd_qos.ltq_penalty +
441                 OST_TGT(lod,i)->ltd_qos.ltq_oss->lqo_penalty;
442         if (temp < temp2)
443                 OST_TGT(lod,i)->ltd_qos.ltq_weight = 0;
444         else
445                 OST_TGT(lod,i)->ltd_qos.ltq_weight = temp - temp2;
446         return 0;
447 }
448
449 /**
450  * Re-calculate weights.
451  *
452  * The function is called when some OST target was used for a new object. In
453  * this case we should re-calculate all the weights to keep new allocations
454  * balanced well.
455  *
456  * \param[in] lod       LOD device
457  * \param[in] osts      OST pool where a new object was placed
458  * \param[in] index     OST target where a new object was placed
459  * \param[out] total_wt new total weight for the pool
460  *
461  * \retval              0
462  */
463 static int lod_qos_used(struct lod_device *lod, struct ost_pool *osts,
464                         __u32 index, __u64 *total_wt)
465 {
466         struct lod_tgt_desc *ost;
467         struct lod_qos_oss  *oss;
468         unsigned int j;
469         ENTRY;
470
471         ost = OST_TGT(lod,index);
472         LASSERT(ost);
473
474         /* Don't allocate on this devuce anymore, until the next alloc_qos */
475         ost->ltd_qos.ltq_usable = 0;
476
477         oss = ost->ltd_qos.ltq_oss;
478
479         /* Decay old penalty by half (we're adding max penalty, and don't
480            want it to run away.) */
481         ost->ltd_qos.ltq_penalty >>= 1;
482         oss->lqo_penalty >>= 1;
483
484         /* mark the OSS and OST as recently used */
485         ost->ltd_qos.ltq_used = oss->lqo_used = cfs_time_current_sec();
486
487         /* Set max penalties for this OST and OSS */
488         ost->ltd_qos.ltq_penalty +=
489                 ost->ltd_qos.ltq_penalty_per_obj * lod->lod_ostnr;
490         oss->lqo_penalty += oss->lqo_penalty_per_obj *
491                 lod->lod_qos.lq_active_oss_count;
492
493         /* Decrease all OSS penalties */
494         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
495                 if (oss->lqo_penalty < oss->lqo_penalty_per_obj)
496                         oss->lqo_penalty = 0;
497                 else
498                         oss->lqo_penalty -= oss->lqo_penalty_per_obj;
499         }
500
501         *total_wt = 0;
502         /* Decrease all OST penalties */
503         for (j = 0; j < osts->op_count; j++) {
504                 int i;
505
506                 i = osts->op_array[j];
507                 if (!cfs_bitmap_check(lod->lod_ost_bitmap, i))
508                         continue;
509
510                 ost = OST_TGT(lod,i);
511                 LASSERT(ost);
512
513                 if (ost->ltd_qos.ltq_penalty <
514                                 ost->ltd_qos.ltq_penalty_per_obj)
515                         ost->ltd_qos.ltq_penalty = 0;
516                 else
517                         ost->ltd_qos.ltq_penalty -=
518                                 ost->ltd_qos.ltq_penalty_per_obj;
519
520                 lod_qos_calc_weight(lod, i);
521
522                 /* Recalc the total weight of usable osts */
523                 if (ost->ltd_qos.ltq_usable)
524                         *total_wt += ost->ltd_qos.ltq_weight;
525
526                 QOS_DEBUG("recalc tgt %d usable=%d avail=%llu"
527                           " ostppo=%llu ostp=%llu ossppo=%llu"
528                           " ossp=%llu wt=%llu\n",
529                           i, ost->ltd_qos.ltq_usable, TGT_BAVAIL(i) >> 10,
530                           ost->ltd_qos.ltq_penalty_per_obj >> 10,
531                           ost->ltd_qos.ltq_penalty >> 10,
532                           ost->ltd_qos.ltq_oss->lqo_penalty_per_obj >> 10,
533                           ost->ltd_qos.ltq_oss->lqo_penalty >> 10,
534                           ost->ltd_qos.ltq_weight >> 10);
535         }
536
537         RETURN(0);
538 }
539
540 void lod_qos_rr_init(struct lod_qos_rr *lqr)
541 {
542         spin_lock_init(&lqr->lqr_alloc);
543         lqr->lqr_dirty = 1;
544 }
545
546
547 #define LOV_QOS_EMPTY ((__u32)-1)
548
549 /**
550  * Calculate optimal round-robin order with regard to OSSes.
551  *
552  * Place all the OSTs from pool \a src_pool in a special array to be used for
553  * round-robin (RR) stripe allocation.  The placement algorithm interleaves
554  * OSTs from the different OSSs so that RR allocation can balance OSSs evenly.
555  * Resorts the targets when the number of active targets changes (because of
556  * a new target or activation/deactivation).
557  *
558  * \param[in] lod       LOD device
559  * \param[in] src_pool  OST pool
560  * \param[in] lqr       round-robin list
561  *
562  * \retval 0            on success
563  * \retval -ENOMEM      fails to allocate the array
564  */
565 static int lod_qos_calc_rr(struct lod_device *lod, struct ost_pool *src_pool,
566                            struct lod_qos_rr *lqr)
567 {
568         struct lod_qos_oss  *oss;
569         struct lod_tgt_desc *ost;
570         unsigned placed, real_count;
571         unsigned int i;
572         int rc;
573         ENTRY;
574
575         if (!lqr->lqr_dirty) {
576                 LASSERT(lqr->lqr_pool.op_size);
577                 RETURN(0);
578         }
579
580         /* Do actual allocation. */
581         down_write(&lod->lod_qos.lq_rw_sem);
582
583         /*
584          * Check again. While we were sleeping on @lq_rw_sem something could
585          * change.
586          */
587         if (!lqr->lqr_dirty) {
588                 LASSERT(lqr->lqr_pool.op_size);
589                 up_write(&lod->lod_qos.lq_rw_sem);
590                 RETURN(0);
591         }
592
593         real_count = src_pool->op_count;
594
595         /* Zero the pool array */
596         /* alloc_rr is holding a read lock on the pool, so nobody is adding/
597            deleting from the pool. The lq_rw_sem insures that nobody else
598            is reading. */
599         lqr->lqr_pool.op_count = real_count;
600         rc = lod_ost_pool_extend(&lqr->lqr_pool, real_count);
601         if (rc) {
602                 up_write(&lod->lod_qos.lq_rw_sem);
603                 RETURN(rc);
604         }
605         for (i = 0; i < lqr->lqr_pool.op_count; i++)
606                 lqr->lqr_pool.op_array[i] = LOV_QOS_EMPTY;
607
608         /* Place all the OSTs from 1 OSS at the same time. */
609         placed = 0;
610         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
611                 int j = 0;
612
613                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
614                         int next;
615
616                         if (!cfs_bitmap_check(lod->lod_ost_bitmap,
617                                                 src_pool->op_array[i]))
618                                 continue;
619
620                         ost = OST_TGT(lod,src_pool->op_array[i]);
621                         LASSERT(ost && ost->ltd_ost);
622                         if (ost->ltd_qos.ltq_oss != oss)
623                                 continue;
624
625                         /* Evenly space these OSTs across arrayspace */
626                         next = j * lqr->lqr_pool.op_count / oss->lqo_ost_count;
627                         while (lqr->lqr_pool.op_array[next] != LOV_QOS_EMPTY)
628                                 next = (next + 1) % lqr->lqr_pool.op_count;
629
630                         lqr->lqr_pool.op_array[next] = src_pool->op_array[i];
631                         j++;
632                         placed++;
633                 }
634         }
635
636         lqr->lqr_dirty = 0;
637         up_write(&lod->lod_qos.lq_rw_sem);
638
639         if (placed != real_count) {
640                 /* This should never happen */
641                 LCONSOLE_ERROR_MSG(0x14e, "Failed to place all OSTs in the "
642                                    "round-robin list (%d of %d).\n",
643                                    placed, real_count);
644                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
645                         LCONSOLE(D_WARNING, "rr #%d ost idx=%d\n", i,
646                                  lqr->lqr_pool.op_array[i]);
647                 }
648                 lqr->lqr_dirty = 1;
649                 RETURN(-EAGAIN);
650         }
651
652 #if 0
653         for (i = 0; i < lqr->lqr_pool.op_count; i++)
654                 QOS_CONSOLE("rr #%d ost idx=%d\n", i, lqr->lqr_pool.op_array[i]);
655 #endif
656
657         RETURN(0);
658 }
659
660 /**
661  * Instantiate and declare creation of a new object.
662  *
663  * The function instantiates LU representation for a new object on the
664  * specified device. Also it declares an intention to create that
665  * object on the storage target.
666  *
667  * Note lu_object_anon() is used which is a trick with regard to LU/OSD
668  * infrastructure - in the existing precreation framework we can't assign FID
669  * at this moment, we do this later once a transaction is started. So the
670  * special method instantiates FID-less object in the cache and later it
671  * will get a FID and proper placement in LU cache.
672  *
673  * \param[in] env       execution environment for this thread
674  * \param[in] d         LOD device
675  * \param[in] ost_idx   OST target index where the object is being created
676  * \param[in] th        transaction handle
677  *
678  * \retval              object ptr on success, ERR_PTR() otherwise
679  */
680 static struct dt_object *lod_qos_declare_object_on(const struct lu_env *env,
681                                                    struct lod_device *d,
682                                                    __u32 ost_idx,
683                                                    struct thandle *th)
684 {
685         struct lod_tgt_desc *ost;
686         struct lu_object *o, *n;
687         struct lu_device *nd;
688         struct dt_object *dt;
689         int               rc;
690         ENTRY;
691
692         LASSERT(d);
693         LASSERT(ost_idx < d->lod_osts_size);
694         ost = OST_TGT(d,ost_idx);
695         LASSERT(ost);
696         LASSERT(ost->ltd_ost);
697
698         nd = &ost->ltd_ost->dd_lu_dev;
699
700         /*
701          * allocate anonymous object with zero fid, real fid
702          * will be assigned by OSP within transaction
703          * XXX: to be fixed with fully-functional OST fids
704          */
705         o = lu_object_anon(env, nd, NULL);
706         if (IS_ERR(o))
707                 GOTO(out, dt = ERR_PTR(PTR_ERR(o)));
708
709         n = lu_object_locate(o->lo_header, nd->ld_type);
710         if (unlikely(n == NULL)) {
711                 CERROR("can't find slice\n");
712                 lu_object_put(env, o);
713                 GOTO(out, dt = ERR_PTR(-EINVAL));
714         }
715
716         dt = container_of(n, struct dt_object, do_lu);
717
718         rc = lod_sub_declare_create(env, dt, NULL, NULL, NULL, th);
719         if (rc < 0) {
720                 CDEBUG(D_OTHER, "can't declare creation on #%u: %d\n",
721                        ost_idx, rc);
722                 lu_object_put(env, o);
723                 dt = ERR_PTR(rc);
724         }
725
726 out:
727         RETURN(dt);
728 }
729
730 /**
731  * Calculate a minimum acceptable stripe count.
732  *
733  * Return an acceptable stripe count depending on flag LOV_USES_DEFAULT_STRIPE:
734  * all stripes or 3/4 of stripes.
735  *
736  * \param[in] stripe_count      number of stripes requested
737  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
738  *
739  * \retval                      acceptable stripecount
740  */
741 static int min_stripe_count(__u32 stripe_count, int flags)
742 {
743         return (flags & LOV_USES_DEFAULT_STRIPE ?
744                 stripe_count - (stripe_count / 4) : stripe_count);
745 }
746
747 #define LOV_CREATE_RESEED_MULT 30
748 #define LOV_CREATE_RESEED_MIN  2000
749
750 /**
751  * Initialize temporary OST-in-use array.
752  *
753  * Allocate or extend the array used to mark targets already assigned to a new
754  * striping so they are not used more than once.
755  *
756  * \param[in] env       execution environment for this thread
757  * \param[in] stripes   number of items needed in the array
758  *
759  * \retval 0            on success
760  * \retval -ENOMEM      on error
761  */
762 static inline int lod_qos_ost_in_use_clear(const struct lu_env *env,
763                                            __u32 stripes)
764 {
765         struct lod_thread_info *info = lod_env_info(env);
766
767         if (info->lti_ea_store_size < sizeof(int) * stripes)
768                 lod_ea_store_resize(info, stripes * sizeof(int));
769         if (info->lti_ea_store_size < sizeof(int) * stripes) {
770                 CERROR("can't allocate memory for ost-in-use array\n");
771                 return -ENOMEM;
772         }
773         memset(info->lti_ea_store, -1, sizeof(int) * stripes);
774         return 0;
775 }
776
777 /**
778  * Remember a target in the array of used targets.
779  *
780  * Mark the given target as used for a new striping being created. The status
781  * of an OST in a striping can be checked with lod_qos_is_ost_used().
782  *
783  * \param[in] env       execution environment for this thread
784  * \param[in] idx       index in the array
785  * \param[in] ost       OST target index to mark as used
786  */
787 static inline void lod_qos_ost_in_use(const struct lu_env *env,
788                                       int idx, int ost)
789 {
790         struct lod_thread_info *info = lod_env_info(env);
791         int *osts = info->lti_ea_store;
792
793         LASSERT(info->lti_ea_store_size >= idx * sizeof(int));
794         osts[idx] = ost;
795 }
796
797 /**
798  * Check is OST used in a striping.
799  *
800  * Checks whether OST with the given index is marked as used in the temporary
801  * array (see lod_qos_ost_in_use()).
802  *
803  * \param[in] env       execution environment for this thread
804  * \param[in] ost       OST target index to check
805  * \param[in] stripes   the number of items used in the array already
806  *
807  * \retval 0            not used
808  * \retval 1            used
809  */
810 static int lod_qos_is_ost_used(const struct lu_env *env, int ost, __u32 stripes)
811 {
812         struct lod_thread_info *info = lod_env_info(env);
813         int *osts = info->lti_ea_store;
814         __u32 j;
815
816         for (j = 0; j < stripes; j++) {
817                 if (osts[j] == ost)
818                         return 1;
819         }
820         return 0;
821 }
822
823 /**
824  * Check is OST used in a composite layout
825  *
826  * \param[in] inuse     all inuse ost indexs
827  * \param[in] ost       OST target index to check
828  *
829  * \retval 0            not used
830  * \retval 1            used
831  */
832 static inline int lod_comp_is_ost_used(struct ost_pool *inuse, int ost)
833 {
834         __u32 j;
835         LASSERT(inuse != NULL);
836
837         if (inuse->op_size == 0)
838                 return 0;
839
840         LASSERT(inuse->op_count * sizeof(inuse->op_array[0]) <= inuse->op_size);
841         for (j = 0; j < inuse->op_count; j++) {
842                 if (inuse->op_array[j] == ost)
843                         return 1;
844         }
845         return 0;
846 }
847
848 /**
849  * Mark the given target as used for a composite layout
850  *
851  * \param[in] inuse     inuse ost index array
852  * \param[in] idx       index in the array
853  */
854 static inline void lod_comp_ost_in_use(struct ost_pool *inuse, int ost)
855 {
856         LASSERT(inuse != NULL);
857         if (inuse->op_size && !lod_comp_is_ost_used(inuse, ost)) {
858                 LASSERTF(inuse->op_count * sizeof(inuse->op_array[0]) <
859                          inuse->op_size,
860                          "count %d size %u", inuse->op_count, inuse->op_size);
861                 inuse->op_array[inuse->op_count] = ost;
862                 inuse->op_count++;
863         }
864 }
865
866 static int lod_check_and_reserve_ost(const struct lu_env *env,
867                                      struct lod_device *m,
868                                      struct obd_statfs *sfs, __u32 ost_idx,
869                                      __u32 speed, __u32 *s_idx,
870                                      struct dt_object **stripe,
871                                      struct thandle *th,
872                                      struct ost_pool *inuse)
873 {
874         struct dt_object   *o;
875         __u32 stripe_idx = *s_idx;
876         int rc;
877
878         rc = lod_statfs_and_check(env, m, ost_idx, sfs);
879         if (rc) {
880                 /* this OSP doesn't feel well */
881                 goto out_return;
882         }
883
884         /*
885          * We expect number of precreated objects in f_ffree at
886          * the first iteration, skip OSPs with no objects ready
887          */
888         if (sfs->os_fprecreated == 0 && speed == 0) {
889                 QOS_DEBUG("#%d: precreation is empty\n", ost_idx);
890                 goto out_return;
891         }
892
893         /*
894          * try to use another OSP if this one is degraded
895          */
896         if (sfs->os_state & OS_STATE_DEGRADED && speed < 2) {
897                 QOS_DEBUG("#%d: degraded\n", ost_idx);
898                 goto out_return;
899         }
900
901         /*
902          * try not allocate on OST which has been used by other
903          * component
904          */
905         if (speed == 0 && lod_comp_is_ost_used(inuse, ost_idx)) {
906                 QOS_DEBUG("#%d: used by other component\n", ost_idx);
907                 goto out_return;
908         }
909
910         /*
911          * do not put >1 objects on a single OST
912          */
913         if (lod_qos_is_ost_used(env, ost_idx, stripe_idx))
914                 goto out_return;
915
916         o = lod_qos_declare_object_on(env, m, ost_idx, th);
917         if (IS_ERR(o)) {
918                 CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
919                        ost_idx, (int) PTR_ERR(o));
920                 rc = PTR_ERR(o);
921                 goto out_return;
922         }
923
924         /*
925          * We've successfully declared (reserved) an object
926          */
927         lod_qos_ost_in_use(env, stripe_idx, ost_idx);
928         lod_comp_ost_in_use(inuse, ost_idx);
929         stripe[stripe_idx] = o;
930         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_LOV_CREATE_RACE, 2);
931         stripe_idx++;
932         *s_idx = stripe_idx;
933
934 out_return:
935         return rc;
936 }
937
938 /**
939  * Allocate a striping using round-robin algorithm.
940  *
941  * Allocates a new striping using round-robin algorithm. The function refreshes
942  * all the internal structures (statfs cache, array of available OSTs sorted
943  * with regard to OSS, etc). The number of stripes required is taken from the
944  * object (must be prepared by the caller), but can change if the flag
945  * LOV_USES_DEFAULT_STRIPE is supplied. The caller should ensure nobody else
946  * is trying to create a striping on the object in parallel. All the internal
947  * structures (like pools, etc) are protected and no additional locking is
948  * required. The function succeeds even if a single stripe is allocated. To save
949  * time we give priority to targets which already have objects precreated.
950  * Full OSTs are skipped (see lod_qos_dev_is_full() for the details).
951  *
952  * \param[in] env       execution environment for this thread
953  * \param[in] lo        LOD object
954  * \param[out] stripe   striping created
955  * \param[in] flags     allocation flags (0 or LOV_USES_DEFAULT_STRIPE)
956  * \param[in] th        transaction handle
957  * \param[in] comp_idx  index of ldo_comp_entries
958  * \param[in|out] inuse array of inuse ost index
959  *
960  * \retval 0            on success
961  * \retval -ENOSPC      if not enough OSTs are found
962  * \retval negative     negated errno for other failures
963  */
964 static int lod_alloc_rr(const struct lu_env *env, struct lod_object *lo,
965                         struct dt_object **stripe, int flags,
966                         struct thandle *th, int comp_idx,
967                         struct ost_pool *inuse)
968 {
969         struct lod_layout_component *lod_comp;
970         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
971         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
972         struct pool_desc  *pool = NULL;
973         struct ost_pool   *osts;
974         struct lod_qos_rr *lqr;
975         unsigned int    i, array_idx;
976         __u32 ost_start_idx_temp;
977         __u32 stripe_idx = 0;
978         __u32 stripe_count, stripe_count_min, ost_idx;
979         int rc, speed = 0, ost_connecting = 0;
980         ENTRY;
981
982         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
983         lod_comp = &lo->ldo_comp_entries[comp_idx];
984         stripe_count = lod_comp->llc_stripe_count;
985         stripe_count_min = min_stripe_count(stripe_count, flags);
986
987         if (lod_comp->llc_pool != NULL)
988                 pool = lod_find_pool(m, lod_comp->llc_pool);
989
990         if (pool != NULL) {
991                 down_read(&pool_tgt_rw_sem(pool));
992                 osts = &(pool->pool_obds);
993                 lqr = &(pool->pool_rr);
994         } else {
995                 osts = &(m->lod_pool_info);
996                 lqr = &(m->lod_qos.lq_rr);
997         }
998
999         rc = lod_qos_calc_rr(m, osts, lqr);
1000         if (rc)
1001                 GOTO(out, rc);
1002
1003         rc = lod_qos_ost_in_use_clear(env, stripe_count);
1004         if (rc)
1005                 GOTO(out, rc);
1006
1007         down_read(&m->lod_qos.lq_rw_sem);
1008         spin_lock(&lqr->lqr_alloc);
1009         if (--lqr->lqr_start_count <= 0) {
1010                 lqr->lqr_start_idx = cfs_rand() % osts->op_count;
1011                 lqr->lqr_start_count =
1012                         (LOV_CREATE_RESEED_MIN / max(osts->op_count, 1U) +
1013                          LOV_CREATE_RESEED_MULT) * max(osts->op_count, 1U);
1014         } else if (stripe_count_min >= osts->op_count ||
1015                         lqr->lqr_start_idx > osts->op_count) {
1016                 /* If we have allocated from all of the OSTs, slowly
1017                  * precess the next start if the OST/stripe count isn't
1018                  * already doing this for us. */
1019                 lqr->lqr_start_idx %= osts->op_count;
1020                 if (stripe_count > 1 && (osts->op_count % stripe_count) != 1)
1021                         ++lqr->lqr_offset_idx;
1022         }
1023         ost_start_idx_temp = lqr->lqr_start_idx;
1024
1025 repeat_find:
1026
1027         QOS_DEBUG("pool '%s' want %d start_idx %d start_count %d offset %d "
1028                   "active %d count %d\n",
1029                   lod_comp->llc_pool ? lod_comp->llc_pool : "",
1030                   stripe_count, lqr->lqr_start_idx, lqr->lqr_start_count,
1031                   lqr->lqr_offset_idx, osts->op_count, osts->op_count);
1032
1033         for (i = 0; i < osts->op_count && stripe_idx < stripe_count; i++) {
1034                 array_idx = (lqr->lqr_start_idx + lqr->lqr_offset_idx) %
1035                                 osts->op_count;
1036                 ++lqr->lqr_start_idx;
1037                 ost_idx = lqr->lqr_pool.op_array[array_idx];
1038
1039                 QOS_DEBUG("#%d strt %d act %d strp %d ary %d idx %d\n",
1040                           i, lqr->lqr_start_idx, /* XXX: active*/ 0,
1041                           stripe_idx, array_idx, ost_idx);
1042
1043                 if ((ost_idx == LOV_QOS_EMPTY) ||
1044                     !cfs_bitmap_check(m->lod_ost_bitmap, ost_idx))
1045                         continue;
1046
1047                 /* Fail Check before osc_precreate() is called
1048                    so we can only 'fail' single OSC. */
1049                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
1050                         continue;
1051
1052                 spin_unlock(&lqr->lqr_alloc);
1053                 rc = lod_check_and_reserve_ost(env, m, sfs, ost_idx, speed,
1054                                                &stripe_idx, stripe, th, inuse);
1055                 spin_lock(&lqr->lqr_alloc);
1056
1057                 if (rc != 0 && OST_TGT(m, ost_idx)->ltd_connecting)
1058                         ost_connecting = 1;
1059         }
1060         if ((speed < 2) && (stripe_idx < stripe_count_min)) {
1061                 /* Try again, allowing slower OSCs */
1062                 speed++;
1063                 lqr->lqr_start_idx = ost_start_idx_temp;
1064
1065                 ost_connecting = 0;
1066                 goto repeat_find;
1067         }
1068
1069         spin_unlock(&lqr->lqr_alloc);
1070         up_read(&m->lod_qos.lq_rw_sem);
1071
1072         if (stripe_idx) {
1073                 lod_comp->llc_stripe_count = stripe_idx;
1074                 /* at least one stripe is allocated */
1075                 rc = 0;
1076         } else {
1077                 /* nobody provided us with a single object */
1078                 if (ost_connecting)
1079                         rc = -EINPROGRESS;
1080                 else
1081                         rc = -ENOSPC;
1082         }
1083
1084 out:
1085         if (pool != NULL) {
1086                 up_read(&pool_tgt_rw_sem(pool));
1087                 /* put back ref got by lod_find_pool() */
1088                 lod_pool_putref(pool);
1089         }
1090
1091         RETURN(rc);
1092 }
1093
1094 /**
1095  * Allocate a specific striping layout on a user defined set of OSTs.
1096  *
1097  * Allocates new striping using the OST index range provided by the data from
1098  * the lmm_obejcts contained in the lov_user_md passed to this method. Full
1099  * OSTs are not considered. The exact order of OSTs requested by the user
1100  * is respected as much as possible depending on OST status. The number of
1101  * stripes needed and stripe offset are taken from the object. If that number
1102  * can not be met, then the function returns a failure and then it's the
1103  * caller's responsibility to release the stripes allocated. All the internal
1104  * structures are protected, but no concurrent allocation is allowed on the
1105  * same objects.
1106  *
1107  * \param[in] env       execution environment for this thread
1108  * \param[in] lo        LOD object
1109  * \param[out] stripe   striping created
1110  * \param[in] th        transaction handle
1111  * \param[in] comp_idx  index of ldo_comp_entries
1112  * \param[in|out] inuse array of inuse ost index
1113  *
1114  * \retval 0            on success
1115  * \retval -ENODEV      OST index does not exist on file system
1116  * \retval -EINVAL      requested OST index is invalid
1117  * \retval negative     negated errno on error
1118  */
1119 static int lod_alloc_ost_list(const struct lu_env *env, struct lod_object *lo,
1120                               struct dt_object **stripe, struct thandle *th,
1121                               int comp_idx, struct ost_pool *inuse)
1122 {
1123         struct lod_layout_component *lod_comp;
1124         struct lod_device       *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1125         struct obd_statfs       *sfs = &lod_env_info(env)->lti_osfs;
1126         struct dt_object        *o;
1127         unsigned int            array_idx = 0;
1128         int                     stripe_count = 0;
1129         int                     i;
1130         int                     rc = -EINVAL;
1131         ENTRY;
1132
1133         /* for specific OSTs layout */
1134         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1135         lod_comp = &lo->ldo_comp_entries[comp_idx];
1136         LASSERT(lod_comp->llc_ostlist.op_array);
1137
1138         rc = lod_qos_ost_in_use_clear(env, lod_comp->llc_stripe_count);
1139         if (rc < 0)
1140                 RETURN(rc);
1141
1142         for (i = 0; i < lod_comp->llc_stripe_count; i++) {
1143                 if (lod_comp->llc_ostlist.op_array[i] ==
1144                     lod_comp->llc_stripe_offset) {
1145                         array_idx = i;
1146                         break;
1147                 }
1148         }
1149         if (i == lod_comp->llc_stripe_count) {
1150                 CDEBUG(D_OTHER,
1151                        "%s: start index %d not in the specified list of OSTs\n",
1152                        lod2obd(m)->obd_name, lod_comp->llc_stripe_offset);
1153                 RETURN(-EINVAL);
1154         }
1155
1156         for (i = 0; i < lod_comp->llc_stripe_count;
1157              i++, array_idx = (array_idx + 1) % lod_comp->llc_stripe_count) {
1158                 __u32 ost_idx = lod_comp->llc_ostlist.op_array[array_idx];
1159
1160                 if (!cfs_bitmap_check(m->lod_ost_bitmap, ost_idx)) {
1161                         rc = -ENODEV;
1162                         break;
1163                 }
1164
1165                 /*
1166                  * do not put >1 objects on a single OST
1167                  */
1168                 if (lod_qos_is_ost_used(env, ost_idx, stripe_count)) {
1169                         rc = -EINVAL;
1170                         break;
1171                 }
1172
1173                 rc = lod_statfs_and_check(env, m, ost_idx, sfs);
1174                 if (rc < 0) /* this OSP doesn't feel well */
1175                         break;
1176
1177                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
1178                 if (IS_ERR(o)) {
1179                         rc = PTR_ERR(o);
1180                         CDEBUG(D_OTHER,
1181                                "%s: can't declare new object on #%u: %d\n",
1182                                lod2obd(m)->obd_name, ost_idx, rc);
1183                         break;
1184                 }
1185
1186                 /*
1187                  * We've successfully declared (reserved) an object
1188                  */
1189                 lod_qos_ost_in_use(env, stripe_count, ost_idx);
1190                 lod_comp_ost_in_use(inuse, ost_idx);
1191                 stripe[stripe_count] = o;
1192                 stripe_count++;
1193         }
1194
1195         RETURN(rc);
1196 }
1197
1198 /**
1199  * Allocate a striping on a predefined set of OSTs.
1200  *
1201  * Allocates new layout starting from OST index in lo->ldo_stripe_offset.
1202  * Full OSTs are not considered. The exact order of OSTs is not important and
1203  * varies depending on OST status. The allocation procedure prefers the targets
1204  * with precreated objects ready. The number of stripes needed and stripe
1205  * offset are taken from the object. If that number cannot be met, then the
1206  * function returns an error and then it's the caller's responsibility to
1207  * release the stripes allocated. All the internal structures are protected,
1208  * but no concurrent allocation is allowed on the same objects.
1209  *
1210  * \param[in] env       execution environment for this thread
1211  * \param[in] lo        LOD object
1212  * \param[out] stripe   striping created
1213  * \param[in] flags     not used
1214  * \param[in] th        transaction handle
1215  * \param[in] comp_idx  index of ldo_comp_entries
1216  * \param[in|out]inuse  array of inuse ost index
1217  *
1218  * \retval 0            on success
1219  * \retval -ENOSPC      if no OST objects are available at all
1220  * \retval -EFBIG       if not enough OST objects are found
1221  * \retval -EINVAL      requested offset is invalid
1222  * \retval negative     errno on failure
1223  */
1224 static int lod_alloc_specific(const struct lu_env *env, struct lod_object *lo,
1225                               struct dt_object **stripe, int flags,
1226                               struct thandle *th, int comp_idx,
1227                               struct ost_pool *inuse)
1228 {
1229         struct lod_layout_component *lod_comp;
1230         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1231         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
1232         struct dt_object  *o;
1233         __u32              ost_idx;
1234         unsigned int       i, array_idx, ost_count;
1235         int                rc, stripe_num = 0;
1236         int                speed = 0;
1237         struct pool_desc  *pool = NULL;
1238         struct ost_pool   *osts;
1239         ENTRY;
1240
1241         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1242         lod_comp = &lo->ldo_comp_entries[comp_idx];
1243
1244         rc = lod_qos_ost_in_use_clear(env, lod_comp->llc_stripe_count);
1245         if (rc)
1246                 GOTO(out, rc);
1247
1248         if (lod_comp->llc_pool != NULL)
1249                 pool = lod_find_pool(m, lod_comp->llc_pool);
1250
1251         if (pool != NULL) {
1252                 down_read(&pool_tgt_rw_sem(pool));
1253                 osts = &(pool->pool_obds);
1254         } else {
1255                 osts = &(m->lod_pool_info);
1256         }
1257
1258         ost_count = osts->op_count;
1259
1260 repeat_find:
1261         /* search loi_ost_idx in ost array */
1262         array_idx = 0;
1263         for (i = 0; i < ost_count; i++) {
1264                 if (osts->op_array[i] == lod_comp->llc_stripe_offset) {
1265                         array_idx = i;
1266                         break;
1267                 }
1268         }
1269         if (i == ost_count) {
1270                 CERROR("Start index %d not found in pool '%s'\n",
1271                        lod_comp->llc_stripe_offset,
1272                        lod_comp->llc_pool ? lod_comp->llc_pool : "");
1273                 GOTO(out, rc = -EINVAL);
1274         }
1275
1276         for (i = 0; i < ost_count;
1277                         i++, array_idx = (array_idx + 1) % ost_count) {
1278                 ost_idx = osts->op_array[array_idx];
1279
1280                 if (!cfs_bitmap_check(m->lod_ost_bitmap, ost_idx))
1281                         continue;
1282
1283                 /* Fail Check before osc_precreate() is called
1284                    so we can only 'fail' single OSC. */
1285                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
1286                         continue;
1287
1288                 /*
1289                  * do not put >1 objects on a single OST
1290                  */
1291                 if (lod_qos_is_ost_used(env, ost_idx, stripe_num))
1292                         continue;
1293
1294                 /*
1295                  * try not allocate on the OST used by other component
1296                  */
1297                 if (speed == 0 && i != 0 &&
1298                     lod_comp_is_ost_used(inuse, ost_idx))
1299                         continue;
1300
1301                 /* Drop slow OSCs if we can, but not for requested start idx.
1302                  *
1303                  * This means "if OSC is slow and it is not the requested
1304                  * start OST, then it can be skipped, otherwise skip it only
1305                  * if it is inactive/recovering/out-of-space." */
1306
1307                 rc = lod_statfs_and_check(env, m, ost_idx, sfs);
1308                 if (rc) {
1309                         /* this OSP doesn't feel well */
1310                         continue;
1311                 }
1312
1313                 /*
1314                  * We expect number of precreated objects at the first
1315                  * iteration.  Skip OSPs with no objects ready.  Don't apply
1316                  * this logic to OST specified with stripe_offset.
1317                  */
1318                 if (i != 0 && sfs->os_fprecreated == 0 && speed == 0)
1319                         continue;
1320
1321                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
1322                 if (IS_ERR(o)) {
1323                         CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
1324                                ost_idx, (int) PTR_ERR(o));
1325                         continue;
1326                 }
1327
1328                 /*
1329                  * We've successfully declared (reserved) an object
1330                  */
1331                 lod_qos_ost_in_use(env, stripe_num, ost_idx);
1332                 lod_comp_ost_in_use(inuse, ost_idx);
1333                 stripe[stripe_num] = o;
1334                 stripe_num++;
1335
1336                 /* We have enough stripes */
1337                 if (stripe_num == lod_comp->llc_stripe_count)
1338                         GOTO(out, rc = 0);
1339         }
1340         if (speed < 2) {
1341                 /* Try again, allowing slower OSCs */
1342                 speed++;
1343                 goto repeat_find;
1344         }
1345
1346         /* If we were passed specific striping params, then a failure to
1347          * meet those requirements is an error, since we can't reallocate
1348          * that memory (it might be part of a larger array or something).
1349          */
1350         CERROR("can't lstripe objid "DFID": have %d want %u\n",
1351                PFID(lu_object_fid(lod2lu_obj(lo))), stripe_num,
1352                lod_comp->llc_stripe_count);
1353         rc = stripe_num == 0 ? -ENOSPC : -EFBIG;
1354 out:
1355         if (pool != NULL) {
1356                 up_read(&pool_tgt_rw_sem(pool));
1357                 /* put back ref got by lod_find_pool() */
1358                 lod_pool_putref(pool);
1359         }
1360
1361         RETURN(rc);
1362 }
1363
1364 /**
1365  * Check whether QoS allocation should be used.
1366  *
1367  * A simple helper to decide when QoS allocation should be used:
1368  * if it's just a single available target or the used space is
1369  * evenly distributed among the targets at the moment, then QoS
1370  * allocation algorithm should not be used.
1371  *
1372  * \param[in] lod       LOD device
1373  *
1374  * \retval 0            should not be used
1375  * \retval 1            should be used
1376  */
1377 static inline int lod_qos_is_usable(struct lod_device *lod)
1378 {
1379 #ifdef FORCE_QOS
1380         /* to be able to debug QoS code */
1381         return 1;
1382 #endif
1383
1384         /* Detect -EAGAIN early, before expensive lock is taken. */
1385         if (!lod->lod_qos.lq_dirty && lod->lod_qos.lq_same_space)
1386                 return 0;
1387
1388         if (lod->lod_desc.ld_active_tgt_count < 2)
1389                 return 0;
1390
1391         return 1;
1392 }
1393
1394 /**
1395  * Allocate a striping using an algorithm with weights.
1396  *
1397  * The function allocates OST objects to create a striping. The algorithm
1398  * used is based on weights (currently only using the free space), and it's
1399  * trying to ensure the space is used evenly by OSTs and OSSs. The striping
1400  * configuration (# of stripes, offset, pool) is taken from the object and
1401  * is prepared by the caller.
1402  *
1403  * If LOV_USES_DEFAULT_STRIPE is not passed and prepared configuration can't
1404  * be met due to too few OSTs, then allocation fails. If the flag is passed
1405  * fewer than 3/4 of the requested number of stripes can be allocated, then
1406  * allocation fails.
1407  *
1408  * No concurrent allocation is allowed on the object and this must be ensured
1409  * by the caller. All the internal structures are protected by the function.
1410  *
1411  * The algorithm has two steps: find available OSTs and calculate their
1412  * weights, then select the OSTs with their weights used as the probability.
1413  * An OST with a higher weight is proportionately more likely to be selected
1414  * than one with a lower weight.
1415  *
1416  * \param[in] env       execution environment for this thread
1417  * \param[in] lo        LOD object
1418  * \param[out] stripe   striping created
1419  * \param[in] flags     0 or LOV_USES_DEFAULT_STRIPE
1420  * \param[in] th        transaction handle
1421  * \param[in] comp_idx  index of ldo_comp_entries
1422  * \param[in|out]inuse  array of inuse ost index
1423  *
1424  * \retval 0            on success
1425  * \retval -EAGAIN      not enough OSTs are found for specified stripe count
1426  * \retval -EINVAL      requested OST index is invalid
1427  * \retval negative     errno on failure
1428  */
1429 static int lod_alloc_qos(const struct lu_env *env, struct lod_object *lo,
1430                          struct dt_object **stripe, int flags,
1431                          struct thandle *th, int comp_idx,
1432                          struct ost_pool *inuse)
1433 {
1434         struct lod_layout_component *lod_comp;
1435         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1436         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
1437         struct lod_tgt_desc *ost;
1438         struct dt_object *o;
1439         __u64 total_weight = 0;
1440         struct pool_desc *pool = NULL;
1441         struct ost_pool *osts;
1442         unsigned int i;
1443         __u32 nfound, good_osts, stripe_count, stripe_count_min;
1444         __u32 inuse_old_count = inuse->op_count;
1445         int rc = 0;
1446         ENTRY;
1447
1448         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1449         lod_comp = &lo->ldo_comp_entries[comp_idx];
1450         stripe_count = lod_comp->llc_stripe_count;
1451         stripe_count_min = min_stripe_count(stripe_count, flags);
1452         if (stripe_count_min < 1)
1453                 RETURN(-EINVAL);
1454
1455         if (lod_comp->llc_pool != NULL)
1456                 pool = lod_find_pool(lod, lod_comp->llc_pool);
1457
1458         if (pool != NULL) {
1459                 down_read(&pool_tgt_rw_sem(pool));
1460                 osts = &(pool->pool_obds);
1461         } else {
1462                 osts = &(lod->lod_pool_info);
1463         }
1464
1465         /* Detect -EAGAIN early, before expensive lock is taken. */
1466         if (!lod_qos_is_usable(lod))
1467                 GOTO(out_nolock, rc = -EAGAIN);
1468
1469         /* Do actual allocation, use write lock here. */
1470         down_write(&lod->lod_qos.lq_rw_sem);
1471
1472         /*
1473          * Check again, while we were sleeping on @lq_rw_sem things could
1474          * change.
1475          */
1476         if (!lod_qos_is_usable(lod))
1477                 GOTO(out, rc = -EAGAIN);
1478
1479         rc = lod_qos_calc_ppo(lod);
1480         if (rc)
1481                 GOTO(out, rc);
1482
1483         rc = lod_qos_ost_in_use_clear(env, lod_comp->llc_stripe_count);
1484         if (rc)
1485                 GOTO(out, rc);
1486
1487         good_osts = 0;
1488         /* Find all the OSTs that are valid stripe candidates */
1489         for (i = 0; i < osts->op_count; i++) {
1490                 if (!cfs_bitmap_check(lod->lod_ost_bitmap, osts->op_array[i]))
1491                         continue;
1492
1493                 ost = OST_TGT(lod, osts->op_array[i]);
1494                 ost->ltd_qos.ltq_usable = 0;
1495
1496                 rc = lod_statfs_and_check(env, lod, osts->op_array[i], sfs);
1497                 if (rc) {
1498                         /* this OSP doesn't feel well */
1499                         continue;
1500                 }
1501
1502                 if (sfs->os_state & OS_STATE_DEGRADED)
1503                         continue;
1504
1505                 /* Fail Check before osc_precreate() is called
1506                    so we can only 'fail' single OSC. */
1507                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) &&
1508                                    osts->op_array[i] == 0)
1509                         continue;
1510
1511                 ost->ltd_qos.ltq_usable = 1;
1512                 lod_qos_calc_weight(lod, osts->op_array[i]);
1513                 total_weight += ost->ltd_qos.ltq_weight;
1514
1515                 good_osts++;
1516         }
1517
1518         QOS_DEBUG("found %d good osts\n", good_osts);
1519
1520         if (good_osts < stripe_count_min)
1521                 GOTO(out, rc = -EAGAIN);
1522
1523         /* We have enough osts */
1524         if (good_osts < stripe_count)
1525                 stripe_count = good_osts;
1526
1527         /* Find enough OSTs with weighted random allocation. */
1528         nfound = 0;
1529         while (nfound < stripe_count) {
1530                 __u64 rand, cur_weight;
1531
1532                 cur_weight = 0;
1533                 rc = -ENOSPC;
1534
1535                 if (total_weight) {
1536 #if BITS_PER_LONG == 32
1537                         rand = cfs_rand() % (unsigned)total_weight;
1538                         /* If total_weight > 32-bit, first generate the high
1539                          * 32 bits of the random number, then add in the low
1540                          * 32 bits (truncated to the upper limit, if needed) */
1541                         if (total_weight > 0xffffffffULL)
1542                                 rand = (__u64)(cfs_rand() %
1543                                         (unsigned)(total_weight >> 32)) << 32;
1544                         else
1545                                 rand = 0;
1546
1547                         if (rand == (total_weight & 0xffffffff00000000ULL))
1548                                 rand |= cfs_rand() % (unsigned)total_weight;
1549                         else
1550                                 rand |= cfs_rand();
1551
1552 #else
1553                         rand = ((__u64)cfs_rand() << 32 | cfs_rand()) %
1554                                 total_weight;
1555 #endif
1556                 } else {
1557                         rand = 0;
1558                 }
1559
1560                 /* On average, this will hit larger-weighted OSTs more often.
1561                  * 0-weight OSTs will always get used last (only when rand=0) */
1562                 for (i = 0; i < osts->op_count; i++) {
1563                         __u32 idx = osts->op_array[i];
1564
1565                         if (!cfs_bitmap_check(lod->lod_ost_bitmap, idx))
1566                                 continue;
1567
1568                         ost = OST_TGT(lod, idx);
1569
1570                         if (!ost->ltd_qos.ltq_usable)
1571                                 continue;
1572
1573                         cur_weight += ost->ltd_qos.ltq_weight;
1574                         QOS_DEBUG("stripe_count=%d nfound=%d cur_weight=%llu "
1575                                   "rand=%llu total_weight=%llu\n",
1576                                   stripe_count, nfound, cur_weight, rand,
1577                                   total_weight);
1578
1579                         if (cur_weight < rand)
1580                                 continue;
1581
1582                         QOS_DEBUG("stripe=%d to idx=%d\n", nfound, idx);
1583                         /*
1584                          * do not put >1 objects on a single OST
1585                          */
1586                         if (lod_qos_is_ost_used(env, idx, nfound) ||
1587                             lod_comp_is_ost_used(inuse, idx))
1588                                 continue;
1589
1590                         o = lod_qos_declare_object_on(env, lod, idx, th);
1591                         if (IS_ERR(o)) {
1592                                 QOS_DEBUG("can't declare object on #%u: %d\n",
1593                                           idx, (int) PTR_ERR(o));
1594                                 continue;
1595                         }
1596
1597                         lod_qos_ost_in_use(env, nfound, idx);
1598                         lod_comp_ost_in_use(inuse, idx);
1599                         stripe[nfound++] = o;
1600                         lod_qos_used(lod, osts, idx, &total_weight);
1601                         rc = 0;
1602                         break;
1603                 }
1604
1605                 if (rc) {
1606                         /* no OST found on this iteration, give up */
1607                         break;
1608                 }
1609         }
1610
1611         if (unlikely(nfound != stripe_count)) {
1612                 /*
1613                  * when the decision to use weighted algorithm was made
1614                  * we had enough appropriate OSPs, but this state can
1615                  * change anytime (no space on OST, broken connection, etc)
1616                  * so it's possible OSP won't be able to provide us with
1617                  * an object due to just changed state
1618                  */
1619                 QOS_DEBUG("%s: wanted %d objects, found only %d\n",
1620                           lod2obd(lod)->obd_name, stripe_count, nfound);
1621                 for (i = 0; i < nfound; i++) {
1622                         LASSERT(stripe[i] != NULL);
1623                         dt_object_put(env, stripe[i]);
1624                         stripe[i] = NULL;
1625                 }
1626                 LASSERTF(nfound <= inuse->op_count,
1627                          "nfound:%d, op_count:%u\n", nfound, inuse->op_count);
1628                 inuse->op_count = inuse_old_count;
1629
1630                 /* makes sense to rebalance next time */
1631                 lod->lod_qos.lq_dirty = 1;
1632                 lod->lod_qos.lq_same_space = 0;
1633
1634                 rc = -EAGAIN;
1635         }
1636
1637 out:
1638         up_write(&lod->lod_qos.lq_rw_sem);
1639
1640 out_nolock:
1641         if (pool != NULL) {
1642                 up_read(&pool_tgt_rw_sem(pool));
1643                 /* put back ref got by lod_find_pool() */
1644                 lod_pool_putref(pool);
1645         }
1646
1647         RETURN(rc);
1648 }
1649
1650 /**
1651  * Find largest stripe count the caller can use.
1652  *
1653  * Find the maximal possible stripe count not greater than \a stripe_count.
1654  * Sometimes suggested stripecount can't be reached for a number of reasons:
1655  * lack of enough active OSTs or the backend does not support EAs that large.
1656  * If the passed one is 0, then the filesystem's default one is used.
1657  *
1658  * \param[in] lod       LOD device
1659  * \param[in] lo        The lod_object
1660  * \param[in] stripe_count      count the caller would like to use
1661  *
1662  * \retval              the maximum usable stripe count
1663  */
1664 __u16 lod_get_stripe_count(struct lod_device *lod, struct lod_object *lo,
1665                            __u16 stripe_count)
1666 {
1667         __u32 max_stripes = LOV_MAX_STRIPE_COUNT_OLD;
1668
1669         if (!stripe_count)
1670                 stripe_count = lod->lod_desc.ld_default_stripe_count;
1671         if (stripe_count > lod->lod_desc.ld_active_tgt_count)
1672                 stripe_count = lod->lod_desc.ld_active_tgt_count;
1673         if (!stripe_count)
1674                 stripe_count = 1;
1675
1676         /* stripe count is based on whether OSD can handle larger EA sizes */
1677         if (lod->lod_osd_max_easize > 0) {
1678                 unsigned int easize = lod->lod_osd_max_easize;
1679                 int i;
1680
1681                 if (lo->ldo_is_composite) {
1682                         struct lod_layout_component *lod_comp;
1683                         unsigned int header_sz = sizeof(struct lov_comp_md_v1);
1684
1685                         header_sz += sizeof(struct lov_comp_md_entry_v1) *
1686                                         lo->ldo_comp_cnt;
1687                         for (i = 0; i < lo->ldo_comp_cnt; i++) {
1688                                 lod_comp = &lo->ldo_comp_entries[i];
1689                                 if (lod_comp->llc_flags & LCME_FL_INIT)
1690                                         header_sz += lov_mds_md_size(
1691                                                 lod_comp->llc_stripe_count,
1692                                                 LOV_MAGIC_V3);
1693                         }
1694                         if (easize > header_sz)
1695                                 easize -= header_sz;
1696                         else
1697                                 easize = 0;
1698                 }
1699
1700                 max_stripes = lov_mds_md_max_stripe_count(easize, LOV_MAGIC_V3);
1701         }
1702
1703         return (stripe_count < max_stripes) ? stripe_count : max_stripes;
1704 }
1705
1706 /**
1707  * Create in-core respresentation for a fully-defined striping
1708  *
1709  * When the caller passes a fully-defined striping (i.e. everything including
1710  * OST object FIDs are defined), then we still need to instantiate LU-cache
1711  * with the objects representing the stripes defined. This function completes
1712  * that task.
1713  *
1714  * \param[in] env       execution environment for this thread
1715  * \param[in] mo        LOD object
1716  * \param[in] buf       buffer containing the striping
1717  *
1718  * \retval 0            on success
1719  * \retval negative     negated errno on error
1720  */
1721 int lod_use_defined_striping(const struct lu_env *env,
1722                              struct lod_object *mo,
1723                              const struct lu_buf *buf)
1724 {
1725         struct lod_layout_component *lod_comp;
1726         struct lov_mds_md_v1   *v1 = buf->lb_buf;
1727         struct lov_mds_md_v3   *v3 = buf->lb_buf;
1728         struct lov_comp_md_v1  *comp_v1 = NULL;
1729         struct lov_ost_data_v1 *objs;
1730         __u32   magic;
1731         __u16   comp_cnt;
1732         __u16   mirror_cnt;
1733         int     rc = 0, i;
1734         ENTRY;
1735
1736         magic = le32_to_cpu(v1->lmm_magic) & ~LOV_MAGIC_DEFINED;
1737
1738         if (magic != LOV_MAGIC_V1 && magic != LOV_MAGIC_V3 &&
1739             magic != LOV_MAGIC_COMP_V1)
1740                 RETURN(-EINVAL);
1741
1742         if (magic == LOV_MAGIC_COMP_V1) {
1743                 comp_v1 = buf->lb_buf;
1744                 comp_cnt = le16_to_cpu(comp_v1->lcm_entry_count);
1745                 if (comp_cnt == 0)
1746                         RETURN(-EINVAL);
1747                 mirror_cnt = le16_to_cpu(comp_v1->lcm_mirror_count) + 1;
1748                 mo->ldo_flr_state = le16_to_cpu(comp_v1->lcm_flags) &
1749                                         LCM_FL_FLR_MASK;
1750                 mo->ldo_is_composite = 1;
1751         } else {
1752                 mo->ldo_is_composite = 0;
1753                 comp_cnt = 1;
1754                 mirror_cnt = 0;
1755         }
1756         mo->ldo_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
1757
1758         rc = lod_alloc_comp_entries(mo, mirror_cnt, comp_cnt);
1759         if (rc)
1760                 RETURN(rc);
1761
1762         for (i = 0; i < comp_cnt; i++) {
1763                 struct lu_extent *ext;
1764                 char    *pool_name;
1765                 __u32   offs;
1766
1767                 lod_comp = &mo->ldo_comp_entries[i];
1768
1769                 if (mo->ldo_is_composite) {
1770                         offs = le32_to_cpu(comp_v1->lcm_entries[i].lcme_offset);
1771                         v1 = (struct lov_mds_md_v1 *)((char *)comp_v1 + offs);
1772                         magic = le32_to_cpu(v1->lmm_magic);
1773
1774                         ext = &comp_v1->lcm_entries[i].lcme_extent;
1775                         lod_comp->llc_extent.e_start =
1776                                 le64_to_cpu(ext->e_start);
1777                         lod_comp->llc_extent.e_end = le64_to_cpu(ext->e_end);
1778                         lod_comp->llc_flags =
1779                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_flags);
1780                         lod_comp->llc_id =
1781                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_id);
1782                         if (lod_comp->llc_id == LCME_ID_INVAL)
1783                                 GOTO(out, rc = -EINVAL);
1784                 }
1785
1786                 pool_name = NULL;
1787                 if (magic == LOV_MAGIC_V1) {
1788                         objs = &v1->lmm_objects[0];
1789                 } else if (magic == LOV_MAGIC_V3) {
1790                         objs = &v3->lmm_objects[0];
1791                         if (v3->lmm_pool_name[0] != '\0')
1792                                 pool_name = v3->lmm_pool_name;
1793                 } else {
1794                         CDEBUG(D_LAYOUT, "Invalid magic %x\n", magic);
1795                         GOTO(out, rc = -EINVAL);
1796                 }
1797
1798                 lod_comp->llc_pattern = le32_to_cpu(v1->lmm_pattern);
1799                 lod_comp->llc_stripe_size = le32_to_cpu(v1->lmm_stripe_size);
1800                 lod_comp->llc_stripe_count = le16_to_cpu(v1->lmm_stripe_count);
1801                 lod_comp->llc_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
1802                 /**
1803                  * The stripe_offset of an uninit-ed component is stored in
1804                  * the lmm_layout_gen
1805                  */
1806                 if (mo->ldo_is_composite && !lod_comp_inited(lod_comp))
1807                         lod_comp->llc_stripe_offset = lod_comp->llc_layout_gen;
1808                 lod_obj_set_pool(mo, i, pool_name);
1809
1810                 if ((!mo->ldo_is_composite || lod_comp_inited(lod_comp)) &&
1811                     !(lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED) &&
1812                     !(lod_comp->llc_pattern & LOV_PATTERN_MDT)) {
1813                         rc = lod_initialize_objects(env, mo, objs, i);
1814                         if (rc)
1815                                 GOTO(out, rc);
1816                 }
1817         }
1818
1819         rc = lod_fill_mirrors(mo);
1820         if (rc)
1821                 GOTO(out, rc);
1822 out:
1823         if (rc)
1824                 lod_object_free_striping(env, mo);
1825
1826         RETURN(rc);
1827 }
1828
1829 /**
1830  * Parse suggested striping configuration.
1831  *
1832  * The caller gets a suggested striping configuration from a number of sources
1833  * including per-directory default and applications. Then it needs to verify
1834  * the suggested striping is valid, apply missing bits and store the resulting
1835  * configuration in the object to be used by the allocator later. Must not be
1836  * called concurrently against the same object. It's OK to provide a
1837  * fully-defined striping.
1838  *
1839  * \param[in] env       execution environment for this thread
1840  * \param[in] lo        LOD object
1841  * \param[in] buf       buffer containing the striping
1842  *
1843  * \retval 0            on success
1844  * \retval negative     negated errno on error
1845  */
1846 int lod_qos_parse_config(const struct lu_env *env, struct lod_object *lo,
1847                          const struct lu_buf *buf)
1848 {
1849         struct lod_layout_component *lod_comp;
1850         struct lod_device       *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
1851         struct lov_desc         *desc = &d->lod_desc;
1852         struct lov_user_md_v1   *v1 = NULL;
1853         struct lov_user_md_v3   *v3 = NULL;
1854         struct lov_comp_md_v1   *comp_v1 = NULL;
1855         char    def_pool[LOV_MAXPOOLNAME + 1];
1856         __u32   magic;
1857         __u16   comp_cnt;
1858         __u16   mirror_cnt;
1859         int     i, rc;
1860         ENTRY;
1861
1862         if (buf == NULL || buf->lb_buf == NULL || buf->lb_len == 0)
1863                 RETURN(0);
1864
1865         memset(def_pool, 0, sizeof(def_pool));
1866         if (lo->ldo_comp_entries != NULL)
1867                 lod_layout_get_pool(lo->ldo_comp_entries, lo->ldo_comp_cnt,
1868                                     def_pool, sizeof(def_pool));
1869
1870         /* free default striping info */
1871         lod_free_comp_entries(lo);
1872
1873         rc = lod_verify_striping(d, lo, buf, false);
1874         if (rc)
1875                 RETURN(-EINVAL);
1876
1877         v3 = buf->lb_buf;
1878         v1 = buf->lb_buf;
1879         comp_v1 = buf->lb_buf;
1880         magic = v1->lmm_magic;
1881
1882         if (unlikely(le32_to_cpu(magic) & LOV_MAGIC_DEFINED)) {
1883                 /* try to use as fully defined striping */
1884                 rc = lod_use_defined_striping(env, lo, buf);
1885                 RETURN(rc);
1886         }
1887
1888         switch (magic) {
1889         case __swab32(LOV_USER_MAGIC_V1):
1890                 lustre_swab_lov_user_md_v1(v1);
1891                 magic = v1->lmm_magic;
1892                 /* fall through */
1893         case LOV_USER_MAGIC_V1:
1894                 break;
1895         case __swab32(LOV_USER_MAGIC_V3):
1896                 lustre_swab_lov_user_md_v3(v3);
1897                 magic = v3->lmm_magic;
1898                 /* fall through */
1899         case LOV_USER_MAGIC_V3:
1900                 break;
1901         case __swab32(LOV_USER_MAGIC_SPECIFIC):
1902                 lustre_swab_lov_user_md_v3(v3);
1903                 lustre_swab_lov_user_md_objects(v3->lmm_objects,
1904                                                 v3->lmm_stripe_count);
1905                 magic = v3->lmm_magic;
1906                 /* fall through */
1907         case LOV_USER_MAGIC_SPECIFIC:
1908                 break;
1909         case __swab32(LOV_USER_MAGIC_COMP_V1):
1910                 lustre_swab_lov_comp_md_v1(comp_v1);
1911                 magic = comp_v1->lcm_magic;
1912                 /* fall trhough */
1913         case LOV_USER_MAGIC_COMP_V1:
1914                 break;
1915         default:
1916                 CERROR("%s: unrecognized magic %X\n",
1917                        lod2obd(d)->obd_name, magic);
1918                 RETURN(-EINVAL);
1919         }
1920
1921         lustre_print_user_md(D_OTHER, v1, "parse config");
1922
1923         if (magic == LOV_USER_MAGIC_COMP_V1) {
1924                 comp_cnt = comp_v1->lcm_entry_count;
1925                 if (comp_cnt == 0)
1926                         RETURN(-EINVAL);
1927                 mirror_cnt =  comp_v1->lcm_mirror_count + 1;
1928                 if (mirror_cnt > 1)
1929                         lo->ldo_flr_state = LCM_FL_RDONLY;
1930                 lo->ldo_is_composite = 1;
1931         } else {
1932                 comp_cnt = 1;
1933                 mirror_cnt = 0;
1934                 lo->ldo_is_composite = 0;
1935         }
1936
1937         rc = lod_alloc_comp_entries(lo, mirror_cnt, comp_cnt);
1938         if (rc)
1939                 RETURN(rc);
1940
1941         LASSERT(lo->ldo_comp_entries);
1942
1943         for (i = 0; i < comp_cnt; i++) {
1944                 struct pool_desc        *pool;
1945                 struct lu_extent        *ext;
1946                 char    *pool_name;
1947
1948                 lod_comp = &lo->ldo_comp_entries[i];
1949
1950                 if (lo->ldo_is_composite) {
1951                         v1 = (struct lov_user_md *)((char *)comp_v1 +
1952                                         comp_v1->lcm_entries[i].lcme_offset);
1953                         ext = &comp_v1->lcm_entries[i].lcme_extent;
1954                         lod_comp->llc_extent = *ext;
1955                         lod_comp->llc_flags =
1956                                 comp_v1->lcm_entries[i].lcme_flags &
1957                                         LCME_USER_FLAGS;
1958                 }
1959
1960                 pool_name = NULL;
1961                 if (v1->lmm_magic == LOV_USER_MAGIC_V3 ||
1962                     v1->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
1963                         int j;
1964
1965                         v3 = (struct lov_user_md_v3 *)v1;
1966                         if (v3->lmm_pool_name[0] != '\0')
1967                                 pool_name = v3->lmm_pool_name;
1968
1969                         if (v3->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
1970                                 if (v3->lmm_stripe_offset == LOV_OFFSET_DEFAULT)
1971                                         v3->lmm_stripe_offset =
1972                                                 v3->lmm_objects[0].l_ost_idx;
1973
1974                                 /* copy ost list from lmm */
1975                                 lod_comp->llc_ostlist.op_count =
1976                                         v3->lmm_stripe_count;
1977                                 lod_comp->llc_ostlist.op_size =
1978                                         v3->lmm_stripe_count * sizeof(__u32);
1979                                 OBD_ALLOC(lod_comp->llc_ostlist.op_array,
1980                                           lod_comp->llc_ostlist.op_size);
1981                                 if (!lod_comp->llc_ostlist.op_array)
1982                                         GOTO(free_comp, rc = -ENOMEM);
1983
1984                                 for (j = 0; j < v3->lmm_stripe_count; j++)
1985                                         lod_comp->llc_ostlist.op_array[j] =
1986                                                 v3->lmm_objects[j].l_ost_idx;
1987                         }
1988                 }
1989
1990                 if (pool_name == NULL && def_pool[0] != '\0')
1991                         pool_name = def_pool;
1992
1993                 if (v1->lmm_pattern == 0)
1994                         v1->lmm_pattern = LOV_PATTERN_RAID0;
1995                 if (lov_pattern(v1->lmm_pattern) != LOV_PATTERN_RAID0 &&
1996                     lov_pattern(v1->lmm_pattern) != LOV_PATTERN_MDT) {
1997                         CDEBUG(D_LAYOUT, "%s: invalid pattern: %x\n",
1998                                lod2obd(d)->obd_name, v1->lmm_pattern);
1999                         GOTO(free_comp, rc = -EINVAL);
2000                 }
2001
2002                 lod_comp->llc_pattern = v1->lmm_pattern;
2003                 lod_comp->llc_stripe_size = desc->ld_default_stripe_size;
2004                 if (v1->lmm_stripe_size)
2005                         lod_comp->llc_stripe_size = v1->lmm_stripe_size;
2006
2007                 lod_comp->llc_stripe_count = desc->ld_default_stripe_count;
2008                 if (v1->lmm_stripe_count ||
2009                     lov_pattern(v1->lmm_pattern) == LOV_PATTERN_MDT)
2010                         lod_comp->llc_stripe_count = v1->lmm_stripe_count;
2011
2012                 lod_comp->llc_stripe_offset = v1->lmm_stripe_offset;
2013                 lod_obj_set_pool(lo, i, pool_name);
2014
2015                 LASSERT(ergo(lov_pattern(lod_comp->llc_pattern) ==
2016                              LOV_PATTERN_MDT, lod_comp->llc_stripe_count == 0));
2017
2018                 if (pool_name == NULL)
2019                         continue;
2020
2021                 /* In the function below, .hs_keycmp resolves to
2022                  * pool_hashkey_keycmp() */
2023                 /* coverity[overrun-buffer-val] */
2024                 pool = lod_find_pool(d, pool_name);
2025                 if (pool == NULL)
2026                         continue;
2027
2028                 if (lod_comp->llc_stripe_offset != LOV_OFFSET_DEFAULT) {
2029                         rc = lod_check_index_in_pool(
2030                                         lod_comp->llc_stripe_offset, pool);
2031                         if (rc < 0) {
2032                                 lod_pool_putref(pool);
2033                                 CDEBUG(D_LAYOUT, "%s: invalid offset, %u\n",
2034                                        lod2obd(d)->obd_name,
2035                                        lod_comp->llc_stripe_offset);
2036                                 GOTO(free_comp, rc = -EINVAL);
2037                         }
2038                 }
2039
2040                 if (lod_comp->llc_stripe_count > pool_tgt_count(pool))
2041                         lod_comp->llc_stripe_count = pool_tgt_count(pool);
2042
2043                 lod_pool_putref(pool);
2044         }
2045
2046         RETURN(0);
2047
2048 free_comp:
2049         lod_free_comp_entries(lo);
2050         RETURN(rc);
2051 }
2052
2053 /**
2054  * Create a striping for an obejct.
2055  *
2056  * The function creates a new striping for the object. The function tries QoS
2057  * algorithm first unless free space is distributed evenly among OSTs, but
2058  * by default RR algorithm is preferred due to internal concurrency (QoS is
2059  * serialized). The caller must ensure no concurrent calls to the function
2060  * are made against the same object.
2061  *
2062  * \param[in] env       execution environment for this thread
2063  * \param[in] lo        LOD object
2064  * \param[in] attr      attributes OST objects will be declared with
2065  * \param[in] th        transaction handle
2066  * \param[in] comp_idx  index of ldo_comp_entries
2067  * \param[in|out] inuse array of inuse ost index
2068  *
2069  * \retval 0            on success
2070  * \retval negative     negated errno on error
2071  */
2072 int lod_qos_prep_create(const struct lu_env *env, struct lod_object *lo,
2073                         struct lu_attr *attr, struct thandle *th,
2074                         int comp_idx, struct ost_pool *inuse)
2075 {
2076         struct lod_layout_component *lod_comp;
2077         struct lod_device      *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2078         struct dt_object      **stripe;
2079         int                     stripe_len;
2080         int                     flag = LOV_USES_ASSIGNED_STRIPE;
2081         int                     i, rc = 0;
2082         ENTRY;
2083
2084         LASSERT(lo);
2085         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
2086         lod_comp = &lo->ldo_comp_entries[comp_idx];
2087
2088         /* A released component is being created */
2089         if (lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED)
2090                 RETURN(0);
2091
2092         /* A Data-on-MDT component is being created */
2093         if (lov_pattern(lod_comp->llc_pattern) == LOV_PATTERN_MDT)
2094                 RETURN(0);
2095
2096         if (likely(lod_comp->llc_stripe == NULL)) {
2097                 /*
2098                  * no striping has been created so far
2099                  */
2100                 LASSERT(lod_comp->llc_stripe_count);
2101                 /*
2102                  * statfs and check OST targets now, since ld_active_tgt_count
2103                  * could be changed if some OSTs are [de]activated manually.
2104                  */
2105                 lod_qos_statfs_update(env, d);
2106                 stripe_len = lod_get_stripe_count(d, lo,
2107                                                   lod_comp->llc_stripe_count);
2108                 if (stripe_len == 0)
2109                         GOTO(out, rc = -ERANGE);
2110                 lod_comp->llc_stripe_count = stripe_len;
2111                 OBD_ALLOC(stripe, sizeof(stripe[0]) * stripe_len);
2112                 if (stripe == NULL)
2113                         GOTO(out, rc = -ENOMEM);
2114
2115                 lod_getref(&d->lod_ost_descs);
2116                 /* XXX: support for non-0 files w/o objects */
2117                 CDEBUG(D_OTHER, "tgt_count %d stripe_count %d\n",
2118                                 d->lod_desc.ld_tgt_count, stripe_len);
2119
2120                 if (lod_comp->llc_ostlist.op_array) {
2121                         rc = lod_alloc_ost_list(env, lo, stripe, th, comp_idx,
2122                                                 inuse);
2123                 } else if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT) {
2124                         rc = lod_alloc_qos(env, lo, stripe, flag, th,
2125                                            comp_idx, inuse);
2126                         if (rc == -EAGAIN)
2127                                 rc = lod_alloc_rr(env, lo, stripe, flag, th,
2128                                                   comp_idx, inuse);
2129                 } else {
2130                         rc = lod_alloc_specific(env, lo, stripe, flag, th,
2131                                                 comp_idx, inuse);
2132                 }
2133                 lod_putref(d, &d->lod_ost_descs);
2134
2135                 if (rc < 0) {
2136                         for (i = 0; i < stripe_len; i++)
2137                                 if (stripe[i] != NULL)
2138                                         dt_object_put(env, stripe[i]);
2139
2140                         OBD_FREE(stripe, sizeof(stripe[0]) * stripe_len);
2141                         lod_comp->llc_stripe_count = 0;
2142                 } else {
2143                         lod_comp->llc_stripe = stripe;
2144                         lod_comp->llc_stripes_allocated = stripe_len;
2145                 }
2146         } else {
2147                 /*
2148                  * lod_qos_parse_config() found supplied buf as a predefined
2149                  * striping (not a hint), so it allocated all the object
2150                  * now we need to create them
2151                  */
2152                 for (i = 0; i < lod_comp->llc_stripe_count; i++) {
2153                         struct dt_object  *o;
2154
2155                         o = lod_comp->llc_stripe[i];
2156                         LASSERT(o);
2157
2158                         rc = lod_sub_declare_create(env, o, attr, NULL,
2159                                                     NULL, th);
2160                         if (rc < 0) {
2161                                 CERROR("can't declare create: %d\n", rc);
2162                                 break;
2163                         }
2164                 }
2165                 /**
2166                  * Clear LCME_FL_INIT for the component so that
2167                  * lod_striping_create() can create the striping objects
2168                  * in replay.
2169                  */
2170                 lod_comp_unset_init(lod_comp);
2171         }
2172
2173 out:
2174         RETURN(rc);
2175 }
2176
2177 int lod_obj_stripe_set_inuse_cb(const struct lu_env *env,
2178                                 struct lod_object *lo,
2179                                 struct dt_object *dt, struct thandle *th,
2180                                 int comp_idx, int stripe_idx,
2181                                 struct lod_obj_stripe_cb_data *data)
2182 {
2183         struct lod_thread_info  *info = lod_env_info(env);
2184         struct lod_device       *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2185         struct lu_fid   *fid = &info->lti_fid;
2186         __u32   index;
2187         int     rc, type = LU_SEQ_RANGE_OST;
2188
2189         *fid = *lu_object_fid(&dt->do_lu);
2190         rc = lod_fld_lookup(env, d, fid, &index, &type);
2191         if (rc < 0) {
2192                 CERROR("%s: fail to locate "DFID": rc = %d\n",
2193                        lod2obd(d)->obd_name, PFID(fid), rc);
2194                 return rc;
2195         }
2196         lod_comp_ost_in_use(data->locd_inuse, index);
2197         return 0;
2198 }
2199
2200 /**
2201  * Resize per-thread ost list to hold OST target index list already used.
2202  *
2203  * \param[in,out] inuse         structure contains ost list array
2204  * \param[in] cnt               total stripe count of all components
2205  * \param[in] max               array's max size if @max > 0
2206  *
2207  * \retval 0            on success
2208  * \retval -ENOMEM      reallocation failed
2209  */
2210 static int lod_inuse_resize(struct ost_pool *inuse, __u16 cnt, __u16 max)
2211 {
2212         __u32 *array;
2213         __u32 new = cnt * sizeof(inuse->op_array[0]);
2214
2215         inuse->op_count = 0;
2216
2217         if (new <= inuse->op_size)
2218                 return 0;
2219
2220         if (max)
2221                 new = min_t(__u32, new, max);
2222
2223         OBD_ALLOC(array, new);
2224         if (!array)
2225                 return -ENOMEM;
2226
2227         if (inuse->op_array)
2228                 OBD_FREE(inuse->op_array, inuse->op_size);
2229
2230         inuse->op_array = array;
2231         inuse->op_size = new;
2232
2233         return 0;
2234 }
2235
2236 int lod_prepare_inuse(const struct lu_env *env, struct lod_object *lo)
2237 {
2238         struct lod_thread_info *info = lod_env_info(env);
2239         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2240         struct ost_pool *inuse = &info->lti_inuse_osts;
2241         struct lod_obj_stripe_cb_data data = { { 0 } };
2242         __u32 stripe_count = 0;
2243         int i;
2244         int rc;
2245
2246         for (i = 0; i < lo->ldo_comp_cnt; i++)
2247                 stripe_count += lod_comp_entry_stripe_count(lo,
2248                                         &lo->ldo_comp_entries[i], false);
2249         rc = lod_inuse_resize(inuse, stripe_count, d->lod_osd_max_easize);
2250         if (rc)
2251                 return rc;
2252
2253         data.locd_inuse = inuse;
2254         data.locd_stripe_cb = lod_obj_stripe_set_inuse_cb;
2255         return lod_obj_for_each_stripe(env, lo, NULL, &data);
2256 }
2257
2258 int lod_prepare_create(const struct lu_env *env, struct lod_object *lo,
2259                        struct lu_attr *attr, const struct lu_buf *buf,
2260                        struct thandle *th)
2261
2262 {
2263         struct lod_thread_info *info = lod_env_info(env);
2264         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2265         struct ost_pool *inuse = &info->lti_inuse_osts;
2266         uint64_t size = 0;
2267         int i;
2268         int rc;
2269         ENTRY;
2270
2271         LASSERT(lo);
2272
2273         /* no OST available */
2274         /* XXX: should we be waiting a bit to prevent failures during
2275          * cluster initialization? */
2276         if (d->lod_ostnr == 0)
2277                 RETURN(-EIO);
2278
2279         /*
2280          * by this time, the object's ldo_stripe_count and ldo_stripe_size
2281          * contain default value for striping: taken from the parent
2282          * or from filesystem defaults
2283          *
2284          * in case the caller is passing lovea with new striping config,
2285          * we may need to parse lovea and apply new configuration
2286          */
2287         rc = lod_qos_parse_config(env, lo, buf);
2288         if (rc)
2289                 RETURN(rc);
2290
2291         if (attr->la_valid & LA_SIZE)
2292                 size = attr->la_size;
2293
2294         /* prepare inuse */
2295         rc = lod_prepare_inuse(env, lo);
2296         if (rc)
2297                 RETURN(rc);
2298
2299         /**
2300          * prepare OST object creation for the component covering file's
2301          * size, the 1st component (including plain layout file) is always
2302          * instantiated.
2303          */
2304         for (i = 0; i < lo->ldo_comp_cnt; i++) {
2305                 struct lod_layout_component *lod_comp;
2306                 struct lu_extent *extent;
2307
2308                 lod_comp = &lo->ldo_comp_entries[i];
2309                 extent = &lod_comp->llc_extent;
2310                 CDEBUG(D_QOS, "%lld [%lld, %lld)\n",
2311                        size, extent->e_start, extent->e_end);
2312                 if (!lo->ldo_is_composite || size >= extent->e_start) {
2313                         rc = lod_qos_prep_create(env, lo, attr, th, i, inuse);
2314                         if (rc)
2315                                 break;
2316                 }
2317         }
2318
2319         RETURN(rc);
2320 }