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