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