Whamcloud - gitweb
LU-13920 hsm: process hsm_actions only after mdd setup
[fs/lustre-release.git] / lustre / mdt / mdt_coordinator.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 (c) 2011, 2012 Commissariat a l'energie atomique et aux energies
24  *                          alternatives
25  *
26  * Copyright (c) 2013, 2017, Intel Corporation.
27  * Use is subject to license terms.
28  */
29 /*
30  * lustre/mdt/mdt_coordinator.c
31  *
32  * Lustre HSM Coordinator
33  *
34  * Author: Jacques-Charles Lafoucriere <jacques-charles.lafoucriere@cea.fr>
35  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
36  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
37  */
38
39 #define DEBUG_SUBSYSTEM S_MDS
40
41 #include <linux/kthread.h>
42 #include <obd_support.h>
43 #include <lustre_export.h>
44 #include <obd.h>
45 #include <lprocfs_status.h>
46 #include <lustre_log.h>
47 #include <lustre_kernelcomm.h>
48 #include "mdt_internal.h"
49
50 /**
51  * get obj and HSM attributes on a fid
52  * \param mti [IN] context
53  * \param fid [IN] object fid
54  * \param hsm [OUT] HSM meta data
55  * \retval obj or error (-ENOENT if not found)
56  */
57 struct mdt_object *mdt_hsm_get_md_hsm(struct mdt_thread_info *mti,
58                                       const struct lu_fid *fid,
59                                       struct md_hsm *hsm)
60 {
61         struct md_attr          *ma;
62         struct mdt_object       *obj;
63         int                      rc;
64         ENTRY;
65
66         ma = &mti->mti_attr;
67         ma->ma_need = MA_HSM;
68         ma->ma_valid = 0;
69
70         /* find object by FID */
71         obj = mdt_object_find(mti->mti_env, mti->mti_mdt, fid);
72         if (IS_ERR(obj))
73                 RETURN(obj);
74
75         if (!mdt_object_exists(obj)) {
76                 /* no more object */
77                 mdt_object_put(mti->mti_env, obj);
78                 RETURN(ERR_PTR(-ENOENT));
79         }
80
81         rc = mdt_attr_get_complex(mti, obj, ma);
82         if (rc) {
83                 mdt_object_put(mti->mti_env, obj);
84                 RETURN(ERR_PTR(rc));
85         }
86
87         if (ma->ma_valid & MA_HSM)
88                 *hsm = ma->ma_hsm;
89         else
90                 memset(hsm, 0, sizeof(*hsm));
91         ma->ma_valid = 0;
92         RETURN(obj);
93 }
94
95 void mdt_hsm_dump_hal(int level, const char *prefix,
96                       struct hsm_action_list *hal)
97 {
98         int                      i, sz;
99         struct hsm_action_item  *hai;
100         char                     buf[12];
101
102         CDEBUG(level, "%s: HAL header: version %X count %d"
103                       " archive_id %d flags %#llx\n",
104                prefix, hal->hal_version, hal->hal_count,
105                hal->hal_archive_id, hal->hal_flags);
106
107         hai = hai_first(hal);
108         for (i = 0; i < hal->hal_count; i++) {
109                 sz = hai->hai_len - sizeof(*hai);
110                 CDEBUG(level, "%s %d: fid="DFID" dfid="DFID
111                        " cookie=%#llx"
112                        " action=%s extent=%#llx-%#llx gid=%#llx"
113                        " datalen=%d data=[%s]\n",
114                        prefix, i,
115                        PFID(&hai->hai_fid), PFID(&hai->hai_dfid),
116                        hai->hai_cookie,
117                        hsm_copytool_action2name(hai->hai_action),
118                        hai->hai_extent.offset,
119                        hai->hai_extent.length,
120                        hai->hai_gid, sz,
121                        hai_dump_data_field(hai, buf, sizeof(buf)));
122                 hai = hai_next(hai);
123         }
124 }
125
126 /**
127  * data passed to llog_cat_process() callback
128  * to scan requests and take actions
129  */
130 struct hsm_scan_request {
131         int                      hal_sz;
132         int                      hal_used_sz;
133         struct hsm_action_list  *hal;
134 };
135
136 struct hsm_scan_data {
137         struct mdt_thread_info  *hsd_mti;
138         char                     hsd_fsname[MTI_NAME_MAXLEN + 1];
139         /* are we scanning the logs for housekeeping, or just looking
140          * for new work?
141          */
142         bool                     hsd_housekeeping;
143         bool                     hsd_one_restore;
144         int                      hsd_action_count;
145         int                      hsd_request_len; /* array alloc len */
146         int                      hsd_request_count; /* array used count */
147         struct hsm_scan_request *hsd_request;
148 };
149
150 static int mdt_cdt_waiting_cb(const struct lu_env *env,
151                               struct mdt_device *mdt,
152                               struct llog_handle *llh,
153                               struct llog_agent_req_rec *larr,
154                               struct hsm_scan_data *hsd)
155 {
156         struct coordinator *cdt = &mdt->mdt_coordinator;
157         struct hsm_scan_request *request;
158         struct hsm_action_item *hai;
159         size_t hai_size;
160         u32 archive_id;
161         int i;
162
163         /* Are agents full? */
164         if (atomic_read(&cdt->cdt_request_count) >= cdt->cdt_max_requests)
165                 RETURN(hsd->hsd_housekeeping ? 0 : LLOG_PROC_BREAK);
166
167         if (hsd->hsd_action_count + atomic_read(&cdt->cdt_request_count) >=
168             cdt->cdt_max_requests) {
169                 /* We cannot send any more request
170                  *
171                  *                     *** SPECIAL CASE ***
172                  *
173                  * Restore requests are too important not to schedule at least
174                  * one, everytime we can.
175                  */
176                 if (larr->arr_hai.hai_action != HSMA_RESTORE ||
177                     hsd->hsd_one_restore)
178                         RETURN(hsd->hsd_housekeeping ? 0 : LLOG_PROC_BREAK);
179         }
180
181         hai_size = cfs_size_round(larr->arr_hai.hai_len);
182         archive_id = larr->arr_archive_id;
183
184         /* Can we add this action to one of the existing HALs in hsd. */
185         request = NULL;
186         for (i = 0; i < hsd->hsd_request_count; i++) {
187                 if (hsd->hsd_request[i].hal->hal_archive_id == archive_id &&
188                     hsd->hsd_request[i].hal_used_sz + hai_size <=
189                     LDLM_MAXREQSIZE) {
190                         request = &hsd->hsd_request[i];
191                         break;
192                 }
193         }
194
195         /* Are we trying to force-schedule a request? */
196         if (hsd->hsd_action_count + atomic_read(&cdt->cdt_request_count) >=
197             cdt->cdt_max_requests) {
198                 /* Is there really no compatible hsm_scan_request? */
199                 if (!request) {
200                         for (i -= 1; i >= 0; i--) {
201                                 if (hsd->hsd_request[i].hal->hal_archive_id ==
202                                     archive_id) {
203                                         request = &hsd->hsd_request[i];
204                                         break;
205                                 }
206                         }
207                 }
208
209                 /* Make room for the hai */
210                 if (request) {
211                         /* Discard the last hai until there is enough space */
212                         do {
213                                 request->hal->hal_count--;
214
215                                 hai = hai_first(request->hal);
216                                 for (i = 0; i < request->hal->hal_count; i++)
217                                         hai = hai_next(hai);
218                                 request->hal_used_sz -=
219                                         cfs_size_round(hai->hai_len);
220                                 hsd->hsd_action_count--;
221                         } while (request->hal_used_sz + hai_size >
222                                  LDLM_MAXREQSIZE);
223                 } else if (hsd->hsd_housekeeping) {
224                         struct hsm_scan_request *tmp;
225
226                         /* Discard the (whole) last hal */
227                         hsd->hsd_request_count--;
228                         LASSERT(hsd->hsd_request_count >= 0);
229                         tmp = &hsd->hsd_request[hsd->hsd_request_count];
230                         hsd->hsd_action_count -= tmp->hal->hal_count;
231                         LASSERT(hsd->hsd_action_count >= 0);
232                         OBD_FREE(tmp->hal, tmp->hal_sz);
233                 } else {
234                         /* Bailing out, this code path is too hot */
235                         RETURN(LLOG_PROC_BREAK);
236
237                 }
238         }
239
240         if (!request) {
241                 struct hsm_action_list *hal;
242
243                 LASSERT(hsd->hsd_request_count < hsd->hsd_request_len);
244                 request = &hsd->hsd_request[hsd->hsd_request_count];
245
246                 /* allocates hai vector size just needs to be large
247                  * enough */
248                 request->hal_sz = sizeof(*request->hal) +
249                         cfs_size_round(MTI_NAME_MAXLEN + 1) + 2 * hai_size;
250                 OBD_ALLOC_LARGE(hal, request->hal_sz);
251                 if (!hal)
252                         RETURN(-ENOMEM);
253
254                 hal->hal_version = HAL_VERSION;
255                 strlcpy(hal->hal_fsname, hsd->hsd_fsname, MTI_NAME_MAXLEN + 1);
256                 hal->hal_archive_id = larr->arr_archive_id;
257                 hal->hal_flags = larr->arr_flags;
258                 hal->hal_count = 0;
259                 request->hal_used_sz = hal_size(hal);
260                 request->hal = hal;
261                 hsd->hsd_request_count++;
262         } else if (request->hal_sz < request->hal_used_sz + hai_size) {
263                 /* Not enough room, need an extension */
264                 void *hal_buffer;
265                 int sz;
266
267                 sz = min_t(int, 2 * request->hal_sz, LDLM_MAXREQSIZE);
268                 LASSERT(request->hal_used_sz + hai_size < sz);
269
270                 OBD_ALLOC_LARGE(hal_buffer, sz);
271                 if (!hal_buffer)
272                         RETURN(-ENOMEM);
273
274                 memcpy(hal_buffer, request->hal, request->hal_used_sz);
275                 OBD_FREE_LARGE(request->hal, request->hal_sz);
276                 request->hal = hal_buffer;
277                 request->hal_sz = sz;
278         }
279
280         hai = hai_first(request->hal);
281         for (i = 0; i < request->hal->hal_count; i++)
282                 hai = hai_next(hai);
283
284         memcpy(hai, &larr->arr_hai, larr->arr_hai.hai_len);
285
286         request->hal_used_sz += hai_size;
287         request->hal->hal_count++;
288
289         hsd->hsd_action_count++;
290
291         switch (hai->hai_action) {
292         case HSMA_CANCEL:
293                 break;
294         case HSMA_RESTORE:
295                 hsd->hsd_one_restore = true;
296                 /* Intentional fallthrough */
297         default:
298                 cdt_agent_record_hash_add(cdt, hai->hai_cookie,
299                                           llh->lgh_hdr->llh_cat_idx,
300                                           larr->arr_hdr.lrh_index);
301         }
302
303         RETURN(0);
304 }
305
306 static int mdt_cdt_started_cb(const struct lu_env *env,
307                               struct mdt_device *mdt,
308                               struct llog_handle *llh,
309                               struct llog_agent_req_rec *larr,
310                               struct hsm_scan_data *hsd)
311 {
312         struct coordinator *cdt = &mdt->mdt_coordinator;
313         struct hsm_action_item *hai = &larr->arr_hai;
314         struct cdt_agent_req *car;
315         time64_t now = ktime_get_real_seconds();
316         time64_t last;
317         enum changelog_rec_flags clf_flags;
318         int rc;
319
320         if (!hsd->hsd_housekeeping)
321                 RETURN(0);
322
323         /* we search for a running request
324          * error may happen if coordinator crashes or stopped
325          * with running request
326          */
327         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
328         if (car == NULL) {
329                 last = larr->arr_req_change;
330         } else {
331                 last = car->car_req_update;
332         }
333
334         /* test if request too long, if yes cancel it
335          * the same way the copy tool acknowledge a cancel request */
336         if (now <= last + cdt->cdt_active_req_timeout)
337                 GOTO(out_car, rc = 0);
338
339         dump_llog_agent_req_rec("request timed out, start cleaning", larr);
340
341         if (car != NULL) {
342                 car->car_req_update = now;
343                 mdt_hsm_agent_update_statistics(cdt, 0, 1, 0, &car->car_uuid);
344                 /* Remove car from memory list (LU-9075) */
345                 mdt_cdt_remove_request(cdt, hai->hai_cookie);
346         }
347
348         /* Emit a changelog record for the failed action.*/
349         clf_flags = 0;
350         hsm_set_cl_error(&clf_flags, ECANCELED);
351
352         switch (hai->hai_action) {
353         case HSMA_ARCHIVE:
354                 hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
355                 break;
356         case HSMA_RESTORE:
357                 hsm_set_cl_event(&clf_flags, HE_RESTORE);
358                 break;
359         case HSMA_REMOVE:
360                 hsm_set_cl_event(&clf_flags, HE_REMOVE);
361                 break;
362         case HSMA_CANCEL:
363                 hsm_set_cl_event(&clf_flags, HE_CANCEL);
364                 break;
365         default:
366                 /* Unknown record type, skip changelog. */
367                 clf_flags = 0;
368                 break;
369         }
370
371         if (clf_flags != 0)
372                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
373                              &hai->hai_fid);
374
375         if (hai->hai_action == HSMA_RESTORE)
376                 cdt_restore_handle_del(hsd->hsd_mti, cdt, &hai->hai_fid);
377
378         larr->arr_status = ARS_CANCELED;
379         larr->arr_req_change = now;
380         rc = llog_write(hsd->hsd_mti->mti_env, llh, &larr->arr_hdr,
381                         larr->arr_hdr.lrh_index);
382         if (rc < 0) {
383                 CERROR("%s: cannot update agent log: rc = %d\n",
384                        mdt_obd_name(mdt), rc);
385                 rc = LLOG_DEL_RECORD;
386         }
387
388         /* ct has completed a request, so a slot is available,
389          * signal the coordinator to find new work */
390         mdt_hsm_cdt_event(cdt);
391 out_car:
392         if (car != NULL)
393                 mdt_cdt_put_request(car);
394
395         RETURN(rc);
396 }
397
398 /**
399  *  llog_cat_process() callback, used to:
400  *  - find waiting request and start action
401  *  - purge canceled and done requests
402  * \param env [IN] environment
403  * \param llh [IN] llog handle
404  * \param hdr [IN] llog record
405  * \param data [IN/OUT] cb data = struct hsm_scan_data
406  * \retval 0 success
407  * \retval -ve failure
408  */
409 static int mdt_coordinator_cb(const struct lu_env *env,
410                               struct llog_handle *llh,
411                               struct llog_rec_hdr *hdr,
412                               void *data)
413 {
414         struct llog_agent_req_rec *larr = (struct llog_agent_req_rec *)hdr;
415         struct hsm_scan_data *hsd = data;
416         struct mdt_device *mdt = hsd->hsd_mti->mti_mdt;
417         struct coordinator *cdt = &mdt->mdt_coordinator;
418         ENTRY;
419
420         larr = (struct llog_agent_req_rec *)hdr;
421         dump_llog_agent_req_rec("mdt_coordinator_cb(): ", larr);
422         switch (larr->arr_status) {
423         case ARS_WAITING:
424                 RETURN(mdt_cdt_waiting_cb(env, mdt, llh, larr, hsd));
425         case ARS_STARTED:
426                 RETURN(mdt_cdt_started_cb(env, mdt, llh, larr, hsd));
427         default:
428                 if (!hsd->hsd_housekeeping)
429                         RETURN(0);
430
431                 if ((larr->arr_req_change + cdt->cdt_grace_delay) <
432                     ktime_get_real_seconds()) {
433                         cdt_agent_record_hash_del(cdt,
434                                                   larr->arr_hai.hai_cookie);
435                         RETURN(LLOG_DEL_RECORD);
436                 }
437
438                 RETURN(0);
439         }
440 }
441
442 /* Release the ressource used by the coordinator. Called when the
443  * coordinator is stopping. */
444 static void mdt_hsm_cdt_cleanup(struct mdt_device *mdt)
445 {
446         struct coordinator              *cdt = &mdt->mdt_coordinator;
447         struct cdt_agent_req            *car, *tmp1;
448         struct hsm_agent                *ha, *tmp2;
449         struct cdt_restore_handle       *crh, *tmp3;
450         struct mdt_thread_info          *cdt_mti;
451
452         /* start cleaning */
453         down_write(&cdt->cdt_request_lock);
454         list_for_each_entry_safe(car, tmp1, &cdt->cdt_request_list,
455                                  car_request_list) {
456                 cfs_hash_del(cdt->cdt_request_cookie_hash,
457                              &car->car_hai->hai_cookie,
458                              &car->car_cookie_hash);
459                 list_del(&car->car_request_list);
460                 mdt_cdt_put_request(car);
461         }
462         up_write(&cdt->cdt_request_lock);
463
464         down_write(&cdt->cdt_agent_lock);
465         list_for_each_entry_safe(ha, tmp2, &cdt->cdt_agents, ha_list) {
466                 list_del(&ha->ha_list);
467                 if (ha->ha_archive_cnt != 0)
468                         OBD_FREE_PTR_ARRAY(ha->ha_archive_id,
469                                            ha->ha_archive_cnt);
470                 OBD_FREE_PTR(ha);
471         }
472         up_write(&cdt->cdt_agent_lock);
473
474         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
475         mutex_lock(&cdt->cdt_restore_lock);
476         list_for_each_entry_safe(crh, tmp3, &cdt->cdt_restore_handle_list,
477                                  crh_list) {
478                 list_del(&crh->crh_list);
479                 /* give back layout lock */
480                 mdt_object_unlock(cdt_mti, NULL, &crh->crh_lh, 1);
481                 OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
482         }
483         mutex_unlock(&cdt->cdt_restore_lock);
484 }
485
486 /*
487  * Coordinator state transition table, indexed on enum cdt_states, taking
488  * from and to states. For instance since CDT_INIT to CDT_RUNNING is a
489  * valid transition, cdt_transition[CDT_INIT][CDT_RUNNING] is true.
490  */
491 static bool cdt_transition[CDT_STATES_COUNT][CDT_STATES_COUNT] = {
492         /* from -> to:    stopped init   running disable stopping */
493         /* stopped */   { true,   true,  false,  false,  false },
494         /* init */      { true,   false, true,   false,  false },
495         /* running */   { false,  false, true,   true,   true },
496         /* disable */   { false,  false, true,   true,   true },
497         /* stopping */  { true,   false, false,  false,  false }
498 };
499
500 /**
501  * Change coordinator thread state
502  * Some combinations are not valid, so catch them here.
503  *
504  * Returns 0 on success, with old_state set if not NULL, or -EINVAL if
505  * the transition was not possible.
506  */
507 static int set_cdt_state_locked(struct coordinator *cdt,
508                                 enum cdt_states new_state)
509 {
510         int rc;
511         enum cdt_states state;
512
513         state = cdt->cdt_state;
514
515         if (cdt_transition[state][new_state]) {
516                 cdt->cdt_state = new_state;
517                 rc = 0;
518         } else {
519                 CDEBUG(D_HSM,
520                        "unexpected coordinator transition, from=%s, to=%s\n",
521                        cdt_mdt_state2str(state), cdt_mdt_state2str(new_state));
522                 rc = -EINVAL;
523         }
524
525         return rc;
526 }
527
528 static int set_cdt_state(struct coordinator *cdt, enum cdt_states new_state)
529 {
530         int rc;
531
532         mutex_lock(&cdt->cdt_state_lock);
533         rc = set_cdt_state_locked(cdt, new_state);
534         mutex_unlock(&cdt->cdt_state_lock);
535
536         return rc;
537 }
538
539
540
541 /**
542  * coordinator thread
543  * \param data [IN] obd device
544  * \retval 0 success
545  * \retval -ve failure
546  */
547 static int mdt_coordinator(void *data)
548 {
549         struct mdt_thread_info  *mti = data;
550         struct mdt_device       *mdt = mti->mti_mdt;
551         struct coordinator      *cdt = &mdt->mdt_coordinator;
552         struct hsm_scan_data     hsd = { NULL };
553         time64_t                 last_housekeeping = 0;
554         size_t request_sz = 0;
555         int rc;
556         ENTRY;
557
558         CDEBUG(D_HSM, "%s: coordinator thread starting, pid=%d\n",
559                mdt_obd_name(mdt), current->pid);
560
561         hsd.hsd_mti = mti;
562         obd_uuid2fsname(hsd.hsd_fsname, mdt_obd_name(mdt),
563                         sizeof(hsd.hsd_fsname));
564
565         set_cdt_state(cdt, CDT_RUNNING);
566
567         /* Inform mdt_hsm_cdt_start(). */
568         wake_up_all(&cdt->cdt_waitq);
569
570         while (1) {
571                 int i;
572                 int update_idx = 0;
573                 int updates_sz;
574                 int updates_cnt;
575                 struct hsm_record_update *updates;
576
577                 /* Limit execution of the expensive requests traversal
578                  * to at most one second. This prevents repeatedly
579                  * locking/unlocking the catalog for each request
580                  * and preventing other HSM operations from happening
581                  */
582                 wait_event_interruptible_timeout(cdt->cdt_waitq,
583                                                  kthread_should_stop() ||
584                                                  cdt->cdt_wakeup_coordinator,
585                                                  cfs_time_seconds(1));
586
587                 cdt->cdt_wakeup_coordinator = false;
588                 CDEBUG(D_HSM, "coordinator resumes\n");
589
590                 if (kthread_should_stop()) {
591                         CDEBUG(D_HSM, "Coordinator stops\n");
592                         rc = 0;
593                         break;
594                 }
595
596                 /* if coordinator is suspended continue to wait */
597                 if (cdt->cdt_state == CDT_DISABLE) {
598                         CDEBUG(D_HSM, "disable state, coordinator sleeps\n");
599                         continue;
600                 }
601
602                 /* If no event, and no housekeeping to do, continue to
603                  * wait. */
604                 if (last_housekeeping + cdt->cdt_loop_period <=
605                     ktime_get_real_seconds()) {
606                         last_housekeeping = ktime_get_real_seconds();
607                         hsd.hsd_housekeeping = true;
608                 } else if (cdt->cdt_event) {
609                         hsd.hsd_housekeeping = false;
610                 } else {
611                         continue;
612                 }
613
614                 cdt->cdt_event = false;
615
616                 CDEBUG(D_HSM, "coordinator starts reading llog\n");
617
618                 if (hsd.hsd_request_len != cdt->cdt_max_requests) {
619                         /* cdt_max_requests has changed,
620                          * we need to allocate a new buffer
621                          */
622                         struct hsm_scan_request *tmp = NULL;
623                         int max_requests = cdt->cdt_max_requests;
624                         OBD_ALLOC_LARGE(tmp, max_requests *
625                                         sizeof(struct hsm_scan_request));
626                         if (!tmp) {
627                                 CERROR("Failed to resize request buffer, "
628                                        "keeping it at %d\n",
629                                        hsd.hsd_request_len);
630                         } else {
631                                 if (hsd.hsd_request != NULL)
632                                         OBD_FREE_LARGE(hsd.hsd_request,
633                                                        request_sz);
634
635                                 hsd.hsd_request_len = max_requests;
636                                 request_sz = hsd.hsd_request_len *
637                                         sizeof(struct hsm_scan_request);
638                                 hsd.hsd_request = tmp;
639                         }
640                 }
641
642                 hsd.hsd_action_count = 0;
643                 hsd.hsd_request_count = 0;
644                 hsd.hsd_one_restore = false;
645
646                 rc = cdt_llog_process(mti->mti_env, mdt, mdt_coordinator_cb,
647                                       &hsd, 0, 0, WRITE);
648                 if (rc < 0)
649                         goto clean_cb_alloc;
650
651                 CDEBUG(D_HSM, "found %d requests to send\n",
652                        hsd.hsd_request_count);
653
654                 if (list_empty(&cdt->cdt_agents)) {
655                         CDEBUG(D_HSM, "no agent available, "
656                                       "coordinator sleeps\n");
657                         goto clean_cb_alloc;
658                 }
659
660                 /* Compute how many HAI we have in all the requests */
661                 updates_cnt = 0;
662                 for (i = 0; i < hsd.hsd_request_count; i++) {
663                         const struct hsm_scan_request *request =
664                                 &hsd.hsd_request[i];
665
666                         updates_cnt += request->hal->hal_count;
667                 }
668
669                 /* Allocate a temporary array to store the cookies to
670                  * update, and their status. */
671                 updates_sz = updates_cnt * sizeof(*updates);
672                 OBD_ALLOC_LARGE(updates, updates_sz);
673                 if (updates == NULL) {
674                         CERROR("%s: Cannot allocate memory (%d bytes) "
675                                "for %d updates. Too many HSM requests?\n",
676                                mdt_obd_name(mdt), updates_sz, updates_cnt);
677                         goto clean_cb_alloc;
678                 }
679
680                 /* here hsd contains a list of requests to be started */
681                 for (i = 0; i < hsd.hsd_request_count; i++) {
682                         struct hsm_scan_request *request = &hsd.hsd_request[i];
683                         struct hsm_action_list  *hal = request->hal;
684                         struct hsm_action_item  *hai;
685                         int                      j;
686
687                         /* still room for work ? */
688                         if (atomic_read(&cdt->cdt_request_count) >=
689                             cdt->cdt_max_requests)
690                                 break;
691
692                         rc = mdt_hsm_agent_send(mti, hal, 0);
693                         /* if failure, we suppose it is temporary
694                          * if the copy tool failed to do the request
695                          * it has to use hsm_progress
696                          */
697
698                         /* set up cookie vector to set records status
699                          * after copy tools start or failed
700                          */
701                         hai = hai_first(hal);
702                         for (j = 0; j < hal->hal_count; j++) {
703                                 updates[update_idx].cookie = hai->hai_cookie;
704                                 updates[update_idx].status =
705                                         (rc ? ARS_WAITING : ARS_STARTED);
706                                 hai = hai_next(hai);
707                                 update_idx++;
708                         }
709                 }
710
711                 if (update_idx) {
712                         rc = mdt_agent_record_update(mti->mti_env, mdt,
713                                                      updates, update_idx);
714                         if (rc)
715                                 CERROR("%s: mdt_agent_record_update() failed, "
716                                        "rc=%d, cannot update records "
717                                        "for %d cookies\n",
718                                        mdt_obd_name(mdt), rc, update_idx);
719                 }
720
721                 OBD_FREE_LARGE(updates, updates_sz);
722
723 clean_cb_alloc:
724                 /* free hal allocated by callback */
725                 for (i = 0; i < hsd.hsd_request_count; i++) {
726                         struct hsm_scan_request *request = &hsd.hsd_request[i];
727
728                         OBD_FREE_LARGE(request->hal, request->hal_sz);
729                 }
730         }
731
732         if (hsd.hsd_request != NULL)
733                 OBD_FREE_LARGE(hsd.hsd_request, request_sz);
734
735         mdt_hsm_cdt_cleanup(mdt);
736
737         if (rc != 0)
738                 CERROR("%s: coordinator thread exiting, process=%d, rc=%d\n",
739                        mdt_obd_name(mdt), current->pid, rc);
740         else
741                 CDEBUG(D_HSM, "%s: coordinator thread exiting, process=%d,"
742                               " no error\n",
743                        mdt_obd_name(mdt), current->pid);
744
745         RETURN(rc);
746 }
747
748 int cdt_restore_handle_add(struct mdt_thread_info *mti, struct coordinator *cdt,
749                            const struct lu_fid *fid,
750                            const struct hsm_extent *he)
751 {
752         struct cdt_restore_handle *crh;
753         struct mdt_object *obj;
754         int rc;
755         ENTRY;
756
757         OBD_SLAB_ALLOC_PTR(crh, mdt_hsm_cdt_kmem);
758         if (crh == NULL)
759                 RETURN(-ENOMEM);
760
761         crh->crh_fid = *fid;
762         /* in V1 all file is restored
763          * crh->extent.start = he->offset;
764          * crh->extent.end = he->offset + he->length;
765          */
766         crh->crh_extent.start = 0;
767         crh->crh_extent.end = he->length;
768         /* get the layout lock */
769         mdt_lock_reg_init(&crh->crh_lh, LCK_EX);
770         obj = mdt_object_find_lock(mti, &crh->crh_fid, &crh->crh_lh,
771                                    MDS_INODELOCK_LAYOUT);
772         if (IS_ERR(obj))
773                 GOTO(out_crh, rc = PTR_ERR(obj));
774
775         /* We do not keep a reference on the object during the restore
776          * which can be very long. */
777         mdt_object_put(mti->mti_env, obj);
778
779         mutex_lock(&cdt->cdt_restore_lock);
780         if (unlikely(cdt->cdt_state == CDT_STOPPED ||
781                      cdt->cdt_state == CDT_STOPPING)) {
782                 mutex_unlock(&cdt->cdt_restore_lock);
783                 GOTO(out_lh, rc = -EAGAIN);
784         }
785
786         list_add_tail(&crh->crh_list, &cdt->cdt_restore_handle_list);
787         mutex_unlock(&cdt->cdt_restore_lock);
788
789         RETURN(0);
790 out_lh:
791         mdt_object_unlock(mti, NULL, &crh->crh_lh, 1);
792 out_crh:
793         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
794
795         return rc;
796 }
797
798 /**
799  * lookup a restore handle by FID
800  * caller needs to hold cdt_restore_lock
801  * \param cdt [IN] coordinator
802  * \param fid [IN] FID
803  * \retval cdt_restore_handle found
804  * \retval NULL not found
805  */
806 struct cdt_restore_handle *cdt_restore_handle_find(struct coordinator *cdt,
807                                                    const struct lu_fid *fid)
808 {
809         struct cdt_restore_handle *crh;
810         ENTRY;
811
812         list_for_each_entry(crh, &cdt->cdt_restore_handle_list, crh_list) {
813                 if (lu_fid_eq(&crh->crh_fid, fid))
814                         RETURN(crh);
815         }
816
817         RETURN(NULL);
818 }
819
820 void cdt_restore_handle_del(struct mdt_thread_info *mti,
821                             struct coordinator *cdt, const struct lu_fid *fid)
822 {
823         struct cdt_restore_handle *crh;
824
825         /* give back layout lock */
826         mutex_lock(&cdt->cdt_restore_lock);
827         crh = cdt_restore_handle_find(cdt, fid);
828         if (crh != NULL)
829                 list_del(&crh->crh_list);
830         mutex_unlock(&cdt->cdt_restore_lock);
831
832         if (crh == NULL)
833                 return;
834
835         /* XXX We pass a NULL object since the restore handle does not
836          * keep a reference on the object being restored. */
837         mdt_object_unlock(mti, NULL, &crh->crh_lh, 1);
838         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
839 }
840
841 /**
842  * data passed to llog_cat_process() callback
843  * to scan requests and take actions
844  */
845 struct hsm_restore_data {
846         struct mdt_thread_info  *hrd_mti;
847 };
848
849 /**
850  *  llog_cat_process() callback, used to:
851  *  - find restore request and allocate the restore handle
852  * \param env [IN] environment
853  * \param llh [IN] llog handle
854  * \param hdr [IN] llog record
855  * \param data [IN/OUT] cb data = struct hsm_restore_data
856  * \retval 0 success
857  * \retval -ve failure
858  */
859 static int hsm_restore_cb(const struct lu_env *env,
860                           struct llog_handle *llh,
861                           struct llog_rec_hdr *hdr, void *data)
862 {
863         struct llog_agent_req_rec       *larr;
864         struct hsm_restore_data         *hrd;
865         struct hsm_action_item          *hai;
866         struct mdt_thread_info          *mti;
867         struct coordinator              *cdt;
868         int rc;
869         ENTRY;
870
871         hrd = data;
872         mti = hrd->hrd_mti;
873         cdt = &mti->mti_mdt->mdt_coordinator;
874
875         larr = (struct llog_agent_req_rec *)hdr;
876         hai = &larr->arr_hai;
877         if (hai->hai_cookie >= cdt->cdt_last_cookie) {
878                 /* update the cookie to avoid collision */
879                 cdt->cdt_last_cookie = hai->hai_cookie + 1;
880         }
881
882         if (hai->hai_action != HSMA_RESTORE ||
883             agent_req_in_final_state(larr->arr_status))
884                 RETURN(0);
885
886         /* restore request not in a final state */
887
888         /* force replay of restore requests left in started state from previous
889          * CDT context, to be canceled later if finally found to be incompatible
890          * when being re-started */
891         if (larr->arr_status == ARS_STARTED) {
892                 larr->arr_status = ARS_WAITING;
893                 larr->arr_req_change = ktime_get_real_seconds();
894                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
895                 if (rc != 0)
896                         GOTO(out, rc);
897         }
898
899         rc = cdt_restore_handle_add(mti, cdt, &hai->hai_fid, &hai->hai_extent);
900 out:
901         RETURN(rc);
902 }
903
904 /**
905  * restore coordinator state at startup
906  * the goal is to take a layout lock for each registered restore request
907  * \param mti [IN] context
908  */
909 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti)
910 {
911         struct hsm_restore_data  hrd;
912         int                      rc;
913         ENTRY;
914
915         hrd.hrd_mti = mti;
916
917         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt, hsm_restore_cb, &hrd,
918                               0, 0, WRITE);
919
920         RETURN(rc);
921 }
922
923 int hsm_init_ucred(struct lu_ucred *uc)
924 {
925         ENTRY;
926
927         uc->uc_valid = UCRED_OLD;
928         uc->uc_o_uid = 0;
929         uc->uc_o_gid = 0;
930         uc->uc_o_fsuid = 0;
931         uc->uc_o_fsgid = 0;
932         uc->uc_uid = 0;
933         uc->uc_gid = 0;
934         uc->uc_fsuid = 0;
935         uc->uc_fsgid = 0;
936         uc->uc_suppgids[0] = -1;
937         uc->uc_suppgids[1] = -1;
938         uc->uc_cap = CFS_CAP_FS_MASK;
939         uc->uc_umask = 0777;
940         uc->uc_ginfo = NULL;
941         uc->uc_identity = NULL;
942         /* always record internal HSM activity if also enabled globally */
943         uc->uc_enable_audit = 1;
944
945         RETURN(0);
946 }
947
948 /**
949  * initialize coordinator struct
950  * \param mdt [IN] device
951  * \retval 0 success
952  * \retval -ve failure
953  */
954 int mdt_hsm_cdt_init(struct mdt_device *mdt)
955 {
956         struct coordinator      *cdt = &mdt->mdt_coordinator;
957         struct mdt_thread_info  *cdt_mti = NULL;
958         int                      rc;
959         ENTRY;
960
961         init_waitqueue_head(&cdt->cdt_waitq);
962         init_rwsem(&cdt->cdt_llog_lock);
963         init_rwsem(&cdt->cdt_agent_lock);
964         init_rwsem(&cdt->cdt_request_lock);
965         mutex_init(&cdt->cdt_restore_lock);
966         mutex_init(&cdt->cdt_state_lock);
967         set_cdt_state(cdt, CDT_STOPPED);
968
969         INIT_LIST_HEAD(&cdt->cdt_request_list);
970         INIT_LIST_HEAD(&cdt->cdt_agents);
971         INIT_LIST_HEAD(&cdt->cdt_restore_handle_list);
972
973         cdt->cdt_request_cookie_hash = cfs_hash_create("REQUEST_COOKIE_HASH",
974                                                        CFS_HASH_BITS_MIN,
975                                                        CFS_HASH_BITS_MAX,
976                                                        CFS_HASH_BKT_BITS,
977                                                        0 /* extra bytes */,
978                                                        CFS_HASH_MIN_THETA,
979                                                        CFS_HASH_MAX_THETA,
980                                                 &cdt_request_cookie_hash_ops,
981                                                        CFS_HASH_DEFAULT);
982         if (cdt->cdt_request_cookie_hash == NULL)
983                 RETURN(-ENOMEM);
984
985         cdt->cdt_agent_record_hash = cfs_hash_create("AGENT_RECORD_HASH",
986                                                      CFS_HASH_BITS_MIN,
987                                                      CFS_HASH_BITS_MAX,
988                                                      CFS_HASH_BKT_BITS,
989                                                      0 /* extra bytes */,
990                                                      CFS_HASH_MIN_THETA,
991                                                      CFS_HASH_MAX_THETA,
992                                                      &cdt_agent_record_hash_ops,
993                                                      CFS_HASH_DEFAULT);
994         if (cdt->cdt_agent_record_hash == NULL)
995                 GOTO(out_request_cookie_hash, rc = -ENOMEM);
996
997         rc = lu_env_init(&cdt->cdt_env, LCT_MD_THREAD);
998         if (rc < 0)
999                 GOTO(out_agent_record_hash, rc);
1000
1001         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1002         rc = lu_context_init(&cdt->cdt_session, LCT_SERVER_SESSION);
1003         if (rc < 0)
1004                 GOTO(out_env, rc);
1005
1006         lu_context_enter(&cdt->cdt_session);
1007         cdt->cdt_env.le_ses = &cdt->cdt_session;
1008
1009         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1010         LASSERT(cdt_mti != NULL);
1011
1012         cdt_mti->mti_env = &cdt->cdt_env;
1013         cdt_mti->mti_mdt = mdt;
1014
1015         hsm_init_ucred(mdt_ucred(cdt_mti));
1016
1017         /* default values for sysfs tunnables
1018          * can be override by MGS conf */
1019         cdt->cdt_default_archive_id = 1;
1020         cdt->cdt_grace_delay = 60;
1021         cdt->cdt_loop_period = 10;
1022         cdt->cdt_max_requests = 3;
1023         cdt->cdt_policy = CDT_DEFAULT_POLICY;
1024         cdt->cdt_active_req_timeout = 3600;
1025
1026         /* by default do not remove archives on last unlink */
1027         cdt->cdt_remove_archive_on_last_unlink = false;
1028
1029         RETURN(0);
1030
1031 out_env:
1032         lu_env_fini(&cdt->cdt_env);
1033 out_agent_record_hash:
1034         cfs_hash_putref(cdt->cdt_agent_record_hash);
1035         cdt->cdt_agent_record_hash = NULL;
1036 out_request_cookie_hash:
1037         cfs_hash_putref(cdt->cdt_request_cookie_hash);
1038         cdt->cdt_request_cookie_hash = NULL;
1039
1040         return rc;
1041 }
1042
1043 /**
1044  * free a coordinator thread
1045  * \param mdt [IN] device
1046  */
1047 int  mdt_hsm_cdt_fini(struct mdt_device *mdt)
1048 {
1049         struct coordinator *cdt = &mdt->mdt_coordinator;
1050         ENTRY;
1051
1052         lu_context_exit(cdt->cdt_env.le_ses);
1053         lu_context_fini(cdt->cdt_env.le_ses);
1054
1055         lu_env_fini(&cdt->cdt_env);
1056
1057         cfs_hash_putref(cdt->cdt_agent_record_hash);
1058         cdt->cdt_agent_record_hash = NULL;
1059
1060         cfs_hash_putref(cdt->cdt_request_cookie_hash);
1061         cdt->cdt_request_cookie_hash = NULL;
1062
1063         RETURN(0);
1064 }
1065
1066 /**
1067  * start a coordinator thread
1068  * \param mdt [IN] device
1069  * \retval 0 success
1070  * \retval -ve failure
1071  */
1072 static int mdt_hsm_cdt_start(struct mdt_device *mdt)
1073 {
1074         struct coordinator *cdt = &mdt->mdt_coordinator;
1075         struct mdt_thread_info *cdt_mti;
1076         unsigned int i = 0;
1077         int rc;
1078         void *ptr;
1079         struct task_struct *task;
1080         ENTRY;
1081
1082         /* functions defined but not yet used
1083          * this avoid compilation warning
1084          */
1085         ptr = dump_requests;
1086
1087         rc = set_cdt_state(cdt, CDT_INIT);
1088         if (rc) {
1089                 CERROR("%s: Coordinator already started or stopping\n",
1090                        mdt_obd_name(mdt));
1091                 RETURN(-EALREADY);
1092         }
1093
1094         BUILD_BUG_ON(BIT(CDT_POLICY_SHIFT_COUNT - 1) != CDT_POLICY_LAST);
1095         cdt->cdt_policy = CDT_DEFAULT_POLICY;
1096
1097         /* just need to be larger than previous one */
1098         /* cdt_last_cookie is protected by cdt_llog_lock */
1099         cdt->cdt_last_cookie = ktime_get_real_seconds();
1100         atomic_set(&cdt->cdt_request_count, 0);
1101         atomic_set(&cdt->cdt_archive_count, 0);
1102         atomic_set(&cdt->cdt_restore_count, 0);
1103         atomic_set(&cdt->cdt_remove_count, 0);
1104         cdt->cdt_user_request_mask = (1UL << HSMA_RESTORE);
1105         cdt->cdt_group_request_mask = (1UL << HSMA_RESTORE);
1106         cdt->cdt_other_request_mask = (1UL << HSMA_RESTORE);
1107
1108         /* wait until MDD initialize hsm actions llog */
1109         while (!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state) && i < obd_timeout) {
1110                 schedule_timeout_interruptible(cfs_time_seconds(1));
1111                 i++;
1112         }
1113         if (!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state))
1114                 CWARN("%s: trying to init HSM before MDD\n", mdt_obd_name(mdt));
1115
1116         /* to avoid deadlock when start is made through sysfs
1117          * sysfs entries are created by the coordinator thread
1118          */
1119         /* set up list of started restore requests */
1120         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1121         rc = mdt_hsm_pending_restore(cdt_mti);
1122         if (rc)
1123                 CERROR("%s: cannot take the layout locks needed"
1124                        " for registered restore: %d\n",
1125                        mdt_obd_name(mdt), rc);
1126
1127         if (mdt->mdt_bottom->dd_rdonly)
1128                 RETURN(0);
1129
1130         task = kthread_run(mdt_coordinator, cdt_mti, "hsm_cdtr");
1131         if (IS_ERR(task)) {
1132                 rc = PTR_ERR(task);
1133                 set_cdt_state(cdt, CDT_STOPPED);
1134                 CERROR("%s: error starting coordinator thread: %d\n",
1135                        mdt_obd_name(mdt), rc);
1136         } else {
1137                 cdt->cdt_task = task;
1138                 wait_event(cdt->cdt_waitq,
1139                            cdt->cdt_state != CDT_INIT);
1140                 CDEBUG(D_HSM, "%s: coordinator thread started\n",
1141                        mdt_obd_name(mdt));
1142                 rc = 0;
1143         }
1144
1145         RETURN(rc);
1146 }
1147
1148 /**
1149  * stop a coordinator thread
1150  * \param mdt [IN] device
1151  */
1152 int mdt_hsm_cdt_stop(struct mdt_device *mdt)
1153 {
1154         struct coordinator *cdt = &mdt->mdt_coordinator;
1155         int rc;
1156
1157         ENTRY;
1158         /* stop coordinator thread */
1159         rc = set_cdt_state(cdt, CDT_STOPPING);
1160         if (rc == 0) {
1161                 kthread_stop(cdt->cdt_task);
1162                 cdt->cdt_task = NULL;
1163                 set_cdt_state(cdt, CDT_STOPPED);
1164         }
1165
1166         RETURN(rc);
1167 }
1168
1169 static int mdt_hsm_set_exists(struct mdt_thread_info *mti,
1170                               const struct lu_fid *fid,
1171                               u32 archive_id)
1172 {
1173         struct mdt_object *obj;
1174         struct md_hsm mh;
1175         int rc;
1176
1177         obj = mdt_hsm_get_md_hsm(mti, fid, &mh);
1178         if (IS_ERR(obj))
1179                 GOTO(out, rc = PTR_ERR(obj));
1180
1181         if (mh.mh_flags & HS_EXISTS &&
1182             mh.mh_arch_id == archive_id)
1183                 GOTO(out_obj, rc = 0);
1184
1185         mh.mh_flags |= HS_EXISTS;
1186         mh.mh_arch_id = archive_id;
1187         rc = mdt_hsm_attr_set(mti, obj, &mh);
1188
1189 out_obj:
1190         mdt_object_put(mti->mti_env, obj);
1191 out:
1192         return rc;
1193 }
1194
1195 /**
1196  * register all requests from an hal in the memory list
1197  * \param mti [IN] context
1198  * \param hal [IN] request
1199  * \param uuid [OUT] in case of CANCEL, the uuid of the agent
1200  *  which is running the CT
1201  * \retval 0 success
1202  * \retval -ve failure
1203  */
1204 int mdt_hsm_add_hal(struct mdt_thread_info *mti,
1205                     struct hsm_action_list *hal, struct obd_uuid *uuid)
1206 {
1207         struct mdt_device       *mdt = mti->mti_mdt;
1208         struct coordinator      *cdt = &mdt->mdt_coordinator;
1209         struct hsm_action_item  *hai;
1210         int                      rc = 0, i;
1211         ENTRY;
1212
1213         /* register request in memory list */
1214         hai = hai_first(hal);
1215         for (i = 0; i < hal->hal_count; i++, hai = hai_next(hai)) {
1216                 struct cdt_agent_req *car;
1217
1218                 /* in case of a cancel request, we first mark the ondisk
1219                  * record of the request we want to stop as canceled
1220                  * this does not change the cancel record
1221                  * it will be done when updating the request status
1222                  */
1223                 if (hai->hai_action == HSMA_CANCEL) {
1224                         struct hsm_record_update update = {
1225                                 .cookie = hai->hai_cookie,
1226                                 .status = ARS_CANCELED,
1227                         };
1228
1229                         rc = mdt_agent_record_update(mti->mti_env, mti->mti_mdt,
1230                                                      &update, 1);
1231                         if (rc) {
1232                                 CERROR("%s: mdt_agent_record_update() failed, "
1233                                        "rc=%d, cannot update status to %s "
1234                                        "for cookie %#llx\n",
1235                                        mdt_obd_name(mdt), rc,
1236                                        agent_req_status2name(ARS_CANCELED),
1237                                        hai->hai_cookie);
1238                                 GOTO(out, rc);
1239                         }
1240
1241                         /* find the running request to set it canceled */
1242                         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
1243                         if (car != NULL) {
1244                                 car->car_canceled = 1;
1245                                 /* uuid has to be changed to the one running the
1246                                 * request to cancel */
1247                                 *uuid = car->car_uuid;
1248                                 mdt_cdt_put_request(car);
1249                         }
1250                         /* no need to memorize cancel request
1251                          * this also avoid a deadlock when we receive
1252                          * a purge all requests command
1253                          */
1254                         continue;
1255                 }
1256
1257                 if (hai->hai_action == HSMA_ARCHIVE) {
1258                         rc = mdt_hsm_set_exists(mti, &hai->hai_fid,
1259                                                 hal->hal_archive_id);
1260                         if (rc == -ENOENT)
1261                                 continue;
1262                         else if (rc < 0)
1263                                 GOTO(out, rc);
1264                 }
1265
1266                 car = mdt_cdt_alloc_request(hal->hal_archive_id, hal->hal_flags,
1267                                             uuid, hai);
1268                 if (IS_ERR(car))
1269                         GOTO(out, rc = PTR_ERR(car));
1270
1271                 rc = mdt_cdt_add_request(cdt, car);
1272                 if (rc != 0)
1273                         mdt_cdt_free_request(car);
1274         }
1275 out:
1276         RETURN(rc);
1277 }
1278
1279 /**
1280  * swap layouts between 2 fids
1281  * \param mti [IN] context
1282  * \param obj [IN]
1283  * \param dfid [IN]
1284  * \param mh_common [IN] MD HSM
1285  */
1286 static int hsm_swap_layouts(struct mdt_thread_info *mti,
1287                             struct mdt_object *obj, const struct lu_fid *dfid,
1288                             struct md_hsm *mh_common)
1289 {
1290         struct mdt_object       *dobj;
1291         struct mdt_lock_handle  *dlh;
1292         int                      rc;
1293         ENTRY;
1294
1295         if (!mdt_object_exists(obj))
1296                 GOTO(out, rc = -ENOENT);
1297
1298         /* we already have layout lock on obj so take only
1299          * on dfid */
1300         dlh = &mti->mti_lh[MDT_LH_OLD];
1301         mdt_lock_reg_init(dlh, LCK_EX);
1302         dobj = mdt_object_find_lock(mti, dfid, dlh, MDS_INODELOCK_LAYOUT);
1303         if (IS_ERR(dobj))
1304                 GOTO(out, rc = PTR_ERR(dobj));
1305
1306         /* if copy tool closes the volatile before sending the final
1307          * progress through llapi_hsm_copy_end(), all the objects
1308          * are removed and mdd_swap_layout LBUG */
1309         if (!mdt_object_exists(dobj)) {
1310                 CERROR("%s: Copytool has closed volatile file "DFID"\n",
1311                        mdt_obd_name(mti->mti_mdt), PFID(dfid));
1312                 GOTO(out_dobj, rc = -ENOENT);
1313         }
1314         /* Since we only handle restores here, unconditionally use
1315          * SWAP_LAYOUTS_MDS_HSM flag to ensure original layout will
1316          * be preserved in case of failure during swap_layout and not
1317          * leave a file in an intermediate but incoherent state.
1318          * But need to setup HSM xattr of data FID before, reuse
1319          * mti and mh presets for FID in hsm_cdt_request_completed(),
1320          * only need to clear RELEASED and DIRTY.
1321          */
1322         mh_common->mh_flags &= ~(HS_RELEASED | HS_DIRTY);
1323         rc = mdt_hsm_attr_set(mti, dobj, mh_common);
1324         if (rc == 0)
1325                 rc = mo_swap_layouts(mti->mti_env,
1326                                      mdt_object_child(obj),
1327                                      mdt_object_child(dobj),
1328                                      SWAP_LAYOUTS_MDS_HSM);
1329         if (rc == 0) {
1330                 rc = mdt_lsom_downgrade(mti, obj);
1331                 if (rc)
1332                         CDEBUG(D_INODE,
1333                                "%s: File fid="DFID" SOM "
1334                                "downgrade failed, rc = %d\n",
1335                                mdt_obd_name(mti->mti_mdt),
1336                                PFID(mdt_object_fid(obj)), rc);
1337         }
1338 out_dobj:
1339         mdt_object_unlock_put(mti, dobj, dlh, 1);
1340 out:
1341         RETURN(rc);
1342 }
1343
1344 /**
1345  * update status of a completed request
1346  * \param mti [IN] context
1347  * \param pgs [IN] progress of the copy tool
1348  * \retval 0 success
1349  * \retval -ve failure
1350  */
1351 static int hsm_cdt_request_completed(struct mdt_thread_info *mti,
1352                                      struct hsm_progress_kernel *pgs,
1353                                      const struct cdt_agent_req *car,
1354                                      enum agent_req_status *status)
1355 {
1356         const struct lu_env *env = mti->mti_env;
1357         struct mdt_device *mdt = mti->mti_mdt;
1358         struct coordinator *cdt = &mdt->mdt_coordinator;
1359         struct mdt_object *obj = NULL;
1360         enum changelog_rec_flags clf_flags = 0;
1361         struct md_hsm mh;
1362         bool is_mh_changed;
1363         bool need_changelog = true;
1364         int rc = 0;
1365
1366         ENTRY;
1367         /* default is to retry */
1368         *status = ARS_WAITING;
1369
1370         /* find object by FID, mdt_hsm_get_md_hsm() returns obj or err
1371          * if error/removed continue anyway to get correct reporting done */
1372         obj = mdt_hsm_get_md_hsm(mti, &car->car_hai->hai_fid, &mh);
1373         /* we will update MD HSM only if needed */
1374         is_mh_changed = false;
1375
1376         /* no need to change mh->mh_arch_id
1377          * mdt_hsm_get_md_hsm() got it from disk and it is still valid
1378          */
1379         if (pgs->hpk_errval != 0) {
1380                 switch (pgs->hpk_errval) {
1381                 case ENOSYS:
1382                         /* the copy tool does not support cancel
1383                          * so the cancel request is failed
1384                          * As we cannot distinguish a cancel progress
1385                          * from another action progress (they have the
1386                          * same cookie), we suppose here the CT returns
1387                          * ENOSYS only if does not support cancel
1388                          */
1389                         /* this can also happen when cdt calls it to
1390                          * for a timed out request */
1391                         *status = ARS_FAILED;
1392                         /* to have a cancel event in changelog */
1393                         pgs->hpk_errval = ECANCELED;
1394                         break;
1395                 case ECANCELED:
1396                         /* the request record has already been set to
1397                          * ARS_CANCELED, this set the cancel request
1398                          * to ARS_SUCCEED */
1399                         *status = ARS_SUCCEED;
1400                         break;
1401                 default:
1402                         /* retry only if current policy or requested, and
1403                          * object is not on error/removed */
1404                         *status = (cdt->cdt_policy & CDT_NORETRY_ACTION ||
1405                                    !(pgs->hpk_flags & HP_FLAG_RETRY) ||
1406                                    IS_ERR(obj)) ? ARS_FAILED : ARS_WAITING;
1407                         break;
1408                 }
1409
1410                 if (pgs->hpk_errval > CLF_HSM_MAXERROR) {
1411                         CERROR("%s: Request %#llx on "DFID
1412                                " failed, error code %d too large\n",
1413                                mdt_obd_name(mdt),
1414                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1415                                pgs->hpk_errval);
1416                         hsm_set_cl_error(&clf_flags, CLF_HSM_ERROVERFLOW);
1417                         rc = -EINVAL;
1418                 } else {
1419                         hsm_set_cl_error(&clf_flags, pgs->hpk_errval);
1420                 }
1421
1422                 switch (car->car_hai->hai_action) {
1423                 case HSMA_ARCHIVE:
1424                         hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
1425                         break;
1426                 case HSMA_RESTORE:
1427                         hsm_set_cl_event(&clf_flags, HE_RESTORE);
1428                         break;
1429                 case HSMA_REMOVE:
1430                         hsm_set_cl_event(&clf_flags, HE_REMOVE);
1431                         break;
1432                 case HSMA_CANCEL:
1433                         hsm_set_cl_event(&clf_flags, HE_CANCEL);
1434                         CERROR("%s: Failed request %#llx on "DFID
1435                                " cannot be a CANCEL\n",
1436                                mdt_obd_name(mdt),
1437                                pgs->hpk_cookie,
1438                                PFID(&pgs->hpk_fid));
1439                         break;
1440                 default:
1441                         CERROR("%s: Failed request %#llx on "DFID
1442                                " %d is an unknown action\n",
1443                                mdt_obd_name(mdt),
1444                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1445                                car->car_hai->hai_action);
1446                         rc = -EINVAL;
1447                         break;
1448                 }
1449         } else {
1450                 *status = ARS_SUCCEED;
1451                 switch (car->car_hai->hai_action) {
1452                 case HSMA_ARCHIVE:
1453                         hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
1454                         /* set ARCHIVE keep EXIST and clear LOST and
1455                          * DIRTY */
1456                         mh.mh_arch_ver = pgs->hpk_data_version;
1457                         mh.mh_flags |= HS_ARCHIVED;
1458                         mh.mh_flags &= ~(HS_LOST|HS_DIRTY);
1459                         is_mh_changed = true;
1460                         break;
1461                 case HSMA_RESTORE:
1462                         hsm_set_cl_event(&clf_flags, HE_RESTORE);
1463
1464                         /* do not clear RELEASED and DIRTY here
1465                          * this will occur in hsm_swap_layouts()
1466                          */
1467
1468                         /* Restoring has changed the file version on
1469                          * disk. */
1470                         mh.mh_arch_ver = pgs->hpk_data_version;
1471                         is_mh_changed = true;
1472                         break;
1473                 case HSMA_REMOVE:
1474                         hsm_set_cl_event(&clf_flags, HE_REMOVE);
1475                         /* clear ARCHIVED EXISTS and LOST */
1476                         mh.mh_flags &= ~(HS_ARCHIVED | HS_EXISTS | HS_LOST);
1477                         is_mh_changed = true;
1478                         break;
1479                 case HSMA_CANCEL:
1480                         hsm_set_cl_event(&clf_flags, HE_CANCEL);
1481                         CERROR("%s: Successful request %#llx on "DFID" cannot be a CANCEL\n",
1482                                mdt_obd_name(mdt),
1483                                pgs->hpk_cookie,
1484                                PFID(&pgs->hpk_fid));
1485                         break;
1486                 default:
1487                         CERROR("%s: Successful request %#llx on "DFID" %d is an unknown action\n",
1488                                mdt_obd_name(mdt),
1489                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1490                                car->car_hai->hai_action);
1491                         rc = -EINVAL;
1492                         break;
1493                 }
1494         }
1495
1496         /* rc != 0 means error when analysing action, it may come from
1497          * a crasy CT no need to manage DIRTY
1498          * and if mdt_hsm_get_md_hsm() has returned an error, mh has not been
1499          * filled
1500          */
1501         if (rc == 0 && !IS_ERR(obj))
1502                 hsm_set_cl_flags(&clf_flags,
1503                                  mh.mh_flags & HS_DIRTY ? CLF_HSM_DIRTY : 0);
1504
1505         /* unlock is done later, after layout lock management */
1506         if (is_mh_changed && !IS_ERR(obj))
1507                 rc = mdt_hsm_attr_set(mti, obj, &mh);
1508
1509         /* we give back layout lock only if restore was successful or
1510          * if no retry will be attempted and if object is still alive,
1511          * in other cases we just unlock the object */
1512         if (car->car_hai->hai_action == HSMA_RESTORE) {
1513                 struct mdt_lock_handle *lh;
1514
1515                 /* restore in data FID done, we swap the layouts
1516                  * only if restore is successful */
1517                 if (pgs->hpk_errval == 0 && !IS_ERR(obj)) {
1518                         rc = hsm_swap_layouts(mti, obj, &car->car_hai->hai_dfid,
1519                                               &mh);
1520                         if (rc) {
1521                                 if (cdt->cdt_policy & CDT_NORETRY_ACTION)
1522                                         *status = ARS_FAILED;
1523                                 pgs->hpk_errval = -rc;
1524                         }
1525                 }
1526                 /* we have to retry, so keep layout lock */
1527                 if (*status == ARS_WAITING)
1528                         GOTO(out, rc);
1529
1530                 /* restore special case, need to create ChangeLog record
1531                  * before to give back layout lock to avoid concurrent
1532                  * file updater to post out of order ChangeLog */
1533                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
1534                              &car->car_hai->hai_fid);
1535                 need_changelog = false;
1536
1537                 cdt_restore_handle_del(mti, cdt, &car->car_hai->hai_fid);
1538                 if (!IS_ERR_OR_NULL(obj)) {
1539                         /* flush UPDATE lock so attributes are upadated */
1540                         lh = &mti->mti_lh[MDT_LH_OLD];
1541                         mdt_lock_reg_init(lh, LCK_EX);
1542                         mdt_object_lock(mti, obj, lh, MDS_INODELOCK_UPDATE);
1543                         mdt_object_unlock(mti, obj, lh, 1);
1544                 }
1545         }
1546
1547         GOTO(out, rc);
1548
1549 out:
1550         /* always add a ChangeLog record */
1551         if (need_changelog)
1552                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
1553                              &car->car_hai->hai_fid);
1554
1555         if (!IS_ERR(obj))
1556                 mdt_object_put(mti->mti_env, obj);
1557
1558         RETURN(rc);
1559 }
1560
1561 /**
1562  * update status of a request
1563  * \param mti [IN] context
1564  * \param pgs [IN] progress of the copy tool
1565  * \retval 0 success
1566  * \retval -ve failure
1567  */
1568 int mdt_hsm_update_request_state(struct mdt_thread_info *mti,
1569                                  struct hsm_progress_kernel *pgs)
1570 {
1571         struct mdt_device       *mdt = mti->mti_mdt;
1572         struct coordinator      *cdt = &mdt->mdt_coordinator;
1573         struct cdt_agent_req    *car;
1574         int                      rc = 0;
1575         ENTRY;
1576
1577         /* no coordinator started, so we cannot serve requests */
1578         if (cdt->cdt_state == CDT_STOPPED)
1579                 RETURN(-EAGAIN);
1580
1581         /* first do sanity checks */
1582         car = mdt_cdt_update_request(cdt, pgs);
1583         if (IS_ERR(car)) {
1584                 CERROR("%s: Cannot find running request for cookie %#llx"
1585                        " on fid="DFID"\n",
1586                        mdt_obd_name(mdt),
1587                        pgs->hpk_cookie, PFID(&pgs->hpk_fid));
1588
1589                 RETURN(PTR_ERR(car));
1590         }
1591
1592         CDEBUG(D_HSM, "Progress received for fid="DFID" cookie=%#llx"
1593                       " action=%s flags=%d err=%d fid="DFID" dfid="DFID"\n",
1594                       PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1595                       hsm_copytool_action2name(car->car_hai->hai_action),
1596                       pgs->hpk_flags, pgs->hpk_errval,
1597                       PFID(&car->car_hai->hai_fid),
1598                       PFID(&car->car_hai->hai_dfid));
1599
1600         /* progress is done on FID or data FID depending of the action and
1601          * of the copy progress */
1602         /* for restore progress is used to send back the data FID to cdt */
1603         if (car->car_hai->hai_action == HSMA_RESTORE &&
1604             lu_fid_eq(&car->car_hai->hai_fid, &car->car_hai->hai_dfid))
1605                 car->car_hai->hai_dfid = pgs->hpk_fid;
1606
1607         if ((car->car_hai->hai_action == HSMA_RESTORE ||
1608              car->car_hai->hai_action == HSMA_ARCHIVE) &&
1609             (!lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_dfid) &&
1610              !lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_fid))) {
1611                 CERROR("%s: Progress on "DFID" for cookie %#llx"
1612                        " does not match request FID "DFID" nor data FID "
1613                        DFID"\n",
1614                        mdt_obd_name(mdt),
1615                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1616                        PFID(&car->car_hai->hai_fid),
1617                        PFID(&car->car_hai->hai_dfid));
1618                 GOTO(out, rc = -EINVAL);
1619         }
1620
1621         if (pgs->hpk_errval != 0 && !(pgs->hpk_flags & HP_FLAG_COMPLETED)) {
1622                 CERROR("%s: Progress on "DFID" for cookie %#llx action=%s"
1623                        " is not coherent (err=%d and not completed"
1624                        " (flags=%d))\n",
1625                        mdt_obd_name(mdt),
1626                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1627                        hsm_copytool_action2name(car->car_hai->hai_action),
1628                        pgs->hpk_errval, pgs->hpk_flags);
1629                 GOTO(out, rc = -EINVAL);
1630         }
1631
1632         /* now progress is valid */
1633
1634         /* we use a root like ucred */
1635         hsm_init_ucred(mdt_ucred(mti));
1636
1637         if (pgs->hpk_flags & HP_FLAG_COMPLETED) {
1638                 enum agent_req_status status;
1639                 struct hsm_record_update update;
1640                 int rc1;
1641
1642                 rc = hsm_cdt_request_completed(mti, pgs, car, &status);
1643
1644                 CDEBUG(D_HSM, "updating record: fid="DFID" cookie=%#llx action=%s "
1645                               "status=%s\n",
1646                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1647                        hsm_copytool_action2name(car->car_hai->hai_action),
1648                        agent_req_status2name(status));
1649
1650                 /* update record first (LU-9075) */
1651                 update.cookie = pgs->hpk_cookie;
1652                 update.status = status;
1653
1654                 rc1 = mdt_agent_record_update(mti->mti_env, mdt,
1655                                               &update, 1);
1656                 if (rc1)
1657                         CERROR("%s: mdt_agent_record_update() failed,"
1658                                " rc=%d, cannot update status to %s"
1659                                " for cookie %#llx\n",
1660                                mdt_obd_name(mdt), rc1,
1661                                agent_req_status2name(status),
1662                                pgs->hpk_cookie);
1663                 rc = (rc != 0 ? rc : rc1);
1664
1665                 /* then remove request from memory list (LU-9075) */
1666                 mdt_cdt_remove_request(cdt, pgs->hpk_cookie);
1667
1668                 /* ct has completed a request, so a slot is available,
1669                  * signal the coordinator to find new work */
1670                 mdt_hsm_cdt_event(cdt);
1671         } else {
1672                 /* if copytool send a progress on a canceled request
1673                  * we inform copytool it should stop
1674                  */
1675                 if (car->car_canceled == 1)
1676                         rc = -ECANCELED;
1677         }
1678         GOTO(out, rc);
1679
1680 out:
1681         /* remove ref got from mdt_cdt_update_request() */
1682         mdt_cdt_put_request(car);
1683
1684         return rc;
1685 }
1686
1687
1688 /**
1689  * data passed to llog_cat_process() callback
1690  * to cancel requests
1691  */
1692 struct hsm_cancel_all_data {
1693         struct mdt_device       *mdt;
1694 };
1695
1696 /**
1697  *  llog_cat_process() callback, used to:
1698  *  - purge all requests
1699  * \param env [IN] environment
1700  * \param llh [IN] llog handle
1701  * \param hdr [IN] llog record
1702  * \param data [IN] cb data = struct hsm_cancel_all_data
1703  * \retval 0 success
1704  * \retval -ve failure
1705  */
1706 static int mdt_cancel_all_cb(const struct lu_env *env,
1707                              struct llog_handle *llh,
1708                              struct llog_rec_hdr *hdr, void *data)
1709 {
1710         struct llog_agent_req_rec       *larr;
1711         struct hsm_cancel_all_data      *hcad;
1712         int                              rc = 0;
1713         ENTRY;
1714
1715         larr = (struct llog_agent_req_rec *)hdr;
1716         hcad = data;
1717         if (larr->arr_status == ARS_WAITING ||
1718             larr->arr_status == ARS_STARTED) {
1719                 larr->arr_status = ARS_CANCELED;
1720                 larr->arr_req_change = ktime_get_real_seconds();
1721                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
1722         }
1723
1724         RETURN(rc);
1725 }
1726
1727 /**
1728  * cancel all actions
1729  * \param obd [IN] MDT device
1730  */
1731 static int hsm_cancel_all_actions(struct mdt_device *mdt)
1732 {
1733         struct lu_env                    env;
1734         struct lu_context                session;
1735         struct mdt_thread_info          *mti;
1736         struct coordinator              *cdt = &mdt->mdt_coordinator;
1737         struct cdt_agent_req            *car;
1738         struct hsm_action_list          *hal = NULL;
1739         struct hsm_action_item          *hai;
1740         struct hsm_cancel_all_data       hcad;
1741         int                              hal_sz = 0, hal_len, rc;
1742         enum cdt_states                  old_state;
1743         ENTRY;
1744
1745         rc = lu_env_init(&env, LCT_MD_THREAD);
1746         if (rc < 0)
1747                 RETURN(rc);
1748
1749         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1750         rc = lu_context_init(&session, LCT_SERVER_SESSION);
1751         if (rc < 0)
1752                 GOTO(out_env, rc);
1753
1754         lu_context_enter(&session);
1755         env.le_ses = &session;
1756
1757         mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
1758         LASSERT(mti != NULL);
1759
1760         mti->mti_env = &env;
1761         mti->mti_mdt = mdt;
1762
1763         hsm_init_ucred(mdt_ucred(mti));
1764
1765         mutex_lock(&cdt->cdt_state_lock);
1766         old_state = cdt->cdt_state;
1767
1768         /* disable coordinator */
1769         rc = set_cdt_state_locked(cdt, CDT_DISABLE);
1770         if (rc)
1771                 GOTO(out_cdt_state_unlock, rc);
1772
1773         /* send cancel to all running requests */
1774         down_read(&cdt->cdt_request_lock);
1775         list_for_each_entry(car, &cdt->cdt_request_list, car_request_list) {
1776                 mdt_cdt_get_request(car);
1777                 /* request is not yet removed from list, it will be done
1778                  * when copytool will return progress
1779                  */
1780
1781                 if (car->car_hai->hai_action == HSMA_CANCEL) {
1782                         mdt_cdt_put_request(car);
1783                         continue;
1784                 }
1785
1786                 /* needed size */
1787                 hal_len = sizeof(*hal) + cfs_size_round(MTI_NAME_MAXLEN + 1) +
1788                           cfs_size_round(car->car_hai->hai_len);
1789
1790                 if (hal_len > hal_sz && hal_sz > 0) {
1791                         /* not enough room, free old buffer */
1792                         OBD_FREE(hal, hal_sz);
1793                         hal = NULL;
1794                 }
1795
1796                 /* empty buffer, allocate one */
1797                 if (hal == NULL) {
1798                         hal_sz = hal_len;
1799                         OBD_ALLOC(hal, hal_sz);
1800                         if (hal == NULL) {
1801                                 mdt_cdt_put_request(car);
1802                                 up_read(&cdt->cdt_request_lock);
1803                                 GOTO(out_cdt_state, rc = -ENOMEM);
1804                         }
1805                 }
1806
1807                 hal->hal_version = HAL_VERSION;
1808                 obd_uuid2fsname(hal->hal_fsname, mdt_obd_name(mdt),
1809                                 MTI_NAME_MAXLEN);
1810                 hal->hal_fsname[MTI_NAME_MAXLEN] = '\0';
1811                 hal->hal_archive_id = car->car_archive_id;
1812                 hal->hal_flags = car->car_flags;
1813                 hal->hal_count = 0;
1814
1815                 hai = hai_first(hal);
1816                 memcpy(hai, car->car_hai, car->car_hai->hai_len);
1817                 hai->hai_action = HSMA_CANCEL;
1818                 hal->hal_count = 1;
1819
1820                 /* it is possible to safely call mdt_hsm_agent_send()
1821                  * (ie without a deadlock on cdt_request_lock), because the
1822                  * write lock is taken only if we are not in purge mode
1823                  * (mdt_hsm_agent_send() does not call mdt_cdt_add_request()
1824                  *   nor mdt_cdt_remove_request())
1825                  */
1826                 /* no conflict with cdt thread because cdt is disable and we
1827                  * have the request lock */
1828                 mdt_hsm_agent_send(mti, hal, 1);
1829
1830                 mdt_cdt_put_request(car);
1831         }
1832         up_read(&cdt->cdt_request_lock);
1833
1834         if (hal != NULL)
1835                 OBD_FREE(hal, hal_sz);
1836
1837         /* cancel all on-disk records */
1838         hcad.mdt = mdt;
1839
1840         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt, mdt_cancel_all_cb,
1841                               &hcad, 0, 0, WRITE);
1842 out_cdt_state:
1843         /* Enable coordinator, unless the coordinator was stopping. */
1844         set_cdt_state_locked(cdt, old_state);
1845 out_cdt_state_unlock:
1846         mutex_unlock(&cdt->cdt_state_lock);
1847
1848         lu_context_exit(&session);
1849         lu_context_fini(&session);
1850 out_env:
1851         lu_env_fini(&env);
1852
1853         RETURN(rc);
1854 }
1855
1856 /**
1857  * check if a request is compatible with file status
1858  * \param hai [IN] request description
1859  * \param archive_id [IN] request archive id
1860  * \param rq_flags [IN] request flags
1861  * \param hsm [IN] file HSM metadata
1862  * \retval boolean
1863  */
1864 bool mdt_hsm_is_action_compat(const struct hsm_action_item *hai,
1865                               u32 archive_id, u64 rq_flags,
1866                               const struct md_hsm *hsm)
1867 {
1868         int      is_compat = false;
1869         int      hsm_flags;
1870         ENTRY;
1871
1872         hsm_flags = hsm->mh_flags;
1873         switch (hai->hai_action) {
1874         case HSMA_ARCHIVE:
1875                 if (!(hsm_flags & HS_NOARCHIVE) &&
1876                     (hsm_flags & HS_DIRTY || !(hsm_flags & HS_ARCHIVED)))
1877                         is_compat = true;
1878
1879                 if (hsm_flags & HS_EXISTS &&
1880                     archive_id != 0 &&
1881                     archive_id != hsm->mh_arch_id)
1882                         is_compat = false;
1883
1884                 break;
1885         case HSMA_RESTORE:
1886                 if (!(hsm_flags & HS_DIRTY) && (hsm_flags & HS_RELEASED) &&
1887                     hsm_flags & HS_ARCHIVED && !(hsm_flags & HS_LOST))
1888                         is_compat = true;
1889                 break;
1890         case HSMA_REMOVE:
1891                 if (!(hsm_flags & HS_RELEASED) &&
1892                     (hsm_flags & (HS_ARCHIVED | HS_EXISTS)))
1893                         is_compat = true;
1894                 break;
1895         case HSMA_CANCEL:
1896                 is_compat = true;
1897                 break;
1898         }
1899         CDEBUG(D_HSM, "fid="DFID" action=%s flags=%#llx"
1900                       " extent=%#llx-%#llx hsm_flags=%.8X %s\n",
1901                       PFID(&hai->hai_fid),
1902                       hsm_copytool_action2name(hai->hai_action), rq_flags,
1903                       hai->hai_extent.offset, hai->hai_extent.length,
1904                       hsm->mh_flags,
1905                       (is_compat ? "compatible" : "uncompatible"));
1906
1907         RETURN(is_compat);
1908 }
1909
1910 /*
1911  * sysfs interface used to get/set HSM behaviour (cdt->cdt_policy)
1912  */
1913 static const struct {
1914         __u64            bit;
1915         char            *name;
1916         char            *nickname;
1917 } hsm_policy_names[] = {
1918         { CDT_NONBLOCKING_RESTORE,      "NonBlockingRestore",   "NBR"},
1919         { CDT_NORETRY_ACTION,           "NoRetryAction",        "NRA"},
1920         { 0 },
1921 };
1922
1923 /**
1924  * convert a policy name to a bit
1925  * \param name [IN] policy name
1926  * \retval 0 unknown
1927  * \retval   policy bit
1928  */
1929 static __u64 hsm_policy_str2bit(const char *name)
1930 {
1931         int      i;
1932
1933         for (i = 0; hsm_policy_names[i].bit != 0; i++)
1934                 if (strcmp(hsm_policy_names[i].nickname, name) == 0 ||
1935                     strcmp(hsm_policy_names[i].name, name) == 0)
1936                         return hsm_policy_names[i].bit;
1937         return 0;
1938 }
1939
1940 /**
1941  * convert a policy bit field to a string
1942  * \param mask [IN] policy bit field
1943  * \param hexa [IN] print mask before bit names
1944  * \param buffer [OUT] string
1945  * \param count [IN] size of buffer
1946  */
1947 static void hsm_policy_bit2str(struct seq_file *m, const __u64 mask,
1948                                 const bool hexa)
1949 {
1950         int      i, j;
1951         __u64    bit;
1952         ENTRY;
1953
1954         if (hexa)
1955                 seq_printf(m, "(%#llx) ", mask);
1956
1957         for (i = 0; i < CDT_POLICY_SHIFT_COUNT; i++) {
1958                 bit = (1ULL << i);
1959
1960                 for (j = 0; hsm_policy_names[j].bit != 0; j++) {
1961                         if (hsm_policy_names[j].bit == bit)
1962                                 break;
1963                 }
1964                 if (bit & mask)
1965                         seq_printf(m, "[%s] ", hsm_policy_names[j].name);
1966                 else
1967                         seq_printf(m, "%s ", hsm_policy_names[j].name);
1968         }
1969         /* remove last ' ' */
1970         m->count--;
1971         seq_putc(m, '\n');
1972 }
1973
1974 /* methods to read/write HSM policy flags */
1975 static int mdt_hsm_policy_seq_show(struct seq_file *m, void *data)
1976 {
1977         struct mdt_device       *mdt = m->private;
1978         struct coordinator      *cdt = &mdt->mdt_coordinator;
1979         ENTRY;
1980
1981         hsm_policy_bit2str(m, cdt->cdt_policy, false);
1982         RETURN(0);
1983 }
1984
1985 static ssize_t
1986 mdt_hsm_policy_seq_write(struct file *file, const char __user *buffer,
1987                          size_t count, loff_t *off)
1988 {
1989         struct seq_file         *m = file->private_data;
1990         struct mdt_device       *mdt = m->private;
1991         struct coordinator      *cdt = &mdt->mdt_coordinator;
1992         char                    *start, *token, sign;
1993         char                    *buf;
1994         __u64                    policy;
1995         __u64                    add_mask, remove_mask, set_mask;
1996         int                      rc;
1997         ENTRY;
1998
1999         if (count + 1 > PAGE_SIZE)
2000                 RETURN(-EINVAL);
2001
2002         OBD_ALLOC(buf, count + 1);
2003         if (buf == NULL)
2004                 RETURN(-ENOMEM);
2005
2006         if (copy_from_user(buf, buffer, count))
2007                 GOTO(out, rc = -EFAULT);
2008
2009         buf[count] = '\0';
2010
2011         start = buf;
2012         CDEBUG(D_HSM, "%s: receive new policy: '%s'\n", mdt_obd_name(mdt),
2013                start);
2014
2015         add_mask = remove_mask = set_mask = 0;
2016         do {
2017                 token = strsep(&start, "\n ");
2018                 sign = *token;
2019
2020                 if (sign == '\0')
2021                         continue;
2022
2023                 if (sign == '-' || sign == '+')
2024                         token++;
2025
2026                 policy = hsm_policy_str2bit(token);
2027                 if (policy == 0) {
2028                         CWARN("%s: '%s' is unknown, "
2029                               "supported policies are:\n", mdt_obd_name(mdt),
2030                               token);
2031                         hsm_policy_bit2str(m, 0, false);
2032                         GOTO(out, rc = -EINVAL);
2033                 }
2034                 switch (sign) {
2035                 case '-':
2036                         remove_mask |= policy;
2037                         break;
2038                 case '+':
2039                         add_mask |= policy;
2040                         break;
2041                 default:
2042                         set_mask |= policy;
2043                         break;
2044                 }
2045
2046         } while (start != NULL);
2047
2048         CDEBUG(D_HSM, "%s: new policy: rm=%#llx add=%#llx set=%#llx\n",
2049                mdt_obd_name(mdt), remove_mask, add_mask, set_mask);
2050
2051         /* if no sign in all string, it is a clear and set
2052          * if some sign found, all unsigned are converted
2053          * to add
2054          * P1 P2 = set to P1 and P2
2055          * P1 -P2 = add P1 clear P2 same as +P1 -P2
2056          */
2057         if (remove_mask == 0 && add_mask == 0) {
2058                 cdt->cdt_policy = set_mask;
2059         } else {
2060                 cdt->cdt_policy |= set_mask | add_mask;
2061                 cdt->cdt_policy &= ~remove_mask;
2062         }
2063
2064         GOTO(out, rc = count);
2065
2066 out:
2067         OBD_FREE(buf, count + 1);
2068         RETURN(rc);
2069 }
2070 LDEBUGFS_SEQ_FOPS(mdt_hsm_policy);
2071
2072 ssize_t loop_period_show(struct kobject *kobj, struct attribute *attr,
2073                          char *buf)
2074 {
2075         struct coordinator *cdt = container_of(kobj, struct coordinator,
2076                                                cdt_hsm_kobj);
2077
2078         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_loop_period);
2079 }
2080
2081 ssize_t loop_period_store(struct kobject *kobj, struct attribute *attr,
2082                           const char *buffer, size_t count)
2083 {
2084         struct coordinator *cdt = container_of(kobj, struct coordinator,
2085                                                cdt_hsm_kobj);
2086         unsigned int val;
2087         int rc;
2088
2089         rc = kstrtouint(buffer, 0, &val);
2090         if (rc)
2091                 return rc;
2092
2093         if (val != 0)
2094                 cdt->cdt_loop_period = val;
2095
2096         return val ? count : -EINVAL;
2097 }
2098 LUSTRE_RW_ATTR(loop_period);
2099
2100 ssize_t grace_delay_show(struct kobject *kobj, struct attribute *attr,
2101                          char *buf)
2102 {
2103         struct coordinator *cdt = container_of(kobj, struct coordinator,
2104                                                cdt_hsm_kobj);
2105
2106         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_grace_delay);
2107 }
2108
2109 ssize_t grace_delay_store(struct kobject *kobj, struct attribute *attr,
2110                           const char *buffer, size_t count)
2111 {
2112         struct coordinator *cdt = container_of(kobj, struct coordinator,
2113                                                cdt_hsm_kobj);
2114         unsigned int val;
2115         int rc;
2116
2117         rc = kstrtouint(buffer, 0, &val);
2118         if (rc)
2119                 return rc;
2120
2121         if (val != 0)
2122                 cdt->cdt_grace_delay = val;
2123
2124         return val ? count : -EINVAL;
2125 }
2126 LUSTRE_RW_ATTR(grace_delay);
2127
2128 ssize_t active_request_timeout_show(struct kobject *kobj,
2129                                     struct attribute *attr,
2130                                     char *buf)
2131 {
2132         struct coordinator *cdt = container_of(kobj, struct coordinator,
2133                                                cdt_hsm_kobj);
2134
2135         return scnprintf(buf, PAGE_SIZE, "%d\n", cdt->cdt_active_req_timeout);
2136 }
2137
2138 ssize_t active_request_timeout_store(struct kobject *kobj,
2139                                      struct attribute *attr,
2140                                      const char *buffer, size_t count)
2141 {
2142         struct coordinator *cdt = container_of(kobj, struct coordinator,
2143                                                cdt_hsm_kobj);
2144         unsigned int val;
2145         int rc;
2146
2147         rc = kstrtouint(buffer, 0, &val);
2148         if (rc)
2149                 return rc;
2150
2151         if (val != 0)
2152                 cdt->cdt_active_req_timeout = val;
2153
2154         return val ? count : -EINVAL;
2155 }
2156 LUSTRE_RW_ATTR(active_request_timeout);
2157
2158 ssize_t max_requests_show(struct kobject *kobj, struct attribute *attr,
2159                           char *buf)
2160 {
2161         struct coordinator *cdt = container_of(kobj, struct coordinator,
2162                                                cdt_hsm_kobj);
2163
2164         return scnprintf(buf, PAGE_SIZE, "%llu\n", cdt->cdt_max_requests);
2165 }
2166
2167 ssize_t max_requests_store(struct kobject *kobj, struct attribute *attr,
2168                            const char *buffer, size_t count)
2169 {
2170         struct coordinator *cdt = container_of(kobj, struct coordinator,
2171                                                cdt_hsm_kobj);
2172         unsigned long long val;
2173         int rc;
2174
2175         rc = kstrtoull(buffer, 0, &val);
2176         if (rc)
2177                 return rc;
2178
2179         if (val != 0)
2180                 cdt->cdt_max_requests = val;
2181
2182         return val ? count : -EINVAL;
2183 }
2184 LUSTRE_RW_ATTR(max_requests);
2185
2186 ssize_t default_archive_id_show(struct kobject *kobj, struct attribute *attr,
2187                                 char *buf)
2188 {
2189         struct coordinator *cdt = container_of(kobj, struct coordinator,
2190                                                cdt_hsm_kobj);
2191
2192         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_default_archive_id);
2193 }
2194
2195 ssize_t default_archive_id_store(struct kobject *kobj, struct attribute *attr,
2196                                  const char *buffer, size_t count)
2197 {
2198         struct coordinator *cdt = container_of(kobj, struct coordinator,
2199                                                cdt_hsm_kobj);
2200         unsigned int val;
2201         int rc;
2202
2203         rc = kstrtouint(buffer, 0, &val);
2204         if (rc)
2205                 return rc;
2206
2207         if (val != 0)
2208                 cdt->cdt_default_archive_id = val;
2209
2210         return val ? count : -EINVAL;
2211 }
2212 LUSTRE_RW_ATTR(default_archive_id);
2213
2214 /*
2215  * procfs write method for MDT/hsm_control
2216  * proc entry is in mdt directory so data is mdt obd_device pointer
2217  */
2218 #define CDT_ENABLE_CMD   "enabled"
2219 #define CDT_STOP_CMD     "shutdown"
2220 #define CDT_DISABLE_CMD  "disabled"
2221 #define CDT_PURGE_CMD    "purge"
2222 #define CDT_HELP_CMD     "help"
2223 #define CDT_MAX_CMD_LEN  10
2224
2225 ssize_t hsm_control_store(struct kobject *kobj, struct attribute *attr,
2226                           const char *buffer, size_t count)
2227 {
2228         struct obd_device *obd = container_of(kobj, struct obd_device,
2229                                               obd_kset.kobj);
2230         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
2231         struct coordinator *cdt = &(mdt->mdt_coordinator);
2232         int usage = 0;
2233         int rc = 0;
2234
2235         if (count == 0 || count >= CDT_MAX_CMD_LEN)
2236                 return -EINVAL;
2237
2238         if (strncmp(buffer, CDT_ENABLE_CMD, strlen(CDT_ENABLE_CMD)) == 0) {
2239                 if (cdt->cdt_state == CDT_DISABLE) {
2240                         rc = set_cdt_state(cdt, CDT_RUNNING);
2241                         mdt_hsm_cdt_event(cdt);
2242                         wake_up(&cdt->cdt_waitq);
2243                 } else {
2244                         rc = mdt_hsm_cdt_start(mdt);
2245                 }
2246         } else if (strncmp(buffer, CDT_STOP_CMD, strlen(CDT_STOP_CMD)) == 0) {
2247                 if ((cdt->cdt_state == CDT_STOPPING) ||
2248                     (cdt->cdt_state == CDT_STOPPED)) {
2249                         CERROR("%s: Coordinator already stopped\n",
2250                                mdt_obd_name(mdt));
2251                         rc = -EALREADY;
2252                 } else {
2253                         rc = mdt_hsm_cdt_stop(mdt);
2254                 }
2255         } else if (strncmp(buffer, CDT_DISABLE_CMD,
2256                            strlen(CDT_DISABLE_CMD)) == 0) {
2257                 if ((cdt->cdt_state == CDT_STOPPING) ||
2258                     (cdt->cdt_state == CDT_STOPPED)) {
2259                         CERROR("%s: Coordinator is stopped\n",
2260                                mdt_obd_name(mdt));
2261                         rc = -EINVAL;
2262                 } else {
2263                         rc = set_cdt_state(cdt, CDT_DISABLE);
2264                 }
2265         } else if (strncmp(buffer, CDT_PURGE_CMD,
2266                            strlen(CDT_PURGE_CMD)) == 0) {
2267                 rc = hsm_cancel_all_actions(mdt);
2268         } else if (strncmp(buffer, CDT_HELP_CMD,
2269                            strlen(CDT_HELP_CMD)) == 0) {
2270                 usage = 1;
2271         } else {
2272                 usage = 1;
2273                 rc = -EINVAL;
2274         }
2275
2276         if (usage == 1)
2277                 CERROR("%s: Valid coordinator control commands are: "
2278                        "%s %s %s %s %s\n", mdt_obd_name(mdt),
2279                        CDT_ENABLE_CMD, CDT_STOP_CMD, CDT_DISABLE_CMD,
2280                        CDT_PURGE_CMD, CDT_HELP_CMD);
2281
2282         if (rc)
2283                 RETURN(rc);
2284
2285         RETURN(count);
2286 }
2287
2288 ssize_t hsm_control_show(struct kobject *kobj, struct attribute *attr,
2289                          char *buf)
2290 {
2291         struct obd_device *obd = container_of(kobj, struct obd_device,
2292                                               obd_kset.kobj);
2293         struct coordinator *cdt;
2294
2295         cdt = &(mdt_dev(obd->obd_lu_dev)->mdt_coordinator);
2296
2297         return scnprintf(buf, PAGE_SIZE, "%s\n",
2298                          cdt_mdt_state2str(cdt->cdt_state));
2299 }
2300
2301 static int
2302 mdt_hsm_request_mask_show(struct seq_file *m, __u64 mask)
2303 {
2304         bool first = true;
2305         int i;
2306         ENTRY;
2307
2308         for (i = 0; i < 8 * sizeof(mask); i++) {
2309                 if (mask & (1UL << i)) {
2310                         seq_printf(m, "%s%s", first ? "" : " ",
2311                                    hsm_copytool_action2name(i));
2312                         first = false;
2313                 }
2314         }
2315         seq_putc(m, '\n');
2316
2317         RETURN(0);
2318 }
2319
2320 static int
2321 mdt_hsm_user_request_mask_seq_show(struct seq_file *m, void *data)
2322 {
2323         struct mdt_device *mdt = m->private;
2324         struct coordinator *cdt = &mdt->mdt_coordinator;
2325
2326         return mdt_hsm_request_mask_show(m, cdt->cdt_user_request_mask);
2327 }
2328
2329 static int
2330 mdt_hsm_group_request_mask_seq_show(struct seq_file *m, void *data)
2331 {
2332         struct mdt_device *mdt = m->private;
2333         struct coordinator *cdt = &mdt->mdt_coordinator;
2334
2335         return mdt_hsm_request_mask_show(m, cdt->cdt_group_request_mask);
2336 }
2337
2338 static int
2339 mdt_hsm_other_request_mask_seq_show(struct seq_file *m, void *data)
2340 {
2341         struct mdt_device *mdt = m->private;
2342         struct coordinator *cdt = &mdt->mdt_coordinator;
2343
2344         return mdt_hsm_request_mask_show(m, cdt->cdt_other_request_mask);
2345 }
2346
2347 static inline enum hsm_copytool_action
2348 hsm_copytool_name2action(const char *name)
2349 {
2350         if (strcasecmp(name, "NOOP") == 0)
2351                 return HSMA_NONE;
2352         else if (strcasecmp(name, "ARCHIVE") == 0)
2353                 return HSMA_ARCHIVE;
2354         else if (strcasecmp(name, "RESTORE") == 0)
2355                 return HSMA_RESTORE;
2356         else if (strcasecmp(name, "REMOVE") == 0)
2357                 return HSMA_REMOVE;
2358         else if (strcasecmp(name, "CANCEL") == 0)
2359                 return HSMA_CANCEL;
2360         else
2361                 return -1;
2362 }
2363
2364 static ssize_t
2365 mdt_write_hsm_request_mask(struct file *file, const char __user *user_buf,
2366                             size_t user_count, __u64 *mask)
2367 {
2368         char *buf, *pos, *name;
2369         size_t buf_size;
2370         __u64 new_mask = 0;
2371         int rc;
2372         ENTRY;
2373
2374         if (!(user_count < 4096))
2375                 RETURN(-ENOMEM);
2376
2377         buf_size = user_count + 1;
2378
2379         OBD_ALLOC(buf, buf_size);
2380         if (buf == NULL)
2381                 RETURN(-ENOMEM);
2382
2383         if (copy_from_user(buf, user_buf, buf_size - 1))
2384                 GOTO(out, rc = -EFAULT);
2385
2386         buf[buf_size - 1] = '\0';
2387
2388         pos = buf;
2389         while ((name = strsep(&pos, " \t\v\n")) != NULL) {
2390                 int action;
2391
2392                 if (*name == '\0')
2393                         continue;
2394
2395                 action = hsm_copytool_name2action(name);
2396                 if (action < 0)
2397                         GOTO(out, rc = -EINVAL);
2398
2399                 new_mask |= (1UL << action);
2400         }
2401
2402         *mask = new_mask;
2403         rc = user_count;
2404 out:
2405         OBD_FREE(buf, buf_size);
2406
2407         RETURN(rc);
2408 }
2409
2410 static ssize_t
2411 mdt_hsm_user_request_mask_seq_write(struct file *file, const char __user *buf,
2412                                         size_t count, loff_t *off)
2413 {
2414         struct seq_file         *m = file->private_data;
2415         struct mdt_device       *mdt = m->private;
2416         struct coordinator *cdt = &mdt->mdt_coordinator;
2417
2418         return mdt_write_hsm_request_mask(file, buf, count,
2419                                            &cdt->cdt_user_request_mask);
2420 }
2421
2422 static ssize_t
2423 mdt_hsm_group_request_mask_seq_write(struct file *file, const char __user *buf,
2424                                         size_t count, loff_t *off)
2425 {
2426         struct seq_file         *m = file->private_data;
2427         struct mdt_device       *mdt = m->private;
2428         struct coordinator      *cdt = &mdt->mdt_coordinator;
2429
2430         return mdt_write_hsm_request_mask(file, buf, count,
2431                                            &cdt->cdt_group_request_mask);
2432 }
2433
2434 static ssize_t
2435 mdt_hsm_other_request_mask_seq_write(struct file *file, const char __user *buf,
2436                                         size_t count, loff_t *off)
2437 {
2438         struct seq_file         *m = file->private_data;
2439         struct mdt_device       *mdt = m->private;
2440         struct coordinator      *cdt = &mdt->mdt_coordinator;
2441
2442         return mdt_write_hsm_request_mask(file, buf, count,
2443                                            &cdt->cdt_other_request_mask);
2444 }
2445
2446 static ssize_t remove_archive_on_last_unlink_show(struct kobject *kobj,
2447                                                   struct attribute *attr,
2448                                                   char *buf)
2449 {
2450         struct coordinator *cdt = container_of(kobj, struct coordinator,
2451                                                cdt_hsm_kobj);
2452
2453         return scnprintf(buf, PAGE_SIZE, "%u\n",
2454                          cdt->cdt_remove_archive_on_last_unlink);
2455 }
2456
2457 static ssize_t remove_archive_on_last_unlink_store(struct kobject *kobj,
2458                                                    struct attribute *attr,
2459                                                    const char *buffer,
2460                                                    size_t count)
2461 {
2462         struct coordinator *cdt = container_of(kobj, struct coordinator,
2463                                                cdt_hsm_kobj);
2464         bool val;
2465         int rc;
2466
2467         rc = kstrtobool(buffer, &val);
2468         if (rc < 0)
2469                 return rc;
2470
2471         cdt->cdt_remove_archive_on_last_unlink = val;
2472         return count;
2473 }
2474 LUSTRE_RW_ATTR(remove_archive_on_last_unlink);
2475
2476 LDEBUGFS_SEQ_FOPS(mdt_hsm_user_request_mask);
2477 LDEBUGFS_SEQ_FOPS(mdt_hsm_group_request_mask);
2478 LDEBUGFS_SEQ_FOPS(mdt_hsm_other_request_mask);
2479
2480 /* Read-only sysfs files for request counters */
2481 static ssize_t archive_count_show(struct kobject *kobj, struct attribute *attr,
2482                                   char *buf)
2483 {
2484         struct coordinator *cdt = container_of(kobj, struct coordinator,
2485                                                cdt_hsm_kobj);
2486
2487         return scnprintf(buf, PAGE_SIZE, "%d\n",
2488                          atomic_read(&cdt->cdt_archive_count));
2489 }
2490 LUSTRE_RO_ATTR(archive_count);
2491
2492 static ssize_t restore_count_show(struct kobject *kobj, struct attribute *attr,
2493                                   char *buf)
2494 {
2495         struct coordinator *cdt = container_of(kobj, struct coordinator,
2496                                                cdt_hsm_kobj);
2497
2498         return scnprintf(buf, PAGE_SIZE, "%d\n",
2499                          atomic_read(&cdt->cdt_restore_count));
2500 }
2501 LUSTRE_RO_ATTR(restore_count);
2502
2503 static ssize_t remove_count_show(struct kobject *kobj, struct attribute *attr,
2504                                  char *buf)
2505 {
2506         struct coordinator *cdt = container_of(kobj, struct coordinator,
2507                                                cdt_hsm_kobj);
2508
2509         return scnprintf(buf, PAGE_SIZE, "%d\n",
2510                          atomic_read(&cdt->cdt_remove_count));
2511 }
2512 LUSTRE_RO_ATTR(remove_count);
2513
2514 static struct ldebugfs_vars ldebugfs_mdt_hsm_vars[] = {
2515         { .name =       "agents",
2516           .fops =       &mdt_hsm_agent_fops                     },
2517         { .name =       "actions",
2518           .fops =       &mdt_hsm_actions_fops,
2519           .proc_mode =  0444                                    },
2520         { .name =       "policy",
2521           .fops =       &mdt_hsm_policy_fops                    },
2522         { .name =       "active_requests",
2523           .fops =       &mdt_hsm_active_requests_fops           },
2524         { .name =       "user_request_mask",
2525           .fops =       &mdt_hsm_user_request_mask_fops,        },
2526         { .name =       "group_request_mask",
2527           .fops =       &mdt_hsm_group_request_mask_fops,       },
2528         { .name =       "other_request_mask",
2529           .fops =       &mdt_hsm_other_request_mask_fops,       },
2530         { 0 }
2531 };
2532
2533 static struct attribute *hsm_attrs[] = {
2534         &lustre_attr_loop_period.attr,
2535         &lustre_attr_grace_delay.attr,
2536         &lustre_attr_active_request_timeout.attr,
2537         &lustre_attr_max_requests.attr,
2538         &lustre_attr_default_archive_id.attr,
2539         &lustre_attr_remove_archive_on_last_unlink.attr,
2540         &lustre_attr_archive_count.attr,
2541         &lustre_attr_restore_count.attr,
2542         &lustre_attr_remove_count.attr,
2543         NULL,
2544 };
2545
2546 static void hsm_kobj_release(struct kobject *kobj)
2547 {
2548         struct coordinator *cdt = container_of(kobj, struct coordinator,
2549                                                cdt_hsm_kobj);
2550
2551         debugfs_remove_recursive(cdt->cdt_debugfs_dir);
2552         cdt->cdt_debugfs_dir = NULL;
2553
2554         complete(&cdt->cdt_kobj_unregister);
2555 }
2556
2557 static struct kobj_type hsm_ktype = {
2558         .default_attrs  = hsm_attrs,
2559         .sysfs_ops      = &lustre_sysfs_ops,
2560         .release        = hsm_kobj_release,
2561 };
2562
2563 /**
2564  * create sysfs entries for coordinator
2565  * \param mdt [IN]
2566  * \retval 0 success
2567  * \retval -ve failure
2568  */
2569 int hsm_cdt_tunables_init(struct mdt_device *mdt)
2570 {
2571         struct coordinator *cdt = &mdt->mdt_coordinator;
2572         struct obd_device *obd = mdt2obd_dev(mdt);
2573         int rc;
2574
2575         init_completion(&cdt->cdt_kobj_unregister);
2576         rc = kobject_init_and_add(&cdt->cdt_hsm_kobj, &hsm_ktype,
2577                                   &obd->obd_kset.kobj, "%s", "hsm");
2578         if (rc) {
2579                 kobject_put(&cdt->cdt_hsm_kobj);
2580                 return rc;
2581         }
2582
2583         /* init debugfs entries, failure is not critical */
2584         cdt->cdt_debugfs_dir = debugfs_create_dir("hsm",
2585                                                   obd->obd_debugfs_entry);
2586         ldebugfs_add_vars(cdt->cdt_debugfs_dir, ldebugfs_mdt_hsm_vars, mdt);
2587
2588         return 0;
2589 }
2590
2591 /**
2592  * remove sysfs entries for coordinator
2593  *
2594  * @mdt
2595  */
2596 void hsm_cdt_tunables_fini(struct mdt_device *mdt)
2597 {
2598         struct coordinator *cdt = &mdt->mdt_coordinator;
2599
2600         kobject_put(&cdt->cdt_hsm_kobj);
2601         wait_for_completion(&cdt->cdt_kobj_unregister);
2602 }